code
stringlengths 38
801k
| repo_path
stringlengths 6
263
|
---|---|
const common = @import("../common.zig");
pub const NarcOffset = struct {
file: usize,
offset: usize,
};
pub const OverlayOffset = struct {
overlay: usize,
offset: usize,
};
pub const Info = struct {
game_title: [11:0]u8,
gamecode: [4]u8,
version: common.Version,
starters: [3][]const NarcOffset,
instant_text_patch: []const common.Patch,
type_effectiveness: OverlayOffset,
scripts: []const u8,
pokemons: []const u8,
evolutions: []const u8,
level_up_moves: []const u8,
moves: []const u8,
trainers: []const u8,
parties: []const u8,
wild_pokemons: []const u8,
itemdata: []const u8,
hidden_hollows: ?[]const u8,
map_file: []const u8,
map_headers: u16,
text: []const u8,
pokemon_names: u16,
pokedex_category_names: u16,
trainer_names: u16,
move_names: u16,
move_descriptions: u16,
ability_names: u16,
item_names: u16,
item_names_on_the_ground: u16,
item_descriptions: u16,
type_names: u16,
map_names: u16,
story: []const u8,
starter_choice: u16,
starter_choice_indexs: [3]usize,
};
pub const infos = [_]Info{
black2_info,
white2_info,
black_info,
white_info,
};
const black2_info = Info{
.game_title = "POKEMON B2\x00".*,
.gamecode = "IREO".*,
.version = .black2,
.starters = [_][]const NarcOffset{
&[_]NarcOffset{
NarcOffset{ .file = 854, .offset = 0x58B },
NarcOffset{ .file = 854, .offset = 0x590 },
NarcOffset{ .file = 854, .offset = 0x595 },
},
&[_]NarcOffset{
NarcOffset{ .file = 854, .offset = 0x5C0 },
NarcOffset{ .file = 854, .offset = 0x5C5 },
NarcOffset{ .file = 854, .offset = 0x5CA },
},
&[_]NarcOffset{
NarcOffset{ .file = 854, .offset = 0x5E2 },
NarcOffset{ .file = 854, .offset = 0x5E7 },
NarcOffset{ .file = 854, .offset = 0x5EC },
},
},
.instant_text_patch = &[_]common.Patch{
.{ .offset = 0x01e544, .replacement = "\xc0\x46\xc0\x46" },
.{ .offset = 0x01e5fc, .replacement = "\xc5\xd1" },
},
.type_effectiveness = .{ .overlay = 167, .offset = 0x3dc40 },
.scripts = "/a/0/5/6",
.pokemons = "/a/0/1/6",
.evolutions = "/a/0/1/9",
.level_up_moves = "/a/0/1/8",
.moves = "/a/0/2/1",
.trainers = "/a/0/9/1",
.parties = "/a/0/9/2",
.wild_pokemons = "/a/1/2/7",
.itemdata = "/a/0/2/4",
.hidden_hollows = "/a/2/7/3",
.map_file = "a/0/1/2",
.map_headers = 0,
.text = "a/0/0/2",
.pokemon_names = 90,
.pokedex_category_names = 464,
.trainer_names = 382,
.move_names = 403,
.move_descriptions = 402,
.ability_names = 374,
.item_names = 64,
.item_names_on_the_ground = 481,
.item_descriptions = 63,
.type_names = 489,
.map_names = 109,
.story = "/a/0/0/3",
.starter_choice = 169,
.starter_choice_indexs = .{ 37, 36, 35 },
};
const white2_info = Info{
.game_title = "POKEMON W2\x00".*,
.gamecode = "IRDO".*,
.version = .white2,
.starters = black2_info.starters,
.instant_text_patch = &[_]common.Patch{
.{ .offset = 0x01e570, .replacement = "\xc0\x46\xc0\x46" },
.{ .offset = 0x01e628, .replacement = "\xc5\xd1" },
},
.type_effectiveness = .{ .overlay = 167, .offset = 0x3dc40 },
.scripts = black2_info.scripts,
.pokemons = black2_info.pokemons,
.evolutions = black2_info.evolutions,
.level_up_moves = black2_info.level_up_moves,
.moves = black2_info.moves,
.trainers = black2_info.trainers,
.parties = black2_info.parties,
.wild_pokemons = black2_info.wild_pokemons,
.itemdata = black2_info.itemdata,
.hidden_hollows = black2_info.hidden_hollows,
.map_file = black2_info.map_file,
.map_headers = black2_info.map_headers,
.text = black2_info.text,
.pokemon_names = black2_info.pokemon_names,
.pokedex_category_names = black2_info.pokedex_category_names,
.trainer_names = black2_info.trainer_names,
.move_names = black2_info.move_names,
.move_descriptions = black2_info.move_descriptions,
.ability_names = black2_info.ability_names,
.item_names = black2_info.item_names,
.item_names_on_the_ground = black2_info.item_names_on_the_ground,
.item_descriptions = black2_info.item_descriptions,
.type_names = black2_info.type_names,
.map_names = black2_info.map_names,
.story = black2_info.story,
.starter_choice = black2_info.starter_choice,
.starter_choice_indexs = black2_info.starter_choice_indexs,
};
const black_info = Info{
.game_title = "POKEMON B\x00\x00".*,
.gamecode = "IRBO".*,
.version = .black,
.starters = [_][]const NarcOffset{
&[_]NarcOffset{
NarcOffset{ .file = 782, .offset = 0x27f },
NarcOffset{ .file = 782, .offset = 0x284 },
NarcOffset{ .file = 782, .offset = 0x361 },
NarcOffset{ .file = 782, .offset = 0x5FD },
NarcOffset{ .file = 304, .offset = 0x0F9 },
NarcOffset{ .file = 304, .offset = 0x19C },
},
&[_]NarcOffset{
NarcOffset{ .file = 782, .offset = 0x2af },
NarcOffset{ .file = 782, .offset = 0x2b4 },
NarcOffset{ .file = 782, .offset = 0x356 },
NarcOffset{ .file = 782, .offset = 0x5F2 },
NarcOffset{ .file = 304, .offset = 0x11C },
NarcOffset{ .file = 304, .offset = 0x1C4 },
},
&[_]NarcOffset{
NarcOffset{ .file = 782, .offset = 0x2cc },
NarcOffset{ .file = 782, .offset = 0x2d1 },
NarcOffset{ .file = 782, .offset = 0x338 },
NarcOffset{ .file = 782, .offset = 0x5D4 },
NarcOffset{ .file = 304, .offset = 0x12C },
NarcOffset{ .file = 304, .offset = 0x1D9 },
},
},
.instant_text_patch = &[_]common.Patch{
.{ .offset = 0x018fc0, .replacement = "\xc0\x46\xc0\x46" },
.{ .offset = 0x019078, .replacement = "\xc5\xd1" },
},
.type_effectiveness = .{ .overlay = 93, .offset = 0x3a37c },
.scripts = "/a/0/5/7",
.pokemons = black2_info.pokemons,
.evolutions = black2_info.evolutions,
.level_up_moves = black2_info.level_up_moves,
.moves = black2_info.moves,
.trainers = "/a/0/9/2",
.parties = "/a/0/9/3",
.wild_pokemons = "/a/1/2/6",
.itemdata = black2_info.itemdata,
.hidden_hollows = null,
.map_file = black2_info.map_file,
.map_headers = black2_info.map_headers,
.text = black2_info.text,
.pokemon_names = 70,
.pokedex_category_names = 260,
.trainer_names = 190,
.move_names = 203,
.move_descriptions = 202,
.ability_names = 182,
.item_names = 54,
.item_names_on_the_ground = 279,
.item_descriptions = 53,
.type_names = 287,
.map_names = 89,
.story = black2_info.story,
.starter_choice = 430,
.starter_choice_indexs = .{ 18, 17, 16 },
};
const white_info = Info{
.game_title = "POKEMON W\x00\x00".*,
.gamecode = "IRAO".*,
.version = .white,
.starters = black_info.starters,
.instant_text_patch = &[_]common.Patch{
.{ .offset = 0x018fdc, .replacement = "\xc0\x46\xc0\x46" },
.{ .offset = 0x019094, .replacement = "\xc5\xd1" },
},
.type_effectiveness = .{ .overlay = 93, .offset = 0x3a37c },
.scripts = black_info.scripts,
.pokemons = black_info.pokemons,
.evolutions = black_info.evolutions,
.level_up_moves = black_info.level_up_moves,
.moves = black_info.moves,
.trainers = black_info.trainers,
.parties = black_info.parties,
.wild_pokemons = black_info.wild_pokemons,
.itemdata = black_info.itemdata,
.hidden_hollows = black_info.hidden_hollows,
.map_file = black_info.map_file,
.map_headers = black_info.map_headers,
.text = black_info.text,
.pokemon_names = black_info.pokemon_names,
.pokedex_category_names = black_info.pokedex_category_names,
.trainer_names = black_info.trainer_names,
.move_names = black_info.move_names,
.move_descriptions = black_info.move_descriptions,
.ability_names = black_info.ability_names,
.item_names = black_info.item_names,
.item_names_on_the_ground = black_info.item_names_on_the_ground,
.item_descriptions = black_info.item_descriptions,
.type_names = black_info.type_names,
.map_names = black_info.map_names,
.story = black_info.story,
.starter_choice = black_info.starter_choice,
.starter_choice_indexs = black_info.starter_choice_indexs,
};
pub const hm_count = 6;
pub const hm_tm_prefix = "\x87\x03\x88\x03";
pub const tm_count = 95; | src/core/gen5/offsets.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const trait = std.meta.trait;
const vk = @import("../include/vk.zig");
const Render = @import("../lib.zig").Render;
const Context = @import("../backend/context.zig").Context;
const Pipeline = @import("../backend/pipeline.zig").Pipeline;
const RenderPass = @import("../backend/renderpass.zig").RenderPass;
const Framebuffer = @import("../backend/framebuffer.zig").Framebuffer;
const DescriptorSetLayout = @import("descriptor.zig").SetLayout;
const renderpass = @import("renderpass.zig");
pub const IObject = struct {
executeFn: fn (self: *const IObject, cb: vk.CommandBuffer, fb: Framebuffer) anyerror!void,
pub fn execute(self: *const IObject, cb: vk.CommandBuffer, fb: Framebuffer) !void {
try self.executeFn(self, cb, fb);
}
};
pub const State = struct {
kind: vk.PipelineBindPoint,
render_pass: type,
layout: Layout,
shader_stages: []const ShaderStage,
vertex_input_state: VertexInputState,
input_assembly_state: InputAssemblyState,
rasterizer_state: RasterizerState,
multisample_state: ?MultisampleState,
depth_stencil_state: ?DepthStencilState,
color_blend_state: ColorBlendState,
/// Creates a new state with the specified overrides
pub fn override(comptime self: *const State, comptime Override: anytype) State {
comptime var new = State{
.kind = self.kind,
.render_pass = self.render_pass,
.layout = self.layout,
.shader_stages = self.shader_stages,
.vertex_input_state = self.vertex_input_state,
.input_assembly_state = self.input_assembly_state,
.rasterizer_state = self.rasterizer_state,
.multisample_state = self.multisample_state,
.depth_stencil_state = self.depth_stencil_state,
.color_blend_state = self.color_blend_state,
};
comptime for (@typeInfo(@TypeOf(Override)).Struct.fields) |field, i| {
if (@hasField(State, field.name)) {
if (std.mem.startsWith(u8, @typeName(field.field_type), "struct")) {
for (@typeInfo(field.field_type).Struct.fields) |inner_field, j| {
if (@hasField(@TypeOf(@field(new, field.name)), inner_field.name)) {
@field(@field(new, field.name), inner_field.name) = @field(@field(Override, field.name), inner_field.name);
}
}
} else {
@field(new, field.name) = @field(Override, field.name);
}
}
};
return new;
}
};
pub fn Object(comptime state: State) type {
return struct {
const Self = @This();
base: IObject = .{
.executeFn = execute,
},
context: *const Context,
render_pass: *const state.render_pass,
descriptor_set_layouts: [state.layout.set_layouts.len]vk.DescriptorSetLayout,
shader_modules: [state.shader_stages.len]vk.ShaderModule,
layout: vk.PipelineLayout,
pipeline: vk.Pipeline,
/// Build a pipeline object for use in a program
pub fn build(render: *Render, render_pass: *const state.render_pass) !Self {
const context = &render.backend.context;
// create VertexInput info
comptime var vertex_input_bindings: [state.vertex_input_state.bindings.len]vk.VertexInputBindingDescription = undefined;
comptime const vertex_input_attributes_len = blk: {
var len = 0;
for (state.vertex_input_state.bindings) |T| {
len += @typeInfo(T).Struct.fields.len;
}
break :blk len;
};
comptime var vertex_input_attributes: [vertex_input_attributes_len]vk.VertexInputAttributeDescription = undefined;
comptime for (state.vertex_input_state.bindings) |T, i| {
if (!trait.is(.Struct)(T) or !(trait.isPacked(T) or trait.isExtern(T))) {
@compileError("Vertex Type must be a packed/extern struct");
}
var attribute_pos: usize = 0;
for (@typeInfo(T).Struct.fields) |field, j| {
const format: vk.Format = switch (@typeInfo(field.field_type).Struct.fields[0].field_type) {
f32 => switch (@typeInfo(field.field_type).Struct.fields.len) {
1 => .r32_sfloat,
2 => .r32g32_sfloat,
3 => .r32g32b32_sfloat,
4 => .r32g32b32a32_sfloat,
else => @compileError("Invalid Type for Vertex Input"),
},
i32 => switch (@typeInfo(field.field_type).Struct.fields.len) {
1 => .r32_sint,
2 => .r32g32_sint,
3 => .r32g32b32_sint,
4 => .r32g32b32a32_sint,
else => @compileError("Invalid Type for Vertex Input"),
},
else => @compileError("Invalid Type for Vertex Input"),
};
vertex_input_attributes[attribute_pos] = vk.VertexInputAttributeDescription{
.location = @intCast(u32, j),
.binding = i,
.format = format,
.offset = @intCast(u32, @byteOffsetOf(T, field.name)),
};
attribute_pos += 1;
}
vertex_input_bindings[i] = vk.VertexInputBindingDescription{
.binding = i,
.stride = @sizeOf(T),
.input_rate = state.vertex_input_state.input_rate,
};
};
const vertex_input_info = vk.PipelineVertexInputStateCreateInfo{
.vertex_binding_description_count = @intCast(u32, state.vertex_input_state.bindings.len),
.p_vertex_binding_descriptions = &vertex_input_bindings,
.vertex_attribute_description_count = @intCast(u32, vertex_input_attributes_len),
.p_vertex_attribute_descriptions = &vertex_input_attributes,
.flags = .{},
};
// create InputAssembly info
const input_assembly_info = vk.PipelineInputAssemblyStateCreateInfo{
.topology = state.input_assembly_state.topology,
.primitive_restart_enable = if (state.input_assembly_state.primitive_restart) vk.TRUE else vk.FALSE,
.flags = .{},
};
// create Rasterizer info
const rasterizer_info = vk.PipelineRasterizationStateCreateInfo{
.depth_clamp_enable = vk.FALSE,
.rasterizer_discard_enable = vk.FALSE,
.polygon_mode = state.rasterizer_state.polygon_mode,
.line_width = 1.0,
.cull_mode = state.rasterizer_state.cull_mode,
.front_face = state.rasterizer_state.front_face,
.depth_bias_enable = vk.FALSE,
.depth_bias_constant_factor = 0,
.depth_bias_clamp = 0,
.depth_bias_slope_factor = 0,
.flags = .{},
};
// create Multisampling info
const multisample_info = if (state.multisample_state) |multisample|
vk.PipelineMultisampleStateCreateInfo{
.sample_shading_enable = vk.FALSE,
.rasterization_samples = .{ .@"1_bit" = true },
.min_sample_shading = 0,
.p_sample_mask = null,
.alpha_to_coverage_enable = 0,
.alpha_to_one_enable = 0,
.flags = .{},
}
else
vk.PipelineMultisampleStateCreateInfo{
.sample_shading_enable = vk.FALSE,
.rasterization_samples = .{ .@"1_bit" = true },
.min_sample_shading = 0,
.p_sample_mask = null,
.alpha_to_coverage_enable = 0,
.alpha_to_one_enable = 0,
.flags = .{},
};
// create DepthStencil info
const depth_stencil_info: ?vk.PipelineDepthStencilStateCreateInfo = if (state.depth_stencil_state) |depth_stencil| undefined else null;
// create ColorBlend info
comptime var color_blend_attachments: [state.color_blend_state.attachments.len]vk.PipelineColorBlendAttachmentState = undefined;
comptime for (state.color_blend_state.attachments) |attachment, i| {
color_blend_attachments[i] = vk.PipelineColorBlendAttachmentState{
.blend_enable = if (attachment.enable_blending) vk.TRUE else vk.FALSE,
.src_color_blend_factor = attachment.color_blend_src,
.dst_color_blend_factor = attachment.color_blend_dst,
.color_blend_op = attachment.color_blend_op,
.src_alpha_blend_factor = attachment.alpha_blend_src,
.dst_alpha_blend_factor = attachment.alpha_blend_dst,
.alpha_blend_op = attachment.alpha_blend_op,
.color_write_mask = attachment.color_write_mask,
};
};
const color_blend_info = vk.PipelineColorBlendStateCreateInfo{
.logic_op_enable = vk.FALSE,
.logic_op = .copy,
.attachment_count = color_blend_attachments.len,
.p_attachments = &color_blend_attachments,
.blend_constants = [_]f32{ 0, 0, 0, 0 },
.flags = .{},
};
// create PipelineLayout
var descriptor_set_layouts: [state.layout.set_layouts.len]vk.DescriptorSetLayout = undefined;
inline for (state.layout.set_layouts) |set, i| {
var set_bindings: [set.bindings.len]vk.DescriptorSetLayoutBinding = undefined;
for (set.bindings) |binding, j| {
set_bindings[j] = vk.DescriptorSetLayoutBinding{
.binding = @intCast(u32, j),
.descriptor_type = binding.kind,
.descriptor_count = binding.count,
.stage_flags = binding.stages,
.p_immutable_samplers = null,
};
}
const set_info = vk.DescriptorSetLayoutCreateInfo{
.binding_count = set.bindings.len,
.p_bindings = &set_bindings,
.flags = .{},
};
descriptor_set_layouts[i] = try context.vkd.createDescriptorSetLayout(context.device, set_info, null);
}
const layout_info = vk.PipelineLayoutCreateInfo{
.set_layout_count = state.layout.set_layouts.len,
.p_set_layouts = if (state.layout.set_layouts.len == 0) undefined else &descriptor_set_layouts,
.push_constant_range_count = 0,
.p_push_constant_ranges = undefined,
.flags = .{},
};
const layout = try context.vkd.createPipelineLayout(context.device, layout_info, null);
// create Shader Modules
var shader_modules: [state.shader_stages.len]vk.ShaderModule = undefined;
var shader_infos: [state.shader_stages.len]vk.PipelineShaderStageCreateInfo = undefined;
inline for (state.shader_stages) |stage, i| {
const bytes = if (stage.shader == .bytes) stage.shader.bytes else try std.fs.cwd().readFileAllocOptions(&context.arena.allocator, stage.shader.path, std.math.maxInt(u32), @alignOf(u32), 0);
const create_info = vk.ShaderModuleCreateInfo{
.code_size = bytes.len,
.p_code = @ptrCast([*]const u32, bytes),
.flags = .{},
};
shader_modules[i] = try context.vkd.createShaderModule(context.device, create_info, null);
shader_infos[i] = vk.PipelineShaderStageCreateInfo{
.stage = stage.stage,
.module = shader_modules[i],
.p_name = stage.entrypoint[0..:0],
.flags = .{},
.p_specialization_info = null,
};
}
// create fake Viewport info
const viewport_info = vk.PipelineViewportStateCreateInfo{
.viewport_count = 1,
.p_viewports = null,
.scissor_count = 1,
.p_scissors = null,
.flags = .{},
};
// create Dynamic info
const dynamic_states = [_]vk.DynamicState{
.viewport,
.scissor,
};
const dynamic_info = vk.PipelineDynamicStateCreateInfo{
.dynamic_state_count = dynamic_states.len,
.p_dynamic_states = &dynamic_states,
.flags = .{},
};
// create Pipeline
const pipeline_info = [_]vk.GraphicsPipelineCreateInfo{vk.GraphicsPipelineCreateInfo{
.stage_count = @intCast(u32, state.shader_stages.len),
.p_stages = @ptrCast([*]const vk.PipelineShaderStageCreateInfo, &shader_infos),
.p_tessellation_state = null,
.p_vertex_input_state = &vertex_input_info,
.p_input_assembly_state = &input_assembly_info,
.p_viewport_state = &viewport_info,
.p_rasterization_state = &rasterizer_info,
.p_multisample_state = &multisample_info,
.p_depth_stencil_state = null,
.p_color_blend_state = &color_blend_info,
.p_dynamic_state = &dynamic_info,
.layout = layout,
.render_pass = render_pass.render_pass,
.subpass = 0,
.base_pipeline_handle = .null_handle,
.base_pipeline_index = 0,
.flags = .{},
}};
var pipeline: vk.Pipeline = undefined;
_ = try context.vkd.createGraphicsPipelines(context.device, .null_handle, pipeline_info.len, &pipeline_info, null, @ptrCast(*[1]vk.Pipeline, &pipeline));
return Self{
.context = context,
.render_pass = render_pass,
.descriptor_set_layouts = descriptor_set_layouts,
.shader_modules = shader_modules,
.layout = layout,
.pipeline = pipeline,
};
}
pub fn deinit(self: Self) void {
self.context.vkd.destroyPipeline(self.context.device, self.pipeline, null);
self.context.vkd.destroyPipelineLayout(self.context.device, self.layout, null);
for (self.shader_modules) |module| self.context.vkd.destroyShaderModule(self.context.device, module, null);
for (self.descriptor_set_layouts) |layout| self.context.vkd.destroyDescriptorSetLayout(self.context.device, layout, null);
}
pub fn execute(base: *const IObject, cb: vk.CommandBuffer, fb: Framebuffer) !void {
const self = @fieldParentPtr(Self, "base", base);
self.context.vkd.cmdBindPipeline(cb, state.kind, self.pipeline);
}
};
}
pub const Layout = struct {
set_layouts: []const DescriptorSetLayout,
};
pub const ShaderStage = struct {
stage: vk.ShaderStageFlags,
shader: union(enum) {
path: []const u8,
bytes: [:0]align(@alignOf(u32)) const u8,
},
entrypoint: []const u8,
};
pub const VertexInputState = struct {
input_rate: vk.VertexInputRate,
bindings: []const type,
};
pub const InputAssemblyState = struct {
topology: vk.PrimitiveTopology,
primitive_restart: bool,
};
pub const RasterizerState = struct {
cull_mode: vk.CullModeFlags,
front_face: vk.FrontFace,
polygon_mode: vk.PolygonMode,
};
pub const MultisampleState = struct {};
pub const DepthStencilState = struct {};
pub const ColorBlendState = struct {
pub const Attachment = struct {
enable_blending: bool,
color_blend_src: vk.BlendFactor,
color_blend_dst: vk.BlendFactor,
color_blend_op: vk.BlendOp,
alpha_blend_src: vk.BlendFactor,
alpha_blend_dst: vk.BlendFactor,
alpha_blend_op: vk.BlendOp,
color_write_mask: vk.ColorComponentFlags,
};
attachments: []const Attachment,
}; | render/src/program/pipeline.zig |
const std = @import("std");
const math = @import("utils/math.zig");
const Component = @import("Component.zig");
const StateMachine = @import("ActionStates/StateMachine.zig");
const CommonStates = @import("ActionStates/CommonStates.zig");
const Input = @import("Input.zig");
const CharacterData = @import("CharacterData.zig");
const CollisionSystem = @import("CollisionSystem.zig");
const InputComponent = struct { inputCommand: Input.InputCommand = .{} };
const StateMachineComponent = struct { context: StateMachine.CombatStateContext = .{}, stateMachine: StateMachine.CombatStateMachineProcessor = .{} };
// For now our only test state is a global constant. Need to move this to somewhere where character
// specific data is stored.
var StandingCallbacks = StateMachine.CombatStateCallbacks{ .OnUpdate = CommonStates.Standing.OnUpdate, .OnStart = CommonStates.Standing.OnStart, .OnEnd = CommonStates.Standing.OnEnd };
var WalkingForwardCallbacks = StateMachine.CombatStateCallbacks{ .OnUpdate = CommonStates.WalkingForward.OnUpdate, .OnStart = CommonStates.WalkingForward.OnStart, .OnEnd = CommonStates.WalkingForward.OnEnd };
pub const GameData = struct {
HitboxGroup: CharacterData.HitboxGroup, // TODO: Temp data, remove.
Characters: std.ArrayList(CharacterData.CharacterProperties),
//CharacterProperties: [10]CharacterData.CharacterProperties
};
pub fn InitializeGameData(allocator: std.mem.Allocator) GameData
{
var gameData = GameData{ .HitboxGroup = .{ .Hitboxes = std.ArrayList(CharacterData.Hitbox).init(allocator) },
.Characters = std.ArrayList(CharacterData.CharacterProperties).init(allocator)
};
//gameData.HitboxGroup.Hitboxes.append(CharacterData.Hitbox{ .top = 200, .left = 300, .bottom = 0, .right = 600 }) catch unreachable;
return gameData;
}
pub const GameState = struct {
frameCount: i32 = 0,
entityCount: i32 = 1,
physicsComponents: [10]Component.PhysicsComponent = [_]Component.PhysicsComponent{.{}} ** 10,
stateMachineComponents: [10]StateMachineComponent = [_]StateMachineComponent{.{}} ** 10,
inputComponents: [2]InputComponent = [_]InputComponent{.{}} ** 2,
allocator: std.mem.Allocator,
gameData: ?GameData = null,
pub fn Init(self: *GameState) void
{
// Game data initialization
self.gameData = InitializeGameData(self.allocator);
self.stateMachineComponents[0].context.PhysicsComponent = &self.physicsComponents[0];
// testing initializing a single entity
self.stateMachineComponents[0].stateMachine.Context = &self.stateMachineComponents[0].context;
self.stateMachineComponents[0].stateMachine.Registery.RegisterCommonState(StateMachine.CombatStateID.Standing, &StandingCallbacks);
self.stateMachineComponents[0].stateMachine.Registery.RegisterCommonState(StateMachine.CombatStateID.WalkingForward, &WalkingForwardCallbacks);
}
};
// Handles moving all entities which have a physics component
fn PhysicsSystem(gameState: *GameState) void
{
var entityIndex: usize = 0;
while (entityIndex < gameState.entityCount)
{
const component = &gameState.physicsComponents[entityIndex];
// move position based on the current velocity.
component.position = component.position.Add(component.velocity);
component.velocity = component.velocity.Add(component.acceleration);
entityIndex += 1;
}
}
fn ActionSystem(gameState: *GameState) void
{
var entityIndex: usize = 0;
while (entityIndex < gameState.entityCount) {
const component = &gameState.stateMachineComponents[entityIndex];
component.stateMachine.UpdateStateMachine();
entityIndex += 1;
}
}
fn InputCommandSystem(gameState: *GameState) void
{
gameState.stateMachineComponents[0].context.InputCommand = gameState.inputComponents[0].inputCommand;
}
test "Testing setting up game data"
{
var ArenaAllocator = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var Allocator = ArenaAllocator.allocator();
var gameData = GameData{ .HitboxGroup = .{ .Hitboxes = std.ArrayList(CharacterData.Hitbox).init(Allocator) },
.Characters = std.ArrayList(CharacterData.CharacterProperties).init(Allocator)
};
try gameData.HitboxGroup.Hitboxes.append(CharacterData.Hitbox{ .top = 200, .left = -300, .bottom = 0, .right = 300 });
try std.testing.expect(gameData.HitboxGroup.Hitboxes.items[0].right == 300);
}
pub fn UpdateGame(gameState: *GameState) void {
InputCommandSystem(gameState);
ActionSystem(gameState);
PhysicsSystem(gameState);
gameState.frameCount += 1;
} | src/GameSimulation.zig |
const AyArgparse = @This();
const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
args: [][]u8 = undefined,
arguments: std.StringHashMapUnmanaged([]const u8) = .{},
positionals: std.ArrayListUnmanaged([]const u8) = .{},
allocator: Allocator,
params: []const ParamDesc,
pub const ParamDesc = struct {
long: []const u8,
short: ?[]const u8 = null,
need_value: bool = false,
};
pub fn init(allocator: Allocator, params: []const ParamDesc) AyArgparse {
return .{
.allocator = allocator,
.params = params,
};
}
pub fn deinit(self: *AyArgparse) void {
self.arguments.deinit(self.allocator);
self.positionals.deinit(self.allocator);
}
fn next(self: *AyArgparse, index: *usize) ?[]const u8 {
if (index.* < self.args.len) {
index.* += 1;
return self.args[index.* - 1];
}
return null;
}
fn getDescFromLong(self: *AyArgparse, long: []const u8) !ParamDesc {
for (self.params) |param| {
if (mem.eql(u8, param.long, long)) {
return param;
}
}
std.debug.print("invalid argument '--{s}'\n", .{long});
return error.ArgparseError;
}
fn getDescFromShort(self: *AyArgparse, short: []const u8) !ParamDesc {
for (self.params) |param| if (param.short) |p_short| {
if (mem.eql(u8, p_short, short)) {
return param;
}
};
std.debug.print("invalid argument '-{s}'\n", .{short});
return error.ArgparseError;
}
inline fn makeValue(self: *AyArgparse, key: []const u8, value: ?[]const u8, i: *usize, desc: ParamDesc) ![]const u8 {
return blk: {
if (desc.need_value) {
break :blk value orelse self.next(i) orelse {
std.debug.print("expected value for key '{s}'\n", .{key});
return error.ArgparseError;
};
} else if (value != null) {
std.debug.print("key '{s}' does not take value\n", .{key});
return error.ArgparseError;
} else break :blk "true";
};
}
pub fn parse(self: *AyArgparse, args: [][]u8) !void {
self.args = args;
var i: usize = 0;
while (i < args.len) {
var key = self.next(&i).?;
var value: ?[]const u8 = null;
if (mem.startsWith(u8, key, "--")) {
if (mem.eql(u8, key, "--")) {
while (self.next(&i)) |pos|
try self.positionals.append(self.allocator, pos);
return;
}
if (mem.indexOf(u8, key, "=")) |pos| {
value = key[(pos + 1)..];
key = key[0..pos];
}
const key_name = key[2..];
const desc = try self.getDescFromLong(key_name);
const val = try self.makeValue(key, value, &i, desc);
try self.arguments.put(self.allocator, key_name, val);
} else if (mem.startsWith(u8, key, "-")) {
if (mem.indexOf(u8, key, "=")) |pos| {
value = key[(pos + 1)..];
}
var id: usize = 1;
while (id < key.len) : (id += 1) {
const key_name = key[id .. id + 1];
const desc = try self.getDescFromShort(key_name);
const has_value = id + 1 < key.len and key[id + 1] == '=';
const val = blk: {
if (desc.need_value) {
if (!has_value and id + 1 < key.len) {
value = key[id + 1 ..];
id += value.?.len;
}
break :blk value;
} else {
break :blk if (has_value) value else null;
}
};
const val_final = try self.makeValue(key, val, &i, desc);
try self.arguments.put(self.allocator, key_name, val_final);
if (has_value) break;
}
} else {
try self.positionals.append(self.allocator, key);
}
}
} | AyArgparse.zig |
const std = @import("std");
const IOPort = @import("../IOPort.zig");
const TextConsole = @This();
pub const ForegroundColor = enum(u4) {
black = 0,
blue = 1,
green = 2,
cyan = 3,
red = 4,
purple = 5,
dark_orange = 6,
light_gray = 7,
gray = 8,
light_blue = 9,
light_green = 10,
light_cyan = 11,
light_red = 12,
light_purple = 13,
yellow = 14,
white = 15,
};
pub const BackgroundColor = enum(u3) {
black = 0,
blue = 1,
green = 2,
cyan = 3,
red = 4,
purple = 5,
dark_orange = 6,
gray = 7,
};
const CharacterData = packed struct {
character: u8, // Bit 7:0 - Character
foreground_color: ForegroundColor, // Bit 11:8 - Foreground color
background_color: BackgroundColor, // Bit 14:12 - Background color
unused_flag: bool = false, // Bit 15 - Behavior depends on the BIOS. Not using it.
};
video_memory: [*]CharacterData,
width: usize,
height: usize,
register_port: IOPort,
data_port: IOPort,
cursor_x_position: usize = 0,
cursor_y_position: usize = 0,
fn character_index(self: *const TextConsole, x_position: usize, y_position: usize) ?usize {
if (x_position >= self.width) {
return null;
}
if (y_position == self.height) {
return null;
}
return y_position * self.width + x_position;
}
fn current_character_index(self: *const TextConsole) ?usize {
return self.character_index(self.cursor_x_position, self.cursor_y_position);
}
fn scroll(self: *TextConsole, foreground_color: ForegroundColor, background_color: BackgroundColor) void {
var line: usize = 0;
while (line < (self.height - 1)) : (line += 1) {
const source = self.video_memory[(self.character_index(0, line + 1).?)..(self.character_index(self.width - 1, line + 1).? + 1)];
var destnation = self.video_memory[(self.character_index(0, line).?)..(self.character_index(self.width - 1, line).? + 1)];
std.mem.copy(CharacterData, destnation, source);
}
std.mem.set(
CharacterData,
self.video_memory[(self.character_index(0, line).?)..(self.character_index(self.width - 1, line).? + 1)],
.{ .character = 0, .foreground_color = foreground_color, .background_color = background_color },
);
}
fn write_character(self: *TextConsole, character: u8, foreground_color: ForegroundColor, background_color: BackgroundColor) void {
if (character == '\n') {
self.cursor_y_position += 1;
self.cursor_x_position = 0;
while (self.cursor_y_position >= self.height) {
self.scroll(foreground_color, background_color);
self.cursor_y_position = self.height - 1;
}
return;
}
if (self.cursor_x_position >= self.width) {
// TODO
return;
}
while (self.cursor_y_position >= self.height) {
self.scroll(foreground_color, background_color);
self.cursor_y_position = self.height - 1;
}
var character_data = &self.video_memory[self.current_character_index().?];
character_data.character = character;
character_data.foreground_color = foreground_color;
character_data.background_color = background_color;
self.cursor_x_position += 1;
}
fn update_cursor(self: *TextConsole) void {
const maybe_index = self.current_character_index();
if (maybe_index == null) {
return;
}
const index = maybe_index.?;
self.register_port.write_byte(0x0f);
self.data_port.write_byte(@intCast(u8, index & 0xFF));
self.register_port.write_byte(0x0e);
self.data_port.write_byte(@intCast(u8, index >> 8));
}
pub fn clear_and_reset_cursor(self: *TextConsole, foreground_color: ForegroundColor, background_color: BackgroundColor) void {
self.cursor_y_position = 0;
while (self.cursor_y_position < self.height) : (self.cursor_y_position += 1) {
self.cursor_x_position = 0;
while (self.cursor_x_position < self.width) {
// write_character will advance self.cursor_x_position.
self.write_character(' ', foreground_color, background_color);
}
}
self.cursor_y_position = 0;
self.cursor_x_position = 0;
}
pub fn write_string(self: *TextConsole, string: []const u8, foreground_color: ForegroundColor, background_color: BackgroundColor) void {
for (string) |character| {
self.write_character(character, foreground_color, background_color);
}
self.update_cursor();
}
pub fn standard_text_console() TextConsole {
return .{ .video_memory = @intToPtr([*]CharacterData, 0xb8000), .width = 80, .height = 25, .register_port = .{ .port_number = 0x3d4 }, .data_port = .{ .port_number = 0x3d5 } };
} | kernel/console/TextConsole.zig |
const std = @import("std");
const PortIO = @import("port.zig");
/// ATA Bus:
/// Primary: BAR0: 0x1F0, BAR1: 0x3F4
/// Secondary: BAR0: 0x170, BAR1: 0x374
pub const Bus = enum { Primary, Secondary };
pub const Drive = enum { Master, Slave };
pub fn PIODevice(comptime bus: Bus, comptime drv: Drive) type {
return struct {
const BAR0 = switch (bus) {
.Primary => 0x1F0,
.Secondary => 0x170,
};
const BAR1 = switch (bus) {
.Primary => 0x3F4,
.Secondary => 0x374,
};
const PIO_DATA = BAR0 + 0;
const PIO_ERROR = BAR0 + 1;
const PIO_SECTOR_COUNT = BAR0 + 2;
const PIO_LBA0 = BAR0 + 3;
const PIO_LBA1 = BAR0 + 4;
const PIO_LBA2 = BAR0 + 5;
const PIO_SELECT = BAR0 + 6;
const PIO_COMMAND = BAR0 + 7;
const PIO_STATUS = BAR0 + 7;
const PIO_CONTROL = BAR1 + 2;
const PIO_ALTSTATUS = BAR1 + 2;
const ATAError = error {
NotExist,
NotATA,
TransferError,
};
const Self = @This();
block_count: u64,
pub fn init() ATAError!Self {
var self: Self = undefined;
irqDisable();
if (altStatus() == 0) return ATAError.NotExist;
var ident: [256]u16 = undefined;
try self.identify(@ptrCast(*[512]u8, &ident));
const lba = LBAInfo.parse(&ident);
if (!lba.lba48) return ATAError.NotATA;
self.block_count = lba.block_count;
return self;
}
fn irqDisable() void {
PortIO.out(u8, PIO_CONTROL, 0x02);
}
// Alternate Status
fn altStatus() u8 {
return PortIO.in(u8, PIO_ALTSTATUS);
}
pub fn identify(self: *Self, buf: []u8) ATAError!void {
const ATA_IDENTIFY = 0xEC;
PortIO.out(u8, PIO_SELECT, switch (drv) {
.Master => 0xA0,
.Slave => 0xB0,
});
PortIO.out(u8, PIO_SECTOR_COUNT, 0);
PortIO.out(u8, PIO_LBA0, 0);
PortIO.out(u8, PIO_LBA1, 0);
PortIO.out(u8, PIO_LBA2, 0);
PortIO.out(u8, PIO_COMMAND, ATA_IDENTIFY);
var status = PortIO.in(u8, PIO_STATUS);
if (status == 0) return ATAError.NotExist;
// wait while BSY
while (true) {
status = PortIO.in(u8, PIO_STATUS);
if (status & 0x80 == 0) break;
const midLBA = PortIO.in(u8, PIO_LBA1);
const hiLBA = PortIO.in(u8, PIO_LBA2);
if (midLBA != 0 or hiLBA != 0) return ATAError.NotATA;
}
// wait while DRQ or ERR
while (true) {
status = PortIO.in(u8, PIO_STATUS);
if (status & 0x08 != 0) break;
if (status & 0x01 != 0) return ATAError.TransferError;
}
var tmp: [256]u16 = undefined;
for (tmp) |*data| {
data.* = PortIO.in(u16, PIO_DATA);
}
std.mem.copy(u8, buf, @ptrCast(*const [512]u8, &tmp));
}
pub fn read(self: *Self, block: u64, buf: []u8) ATAError!void {
const ATA_READ_EXT = 0x24;
PortIO.out(u8, PIO_SELECT, switch (drv) {
.Master => 0x40,
.Slave => 0x50,
});
// sectorcount high byte
PortIO.out(u8, PIO_SECTOR_COUNT, 0);
// LBA 6:4
PortIO.out(u8, PIO_LBA0, @truncate(u8, block >> 24));
PortIO.out(u8, PIO_LBA1, @truncate(u8, block >> 32));
PortIO.out(u8, PIO_LBA2, @truncate(u8, block >> 40));
// sectorcount low byte
PortIO.out(u8, PIO_SECTOR_COUNT, 1);
// LBA 3:1
PortIO.out(u8, PIO_LBA0, @truncate(u8, block));
PortIO.out(u8, PIO_LBA1, @truncate(u8, block >> 8));
PortIO.out(u8, PIO_LBA2, @truncate(u8, block >> 16));
PortIO.out(u8, PIO_COMMAND, ATA_READ_EXT);
var status = PortIO.in(u8, PIO_STATUS);
if (status == 0) return ATAError.NotExist;
// wait while BSY
while (true) {
status = PortIO.in(u8, PIO_STATUS);
if (status & 0x80 == 0) break;
}
// wait while DRQ
var trys: usize = 1000;
while (true) {
status = PortIO.in(u8, PIO_STATUS);
if (status & 0x08 != 0) break;
if (trys == 0) return ATAError.TransferError;
trys -= 1;
}
var tmp: [256]u16 = undefined;
for (tmp) |*data| {
data.* = PortIO.in(u16, PIO_DATA);
}
std.mem.copy(u8, buf, @ptrCast(*const [512]u8, &tmp));
}
};
}
const LBAInfo = struct {
lba48: bool,
block_count: u64,
const Self = @This();
pub fn parse(ident: *const [256]u16) Self {
var info = Self {
.lba48 = false,
.block_count = 0,
};
const lba48_capable = ident[83] & 0x400 != 0;
if (lba48_capable) {
info.lba48 = true;
info.block_count =
@as(u64, ident[103]) << 48 |
@as(u64, ident[102]) << 32 |
@as(u32, ident[101]) << 16 |
ident[100];
}
else {
info.block_count =
@as(u32, ident[61]) << 16 |
ident[60];
}
return info;
}
}; | src/io/ata.zig |
const std = @import("std");
const NativeVector = @import("native_vector.zig").NativeVector;
const assert = std.debug.assert;
pub fn indexOfScalar(comptime T: type, items: []const T, value: T) ?usize {
var i: usize = 0;
if (comptime NativeVector.supportsType(T)) {
const vec = NativeVector.init(T);
const splat_value = vec.splat(value);
while (i < vec.maxIndex(items.len)) : (i += vec.len) {
const v = vec.load(items[i..]);
const cmpEqual = v == splat_value;
if (vec.anyTrue(cmpEqual)) {
return i + vec.leadingFalseCount(cmpEqual);
}
}
}
while (i < items.len) : (i += 1) {
if (items[i] == value) {
return i;
}
}
return null;
}
pub fn lastIndexOfScalar(comptime T: type, items: []const T, value: T) ?usize {
var i: usize = items.len;
if (comptime NativeVector.supportsType(T)) {
const vec = NativeVector.init(T);
const splat_value = vec.splat(value);
while (i > vec.minIndex(items.len)) {
i -= vec.len;
const v = vec.load(items[i..]);
const cmpEqual = v == splat_value;
if (vec.anyTrue(cmpEqual)) {
return i + vec.len - 1 - vec.trailingFalseCount(cmpEqual);
}
}
}
while (i > 0) {
i -= 1;
if (items[i] == value) {
return i;
}
}
return null;
}
pub fn min(comptime T: type, items: []const T) T {
assert(items.len > 0);
var min_value: T = items[0];
var i: usize = 0;
if (comptime NativeVector.supportsType(T)) {
const vec = NativeVector.init(T);
if (items.len >= vec.len) {
var vmin = vec.load(items[0..]);
i += vec.len;
while (i < vec.maxIndex(items.len)) : (i += vec.len) {
const v = vec.load(items[i..]);
vmin = @select(T, v < vmin, v, vmin);
}
min_value = @reduce(.Min, vmin);
}
}
for (items[i..]) |value| {
min_value = std.math.min(min_value, value);
}
return min_value;
}
pub fn max(comptime T: type, items: []const T) T {
assert(items.len > 0);
var max_value: T = items[0];
var i: usize = 0;
if (comptime NativeVector.supportsType(T)) {
const vec = NativeVector.init(T);
if (items.len >= vec.len) {
var vmax = vec.load(items[0..]);
i += vec.len;
while (i < vec.maxIndex(items.len)) : (i += vec.len) {
const v = vec.load(items[i..]);
vmax = @select(T, v > vmax, v, vmax);
}
max_value = @reduce(.Max, vmax);
}
}
for (items[i..]) |value| {
max_value = std.math.max(max_value, value);
}
return max_value;
}
pub fn eql(comptime T: type, a: []const T, b: []const T) bool {
if (a.len != b.len) return false;
if (a.ptr == b.ptr) return true;
var i: usize = 0;
if (comptime NativeVector.supportsType(T)) {
const vec = NativeVector.init(T);
while (i < vec.maxIndex(a.len)) : (i += vec.len) {
if (vec.anyTrue(vec.load(a[i..]) != vec.load(b[i..]))) {
return false;
}
}
}
while (i < a.len) : (i += 1) {
if (a[i] != b[i]) {
return false;
}
}
return true;
} | src/algorithms.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const e = @import("engine.zig");
const Engine = e.Engine;
const ByteCodeError = e.ByteCodeError;
const DatabaseError = e.DatabaseError;
const c = @import("card.zig");
const Card = c.Card;
test "initialize engine" {
const state = try initEngine(std.testing.allocator, "./database.db");
defer state.deinit();
try std.testing.expect(std.mem.eql(u8, state.database_path, "./database.db"));
}
fn initEngine(allocator: Allocator, path: anytype) !Engine {
const state = Engine.init(allocator, path) catch |err| {
std.log.err("[{s}] Could not initialize engine.", .{@errorName(err)});
return err;
};
return state;
}
test "load card" {
const state = try initEngine(std.testing.allocator, "./database.db");
defer state.deinit();
var card = try loadCard(&state);
defer card.deinit();
try std.testing.expect(std.mem.eql(u8, card.id, "eeba7932-5b7f-4dc4-9470-e7d2bda8beb4"));
}
fn loadCard(state: *const Engine) !Card {
var card = state.loadCard("eeba7932-5b7f-4dc4-9470-e7d2bda8beb4") catch |err| {
std.log.err("[{s}] Could not load card.", .{@errorName(err)});
return err;
};
return card;
}
test "load byte code" {
const state = try initEngine(std.testing.allocator, "./database.db");
defer state.deinit();
var card = try loadCard(&state);
defer card.deinit();
try loadByteCode(&state, &card);
try std.testing.expect(std.mem.eql(u8, card.hash.?, "9ABA6818E5925233B1A111DFB88BFF6397B3BEF3AF97F9D74ADF535BE30CE142"));
}
fn loadByteCode(state: *const Engine, card: *Card) !void {
state.loadByteCode(card) catch |err| {
switch (err) {
ByteCodeError.Load, ByteCodeError.Execute, ByteCodeError.InvalidReturn => {
const s = try state.getByteCodeError(err);
defer state.freeByteCodeError(s);
std.log.err("[{s}] Failed to load bytecode: {s}", .{ @errorName(err), s });
},
DatabaseError.Open, DatabaseError.Prepare, DatabaseError.Bind, DatabaseError.Query, DatabaseError.HashCheck => {
std.log.err("[{s}] Failed to load bytecode due to a database error", .{@errorName(err)});
},
else => {
std.log.err("[{s}] Failed to allocate memory", .{@errorName(err)});
},
}
return err;
};
}
test "exec byte code" {
const state = try initEngine(std.testing.allocator, "./database.db");
defer state.deinit();
var card = try loadCard(&state);
defer card.deinit();
try loadByteCode(&state, &card);
try execByteCode(&state, &card);
try std.testing.expect(std.mem.eql(u8, card.primary_title.?, "cone"));
try std.testing.expect(std.mem.eql(u8, card.sub_title.?, "@pressy4pie"));
try std.testing.expect(card.version_major == 0);
try std.testing.expect(card.version_minor == 1);
}
fn execByteCode(state: *const Engine, card: *Card) !void {
state.executeByteCode(card) catch |err| {
switch (err) {
ByteCodeError.Load, ByteCodeError.Execute, ByteCodeError.InvalidReturn => {
const s = try state.getByteCodeError(err);
defer state.freeByteCodeError(s);
std.log.err("[{s}] Failed to execute bytecode: {s}", .{ @errorName(err), s });
},
DatabaseError.Open, DatabaseError.Prepare, DatabaseError.Bind, DatabaseError.Query, DatabaseError.HashCheck => {
std.log.err("[{s}] Failed to execute bytecode due to a database error", .{@errorName(err)});
},
else => {
std.log.err("[{s}] Failed to allocate memory", .{@errorName(err)});
},
}
return err;
};
}
test "render card" {
const state = try initEngine(std.testing.allocator, "./database.db");
defer state.deinit();
var card = try loadCard(&state);
defer card.deinit();
try loadByteCode(&state, &card);
try execByteCode(&state, &card);
try render(&state, &card);
}
fn render(state: *const Engine, card: *Card) !void {
state.render(card) catch |err| {
switch (err) {
ByteCodeError.Load, ByteCodeError.Execute, ByteCodeError.InvalidReturn => {
const s = try state.getByteCodeError(err);
defer state.freeByteCodeError(s);
std.log.err("[{s}] Bytecode error: {s}", .{ @errorName(err), s });
},
DatabaseError.Open, DatabaseError.Prepare, DatabaseError.Bind, DatabaseError.Query, DatabaseError.HashCheck => {
std.log.err("[{s}] Database error", .{@errorName(err)});
},
else => {
std.log.err("[{s}] Failed to allocate memory", .{@errorName(err)});
},
}
return err;
};
}
pub fn main() anyerror!u8 {
const allocator = std.heap.page_allocator;
const state = initEngine(allocator, "./database.db") catch return 1;
defer state.deinit();
std.log.info("initialized engine v{d}.{d}", .{ e.EngineMajor, e.EngineMinor });
var card = loadCard(&state) catch return 1;
defer card.deinit();
std.log.info("loaded card {s}", .{card.id});
loadByteCode(&state, &card) catch return 1;
std.log.info("loaded bytecode {s}", .{card.hash});
execByteCode(&state, &card) catch return 1;
std.log.info("executed bytecode", .{});
render(&state, &card) catch return 1;
std.log.info("rendered {s}", .{"output.png"});
return 0;
} | engine/src/main.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const Grid = ArrayList(ArrayList(u8));
const Coord = struct { i: i32, j: i32 };
const neighbor_relative_coords = [_]Coord{
Coord{ .i = -1, .j = -1 },
Coord{ .i = 0, .j = -1 },
Coord{ .i = 1, .j = -1 },
Coord{ .i = -1, .j = 0 },
Coord{ .i = 1, .j = 0 },
Coord{ .i = -1, .j = 1 },
Coord{ .i = 0, .j = 1 },
Coord{ .i = 1, .j = 1 },
};
// Fill next_grid with the next state of grid
fn step(grid: ArrayList(ArrayList(u8)), next_grid: ArrayList(ArrayList(u8))) void {
const grid_width = grid.items[0].items.len;
const grid_height = grid.items.len;
var i: usize = 0;
while (i < grid_height) : (i += 1) {
var j: usize = 0;
while (j < grid_width) : (j += 1) {
var num_neighbors_on: u32 = 0;
for (neighbor_relative_coords) |coord| {
const ii: i32 = @intCast(i32, i) + coord.i;
const jj: i32 = @intCast(i32, j) + coord.j;
if (ii >= 0 and ii < grid_height and jj >= 0 and jj < grid_width) {
if (grid.items[@intCast(usize, ii)].items[@intCast(usize, jj)] == '#') {
num_neighbors_on += 1;
}
}
}
if (grid.items[i].items[j] == '#') {
if (num_neighbors_on == 2 or num_neighbors_on == 3) {
next_grid.items[i].items[j] = '#';
} else {
next_grid.items[i].items[j] = '.';
}
} else {
if (num_neighbors_on == 3) {
next_grid.items[i].items[j] = '#';
} else {
next_grid.items[i].items[j] = '.';
}
}
}
}
}
fn count_lights(grid: ArrayList(ArrayList(u8))) u32 {
var num_lights: u32 = 0;
for (grid.items) |row| {
for (row.items) |c| {
if (c == '#') {
num_lights += 1;
}
}
}
return num_lights;
}
fn clone_grid(orig_grid: ArrayList(ArrayList(u8)), arena_allocator: *std.mem.Allocator) !ArrayList(ArrayList(u8)) {
var grid = ArrayList(ArrayList(u8)).init(arena_allocator);
for (orig_grid.items) |orig_row| {
var row = ArrayList(u8).init(arena_allocator);
for (orig_row.items) |c| {
try row.append(c);
}
try grid.append(row);
}
return grid;
}
fn fix_corners(grid: ArrayList(ArrayList(u8))) void {
const grid_width = grid.items[0].items.len;
const grid_height = grid.items.len;
grid.items[0].items[0] = '#';
grid.items[0].items[grid_width - 1] = '#';
grid.items[grid_height - 1].items[0] = '#';
grid.items[grid_height - 1].items[grid_width - 1] = '#';
}
pub fn main() !void {
const file = try std.fs.cwd().openFile("inputs/day18.txt", .{ .read = true });
defer file.close();
var reader = std.io.bufferedReader(file.reader()).reader();
var buffer: [1024]u8 = undefined;
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
var orig_grid = ArrayList(ArrayList(u8)).init(&arena.allocator);
while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| {
var row = ArrayList(u8).init(&arena.allocator);
for (line) |c| {
try row.append(c);
}
try orig_grid.append(row);
}
var grid = try clone_grid(orig_grid, &arena.allocator);
var next_grid = try clone_grid(orig_grid, &arena.allocator);
{
var i: usize = 0;
while (i < 100) : (i += 1) {
step(grid, next_grid);
var tmp_grid = grid;
grid = next_grid;
next_grid = tmp_grid;
}
}
std.debug.print("{d}\n", .{count_lights(grid)});
grid = try clone_grid(orig_grid, &arena.allocator);
fix_corners(grid);
{
var i: usize = 0;
while (i < 100) : (i += 1) {
step(grid, next_grid);
fix_corners(next_grid);
var tmp_grid = grid;
grid = next_grid;
next_grid = tmp_grid;
}
}
std.debug.print("{d}\n", .{count_lights(grid)});
} | src/day18.zig |
const std = @import("std");
const builtin = @import("builtin");
const os = std.os;
const io = std.io;
const mem = std.mem;
const Allocator = mem.Allocator;
const ArrayList = std.ArrayList;
const Buffer = std.Buffer;
const arg = @import("arg.zig");
const introspect = @import("introspect.zig");
const Args = arg.Args;
const Flag = arg.Flag;
var stderr: &io.OutStream(io.FileOutStream.Error) = undefined;
var stdout: &io.OutStream(io.FileOutStream.Error) = undefined;
// TODO: might want these in std
fn fileExists(allocator: &Allocator, path: []const u8) bool {
if (os.File.openRead(allocator, path)) |*file| {
file.close();
return true;
} else |_| {
return false;
}
}
const usage =
\\usage: zig [command] [options]
\\
\\Commands:
\\
\\ build Build project from build.zig
\\ build-exe [source] Create executable from source or object files
\\ build-lib [source] Create library from source or object files
\\ build-obj [source] Create object from source or assembly
\\ cc [args] Call the system c compiler and pass args through
\\ fmt [source] Parse file and render in canonical zig format
\\ run [source] Create executable and run immediately
\\ targets List available compilation targets
\\ test [source] Create and run a test build
\\ translate-c [source] Convert c code to zig code
\\ version Print version number and exit
\\ zen Print zen of zig and exit
\\
\\
;
const Command = struct {
name: []const u8,
exec: fn(&Allocator, []const []const u8) error!void,
};
pub fn main() !void {
var allocator = std.heap.c_allocator;
var stdout_file = try std.io.getStdOut();
var stdout_out_stream = std.io.FileOutStream.init(&stdout_file);
stdout = &stdout_out_stream.stream;
var stderr_file = try std.io.getStdErr();
var stderr_out_stream = std.io.FileOutStream.init(&stderr_file);
stderr = &stderr_out_stream.stream;
const args = try os.argsAlloc(allocator);
defer os.argsFree(allocator, args);
if (args.len <= 1) {
try stderr.write(usage);
os.exit(1);
}
const commands = []Command {
Command { .name = "build", .exec = cmdBuild },
Command { .name = "build-exe", .exec = cmdBuildExe },
Command { .name = "build-lib", .exec = cmdBuildLib },
Command { .name = "build-obj", .exec = cmdBuildObj },
Command { .name = "cc", .exec = cmdCc },
Command { .name = "fmt", .exec = cmdFmt },
Command { .name = "run", .exec = cmdRun },
Command { .name = "targets", .exec = cmdTargets },
Command { .name = "test", .exec = cmdTest },
Command { .name = "translate-c", .exec = cmdTranslateC },
Command { .name = "version", .exec = cmdVersion },
Command { .name = "zen", .exec = cmdZen },
// undocumented commands
Command { .name = "help", .exec = cmdHelp },
Command { .name = "internal", .exec = cmdInternal },
};
for (commands) |command| {
if (mem.eql(u8, command.name, args[1])) {
try command.exec(allocator, args[2..]);
return;
}
}
try stderr.print("unknown command: {}\n\n", args[1]);
try stderr.write(usage);
}
// cmd:build ///////////////////////////////////////////////////////////////////////////////////////
const usage_build =
\\usage: zig build <options>
\\
\\General Options:
\\ --help Print this help and exit
\\ --init Generate a build.zig template
\\ --build-file [file] Override path to build.zig
\\ --cache-dir [path] Override path to cache directory
\\ --verbose Print commands before executing them
\\ --prefix [path] Override default install prefix
\\ --zig-install-prefix [path] Override directory where zig thinks it is installed
\\
\\Project-Specific Options:
\\
\\ Project-specific options become available when the build file is found.
\\
\\Advanced Options:
\\ --build-file [file] Override path to build.zig
\\ --cache-dir [path] Override path to cache directory
\\ --verbose-tokenize Enable compiler debug output for tokenization
\\ --verbose-ast Enable compiler debug output for parsing into an AST
\\ --verbose-link Enable compiler debug output for linking
\\ --verbose-ir Enable compiler debug output for Zig IR
\\ --verbose-llvm-ir Enable compiler debug output for LLVM IR
\\ --verbose-cimport Enable compiler debug output for C imports
\\
\\
;
const args_build_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--init"),
Flag.Arg1("--build-file"),
Flag.Arg1("--cache-dir"),
Flag.Bool("--verbose"),
Flag.Arg1("--prefix"),
Flag.Arg1("--zig-install-prefix"),
Flag.Arg1("--build-file"),
Flag.Arg1("--cache-dir"),
Flag.Bool("--verbose-tokenize"),
Flag.Bool("--verbose-ast"),
Flag.Bool("--verbose-link"),
Flag.Bool("--verbose-ir"),
Flag.Bool("--verbose-llvm-ir"),
Flag.Bool("--verbose-cimport"),
};
const missing_build_file =
\\No 'build.zig' file found.
\\
\\Initialize a 'build.zig' template file with `zig build --init`,
\\or build an executable directly with `zig build-exe $FILENAME.zig`.
\\
\\See: `zig build --help` or `zig help` for more options.
\\
\\
;
fn cmdBuild(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_build_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_build);
os.exit(0);
}
const zig_lib_dir = try introspect.resolveZigLibDir(allocator, flags.single("zig-install-prefix") ?? null);
defer allocator.free(zig_lib_dir);
const zig_std_dir = try os.path.join(allocator, zig_lib_dir, "std");
defer allocator.free(zig_std_dir);
const special_dir = try os.path.join(allocator, zig_std_dir, "special");
defer allocator.free(special_dir);
const build_runner_path = try os.path.join(allocator, special_dir, "build_runner.zig");
defer allocator.free(build_runner_path);
const build_file = flags.single("build-file") ?? "build.zig";
const build_file_abs = try os.path.resolve(allocator, ".", build_file);
defer allocator.free(build_file_abs);
const build_file_exists = fileExists(allocator, build_file_abs);
if (flags.present("init")) {
if (build_file_exists) {
try stderr.print("build.zig already exists\n");
os.exit(1);
}
// Required for proper defer scope finalization
{
const build_template_path = try os.path.join(allocator, special_dir, "build_file_template.zig");
defer allocator.free(build_template_path);
try os.copyFile(allocator, build_template_path, build_file_abs);
try stderr.print("wrote build.zig template\n");
}
os.exit(0);
}
if (!build_file_exists) {
try stderr.write(missing_build_file);
os.exit(1);
}
// TODO: Invoke the build_runner directly and circumvent running the compiler in a subprocess.
var zig_exe_path = try os.selfExePath(allocator);
defer allocator.free(zig_exe_path);
var build_args = ArrayList([]const u8).init(allocator);
defer build_args.deinit();
const build_file_basename = os.path.basename(build_file_abs);
const build_file_dirname = os.path.dirname(build_file_abs);
var full_cache_dir: []u8 = undefined;
if (flags.single("cache-dir")) |cache_dir| {
full_cache_dir = try os.path.resolve(allocator, ".", cache_dir, full_cache_dir);
} else {
full_cache_dir = try os.path.join(allocator, build_file_dirname, "zig-cache");
}
defer allocator.free(full_cache_dir);
const path_to_build_exe = try os.path.join(allocator, full_cache_dir, "build");
defer allocator.free(path_to_build_exe);
try build_args.append(path_to_build_exe);
try build_args.append(zig_exe_path);
try build_args.append(build_file_dirname);
try build_args.append(full_cache_dir);
if (flags.single("zig-install-prefix")) |zig_install_prefix| {
try build_args.append(zig_install_prefix);
}
var proc = try os.ChildProcess.init(build_args.toSliceConst(), allocator);
defer proc.deinit();
var term = try proc.spawnAndWait();
switch (term) {
os.ChildProcess.Term.Exited => |status| {
if (status != 0) {
try stderr.print("{} exited with status {}\n", build_args.at(0), status);
os.exit(1);
}
},
os.ChildProcess.Term.Signal => |signal| {
try stderr.print("{} killed by signal {}\n", build_args.at(0), signal);
os.exit(1);
},
os.ChildProcess.Term.Stopped => |signal| {
try stderr.print("{} stopped by signal {}\n", build_args.at(0), signal);
os.exit(1);
},
os.ChildProcess.Term.Unknown => |status| {
try stderr.print("{} encountered unknown failure {}\n", build_args.at(0), status);
os.exit(1);
},
}
}
// cmd:build-exe ///////////////////////////////////////////////////////////////////////////////////
const usage_build_generic =
\\usage: zig build-exe <options> [file]
\\ zig build-lib <options> [file]
\\ zig build-obj <options> [file]
\\
\\General Options
\\ --help Print this help and exit
\\ --color [auto|off|on] Enable or disable colored error messages
\\
\\Compile Options:
\\ --assembly [source] Add assembly file to build
\\ --cache-dir [path] Override the cache directory
\\ --emit [filetype] Emit a specific file format as compilation output
\\ --enable-timing-info Print timing diagnostics
\\ --libc-include-dir [path] Directory where libc stdlib.h resides
\\ --name [name] Override output name
\\ --output [file] Override destination path
\\ --output-h [file] Override generated header file path
\\ --pkg-begin [name] [path] Make package available to import and push current pkg
\\ --pkg-end Pop current pkg
\\ --release-fast Build with optimizations on and safety off
\\ --release-safe Build with optimizations on and safety on
\\ --static Output will be statically linked
\\ --strip Exclude debug symbols
\\ --target-arch [name] Specify target architecture
\\ --target-environ [name] Specify target environment
\\ --target-os [name] Specify target operating system
\\ --verbose-tokenize Turn on compiler debug output for tokenization
\\ --verbose-ast Turn on compiler debug output for parsing into an AST
\\ --verbose-link Turn on compiler debug output for linking
\\ --verbose-ir Turn on compiler debug output for Zig IR
\\ --verbose-llvm-ir Turn on compiler debug output for LLVM IR
\\ --verbose-cimport Turn on compiler debug output for C imports
\\ --zig-install-prefix [path] Override directory where zig thinks it is installed
\\ -dirafter [dir] Same as -isystem but do it last
\\ -isystem [dir] Add additional search path for other .h files
\\ -mllvm [arg] Additional arguments to forward to LLVM's option processing
\\
\\Link Options:
\\ --ar-path [path] Set the path to ar
\\ --dynamic-linker [path] Set the path to ld.so
\\ --each-lib-rpath Add rpath for each used dynamic library
\\ --libc-lib-dir [path] Directory where libc crt1.o resides
\\ --libc-static-lib-dir [path] Directory where libc crtbegin.o resides
\\ --msvc-lib-dir [path] (windows) directory where vcruntime.lib resides
\\ --kernel32-lib-dir [path] (windows) directory where kernel32.lib resides
\\ --library [lib] Link against lib
\\ --forbid-library [lib] Make it an error to link against lib
\\ --library-path [dir] Add a directory to the library search path
\\ --linker-script [path] Use a custom linker script
\\ --object [obj] Add object file to build
\\ -rdynamic Add all symbols to the dynamic symbol table
\\ -rpath [path] Add directory to the runtime library search path
\\ -mconsole (windows) --subsystem console to the linker
\\ -mwindows (windows) --subsystem windows to the linker
\\ -framework [name] (darwin) link against framework
\\ -mios-version-min [ver] (darwin) set iOS deployment target
\\ -mmacosx-version-min [ver] (darwin) set Mac OS X deployment target
\\ --ver-major [ver] Dynamic library semver major version
\\ --ver-minor [ver] Dynamic library semver minor version
\\ --ver-patch [ver] Dynamic library semver patch version
\\
\\
;
const args_build_generic = []Flag {
Flag.Bool("--help"),
Flag.Option("--color", []const []const u8 { "auto", "off", "on" }),
Flag.Arg1("--assembly"),
Flag.Arg1("--cache-dir"),
Flag.Option("--emit", []const []const u8 { "asm", "bin", "llvm-ir" }),
Flag.Bool("--enable-timing-info"),
Flag.Arg1("--libc-include-dir"),
Flag.Arg1("--name"),
Flag.Arg1("--output"),
Flag.Arg1("--output-h"),
// NOTE: Parsed manually after initial check
Flag.ArgN("--pkg-begin", 2),
Flag.Bool("--pkg-end"),
Flag.Bool("--release-fast"),
Flag.Bool("--release-safe"),
Flag.Bool("--static"),
Flag.Bool("--strip"),
Flag.Arg1("--target-arch"),
Flag.Arg1("--target-environ"),
Flag.Arg1("--target-os"),
Flag.Bool("--verbose-tokenize"),
Flag.Bool("--verbose-ast"),
Flag.Bool("--verbose-link"),
Flag.Bool("--verbose-ir"),
Flag.Bool("--verbose-llvm-ir"),
Flag.Bool("--verbose-cimport"),
Flag.Arg1("--zig-install-prefix"),
Flag.Arg1("-dirafter"),
Flag.Arg1("-isystem"),
Flag.Arg1("-mllvm"),
Flag.Arg1("--ar-path"),
Flag.Arg1("--dynamic-linker"),
Flag.Bool("--each-lib-rpath"),
Flag.Arg1("--libc-lib-dir"),
Flag.Arg1("--libc-static-lib-dir"),
Flag.Arg1("--msvc-lib-dir"),
Flag.Arg1("--kernel32-lib-dir"),
Flag.Arg1("--library"),
Flag.Arg1("--forbid-library"),
Flag.Arg1("--library-path"),
Flag.Arg1("--linker-script"),
// TODO: Collect disjoint many arguments into the same array. Maybe redo the null behavior to
// read all until next flag '-' leading and special case the runtime argument specified.
Flag.ArgN("--object", 1),
// NOTE: Removed -L since it would need to be special-cased and we have an alias in library-path
Flag.Bool("-rdynamic"),
Flag.Arg1("-rpath"),
Flag.Bool("-mconsole"),
Flag.Bool("-mwindows"),
Flag.Arg1("-framework"),
Flag.Arg1("-mios-version-min"),
Flag.Arg1("-mmacosx-version-min"),
Flag.Arg1("--ver-major"),
Flag.Arg1("--ver-minor"),
Flag.Arg1("--ver-patch"),
};
const OutputType = enum {
Exe,
Obj,
Lib,
};
const BuildMode = enum {
Debug,
ReleaseSafe,
ReleaseFast,
};
const OutputColor = enum {
Auto,
On,
Off,
};
const EmitType = enum {
Assembly,
Binary,
LLVMIr,
};
const CliPkg = struct {
name: []const u8,
path: []const u8,
children: ArrayList(&CliPkg),
parent: ?&CliPkg,
pub fn init(allocator: &Allocator, name: []const u8, path: []const u8, parent: ?&CliPkg) !&CliPkg {
var pkg = try allocator.create(CliPkg);
pkg.name = name;
pkg.path = path;
pkg.children = ArrayList(&CliPkg).init(allocator);
pkg.parent = parent;
return pkg;
}
pub fn deinit(self: &CliPkg) void {
for (self.children.toSliceConst()) |child| {
child.deinit();
}
self.children.deinit();
}
};
fn buildOutputType(allocator: &Allocator, args: []const []const u8, out_type: OutputType) !void {
var flags = try Args.parse(allocator, args_build_generic, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_build_generic);
os.exit(0);
}
// NOTE: Have an implied preference if multiple specified
var build_mode = BuildMode.Debug;
if (flags.present("release-fast")) {
build_mode = BuildMode.ReleaseFast;
} else if (flags.present("release-safe")) {
build_mode = BuildMode.ReleaseSafe;
}
// TODO: pkg_begin handling
// TODO: Automatic conversions associating string with enum type?
var color = OutputColor.Auto;
if (flags.single("color")) |color_flag| {
if (mem.eql(u8, color_flag, "auto")) {
color = OutputColor.Auto;
} else if (mem.eql(u8, color_flag, "on")) {
color = OutputColor.On;
} else if (mem.eql(u8, color_flag, "off")) {
color = OutputColor.Off;
} else {
unreachable;
}
}
var emit_type = EmitType.Binary;
if (flags.single("emit")) |emit_flag| {
if (mem.eql(u8, emit_flag, "asm")) {
emit_type = EmitType.Assembly;
} else if (mem.eql(u8, emit_flag, "bin")) {
emit_type = EmitType.Binary;
} else if (mem.eql(u8, emit_flag, "llvm-ir")) {
emit_type = EmitType.LLVMIr;
} else {
unreachable;
}
}
var cur_pkg = try CliPkg.init(allocator, "", "", null); // TODO: Need a path, name?
defer cur_pkg.deinit();
var i: usize = 0;
while (i < args.len) : (i += 1) {
const arg_name = args[i];
if (mem.eql(u8, "--pkg-begin", arg_name)) {
// following two arguments guaranteed to exist due to arg parsing
i += 1;
const new_pkg_name = args[i];
i += 1;
const new_pkg_path = args[i];
var new_cur_pkg = try CliPkg.init(allocator, new_pkg_name, new_pkg_path, cur_pkg);
try cur_pkg.children.append(new_cur_pkg);
cur_pkg = new_cur_pkg;
} else if (mem.eql(u8, "--pkg-end", arg_name)) {
if (cur_pkg.parent == null) {
try stderr.print("encountered --pkg-end with no matching --pkg-begin\n");
os.exit(1);
}
cur_pkg = ??cur_pkg.parent;
}
}
if (cur_pkg.parent != null) {
try stderr.print("unmatched --pkg-begin\n");
os.exit(1);
}
// initAllTargets();
// const target = try ZigTarget.parse(flags.single("target-arch"), flags.single("target-os"), flags.single("target-environ"));
// build is all identical, run doesn't need anywhere near the arguments, test is potentially
// fairly similar. Translate-c can drop half the codegen and initialization.
// TODO: enforce one positional max
var in_file: ?[]const u8 = null;
if (flags.positionals.len != 0) {
in_file = flags.positionals.at(0);
}
// TODO: Needs many arg change.
const assembly = flags.many("assembly");
const objects = flags.many("object");
if (in_file == null and (objects == null or (??objects).len == 0) and (assembly == null or (??assembly).len == 0)) {
try stderr.write("Expected source file argument or at least one --object or --assembly argument\n");
os.exit(1);
}
// Do this sanity check at the top-level.
if (out_type == OutputType.Obj and (objects != null and (??objects).len != 0)) {
try stderr.write("When building an object file, --object arguments are invalid\n");
os.exit(1);
}
// TODO: Get extension name here and construct output path. Build always needs an input file.
// Can always infer the --name argument if not present.
const zig_root_source_file = in_file;
const full_cache_dir = os.path.resolve(allocator, ".", flags.single("cache-dir") ?? "zig-cache"[0..]) catch {
os.exit(1);
};
defer allocator.free(full_cache_dir);
const zig_lib_dir = introspect.resolveZigLibDir(allocator, flags.single("zig-install-prefix") ?? null) catch {
os.exit(1);
};
defer allocator.free(zig_lib_dir);
// var g = Codegen.create(zig_root_source_file, target, out_type, build_mode, zig_lib_dir_buf);
// g.setOutName(out_name);
// g.setLibVersion(0, 0, 0); // TODO: version conversion int
// g.isTest(false);
// g.setLinkerScript(flags.single("linker-script"));
// g.setCacheDir(full_cache_dir);
// g.setEachLibRpath(flags.present("each-lib-rpath"));
// // TODO: Prepend -mllvm for clang
// g.setClangArgv(flags.many("mllvm"));
// g.setLlvmArgv(flags.many("mllvm"));
// g.setStrip(flags.present("strip"));
// g.setIsStatic(flags.present("static"));
// if (flags.single("libc-lib-dir")) |ok| g.setLibCLibDir(ok);
// if (flags.single("libc-static-lib-dir")) |ok| g.setLibCStaticLibDir(ok);
// if (flags.single("libc-include-dir")) |ok| g.setLibCIncludeDir(ok);
// if (flags.single("msvc-lib-dir")) |ok| g.setMsvcLibDir(ok);
// if (flags.single("kernel32-lib-dir")) |ok| g.setKernel32LibDir(ok);
// if (flags.single("dynamic-linker")) |ok| g.setDynamicLinker(ok);
// g.verbose_tokenize = flags.present("verbose-tokenize");
// g.verbose_ast = flags.present("verbose-ast");
// g.verbose_link = flags.present("verbose-link");
// g.verbose_ir = flags.present("verbose-ir");
// g.verbose_llvm_ir = flags.present("verbose-llvm-ir");
// g.verbose_cimport = flags.present("verbose-cimport");
// g.setErrMsgColor(color);
// for (flags.many("library-path")) |lib_dir| g.addLibDir(lib_dir);
// // etc...
// g.setWindowsSubsystem(flags.single("mwindows"), flags.single("mconsole"));
// g.setRDynamic(flags.single("rdynamic"));
// if (flags.single("mmacosx-version-min") and flags.single("mios-version-min")) {
// stderr.write("-mmacosx-version-min and -mios-version-min options not allowed together\n");
// os.exit(1);
// }
// if (flags.single("mmacosx-version-min")) |ok| g.setMmacosXVersionMin(ok);
// if (flags.single("mios-version-min")) |ok| g.setMiosVersionMin(ok);
// if (flags.single("output-h")) |ok| g.setOutputHPath(ok);
// // add package, root
// codegen_set_emit_file_type(g, out_type)
// for (flags.many("object")) |object| {
// codegen_add_object(g, object);
// }
// for (flags.many("assembly")) |assembly| {
// codegen_add_assembly(g, assembly);
// }
// codegen_build(g);
// codegen_link(g, out_file);
if (flags.present("print-timing-info")) {
// codegen_print_timing_info(g, stderr);
}
try stderr.print("building {}: {}\n", @tagName(out_type), in_file);
}
fn cmdBuildExe(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, OutputType.Exe);
}
// cmd:build-lib ///////////////////////////////////////////////////////////////////////////////////
fn cmdBuildLib(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, OutputType.Lib);
}
// cmd:build-obj ///////////////////////////////////////////////////////////////////////////////////
fn cmdBuildObj(allocator: &Allocator, args: []const []const u8) !void {
try buildOutputType(allocator, args, OutputType.Obj);
}
// cmd:cc //////////////////////////////////////////////////////////////////////////////////////////
fn cmdCc(allocator: &Allocator, args: []const []const u8) !void {
// TODO: Would be nice to use libclang directly but I don't think the argument parsing is
// exposed in an easy to use way.
var command = ArrayList([]const u8).init(allocator);
defer command.deinit();
try command.append("cc");
try command.appendSlice(args);
var proc = try os.ChildProcess.init(command.toSliceConst(), allocator);
defer proc.deinit();
var term = try proc.spawnAndWait();
switch (term) {
os.ChildProcess.Term.Exited => |status| {
if (status != 0) {
try stderr.print("cc exited with status {}\n", status);
os.exit(1);
}
},
os.ChildProcess.Term.Signal => |signal| {
try stderr.print("cc killed by signal {}\n", signal);
os.exit(1);
},
os.ChildProcess.Term.Stopped => |signal| {
try stderr.print("cc stopped by signal {}\n", signal);
os.exit(1);
},
os.ChildProcess.Term.Unknown => |status| {
try stderr.print("cc encountered unknown failure {}\n", status);
os.exit(1);
},
}
}
// cmd:fmt /////////////////////////////////////////////////////////////////////////////////////////
const usage_fmt =
\\usage: zig fmt [file]...
\\
\\ Formats the input files and modifies them in-place.
\\
\\Options:
\\ --help Print this help and exit
\\ --keep-backups Retain backup entries for every file
\\
\\
;
const args_fmt_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--keep-backups"),
};
fn cmdFmt(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_fmt_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_fmt);
os.exit(0);
}
if (flags.positionals.len == 0) {
try stderr.write("expected at least one source file argument\n");
os.exit(1);
}
for (flags.positionals.toSliceConst()) |file_path| {
var file = try os.File.openRead(allocator, file_path);
defer file.close();
const source_code = io.readFileAlloc(allocator, file_path) catch |err| {
try stderr.print("unable to open '{}': {}", file_path, err);
continue;
};
defer allocator.free(source_code);
var tokenizer = std.zig.Tokenizer.init(source_code);
var parser = std.zig.Parser.init(&tokenizer, allocator, file_path);
defer parser.deinit();
var tree = parser.parse() catch |err| {
try stderr.print("error parsing file '{}': {}\n", file_path, err);
continue;
};
defer tree.deinit();
var original_file_backup = try Buffer.init(allocator, file_path);
defer original_file_backup.deinit();
try original_file_backup.append(".backup");
try os.rename(allocator, file_path, original_file_backup.toSliceConst());
try stderr.print("{}\n", file_path);
// TODO: BufferedAtomicFile has some access problems.
var out_file = try os.File.openWrite(allocator, file_path);
defer out_file.close();
var out_file_stream = io.FileOutStream.init(&out_file);
try parser.renderSource(out_file_stream.stream, tree.root_node);
if (!flags.present("keep-backups")) {
try os.deleteFile(allocator, original_file_backup.toSliceConst());
}
}
}
// cmd:targets /////////////////////////////////////////////////////////////////////////////////////
// TODO: comptime '@fields' for iteration here instead so we are always in sync.
const Os = builtin.Os;
pub const os_list = []const Os {
Os.freestanding,
Os.ananas,
Os.cloudabi,
Os.dragonfly,
Os.freebsd,
Os.fuchsia,
Os.ios,
Os.kfreebsd,
Os.linux,
Os.lv2,
Os.macosx,
Os.netbsd,
Os.openbsd,
Os.solaris,
Os.windows,
Os.haiku,
Os.minix,
Os.rtems,
Os.nacl,
Os.cnk,
// Os.bitrig,
Os.aix,
Os.cuda,
Os.nvcl,
Os.amdhsa,
Os.ps4,
Os.elfiamcu,
Os.tvos,
Os.watchos,
Os.mesa3d,
Os.contiki,
Os.zen,
};
const Arch = builtin.Arch;
pub const arch_list = []const Arch {
Arch.armv8_2a,
Arch.armv8_1a,
Arch.armv8,
Arch.armv8r,
Arch.armv8m_baseline,
Arch.armv8m_mainline,
Arch.armv7,
Arch.armv7em,
Arch.armv7m,
Arch.armv7s,
Arch.armv7k,
Arch.armv7ve,
Arch.armv6,
Arch.armv6m,
Arch.armv6k,
Arch.armv6t2,
Arch.armv5,
Arch.armv5te,
Arch.armv4t,
// Arch.armeb,
Arch.aarch64,
Arch.aarch64_be,
Arch.avr,
Arch.bpfel,
Arch.bpfeb,
Arch.hexagon,
Arch.mips,
Arch.mipsel,
Arch.mips64,
Arch.mips64el,
Arch.msp430,
Arch.nios2,
Arch.powerpc,
Arch.powerpc64,
Arch.powerpc64le,
Arch.r600,
Arch.amdgcn,
Arch.riscv32,
Arch.riscv64,
Arch.sparc,
Arch.sparcv9,
Arch.sparcel,
Arch.s390x,
Arch.tce,
Arch.tcele,
Arch.thumb,
Arch.thumbeb,
Arch.i386,
Arch.x86_64,
Arch.xcore,
Arch.nvptx,
Arch.nvptx64,
Arch.le32,
Arch.le64,
Arch.amdil,
Arch.amdil64,
Arch.hsail,
Arch.hsail64,
Arch.spir,
Arch.spir64,
Arch.kalimbav3,
Arch.kalimbav4,
Arch.kalimbav5,
Arch.shave,
Arch.lanai,
Arch.wasm32,
Arch.wasm64,
Arch.renderscript32,
Arch.renderscript64,
};
const Environ = builtin.Environ;
pub const environ_list = []const Environ {
Environ.unknown,
Environ.gnu,
Environ.gnuabi64,
Environ.gnueabi,
Environ.gnueabihf,
Environ.gnux32,
Environ.code16,
Environ.eabi,
Environ.eabihf,
Environ.android,
Environ.musl,
Environ.musleabi,
Environ.musleabihf,
Environ.msvc,
Environ.itanium,
Environ.cygnus,
Environ.amdopencl,
Environ.coreclr,
Environ.opencl,
};
fn cmdTargets(allocator: &Allocator, args: []const []const u8) !void {
try stdout.write("Architectures:\n");
for (arch_list) |arch_tag| {
const native_str = if (builtin.arch == arch_tag) " (native) " else "";
try stdout.print(" {}{}\n", @tagName(arch_tag), native_str);
}
try stdout.write("\n");
try stdout.write("Operating Systems:\n");
for (os_list) |os_tag| {
const native_str = if (builtin.os == os_tag) " (native) " else "";
try stdout.print(" {}{}\n", @tagName(os_tag), native_str);
}
try stdout.write("\n");
try stdout.write("Environments:\n");
for (environ_list) |environ_tag| {
const native_str = if (builtin.environ == environ_tag) " (native) " else "";
try stdout.print(" {}{}\n", @tagName(environ_tag), native_str);
}
}
// cmd:version /////////////////////////////////////////////////////////////////////////////////////
fn cmdVersion(allocator: &Allocator, args: []const []const u8) !void {
const c = struct { const ZIG_VERSION_STRING = c"placeholder"; };
try stdout.print("{}\n", std.cstr.toSliceConst(c.ZIG_VERSION_STRING));
}
// cmd:test ////////////////////////////////////////////////////////////////////////////////////////
const usage_test =
\\usage: zig test [file]...
\\
\\Options:
\\ --help Print this help and exit
\\
\\
;
const args_test_spec = []Flag {
Flag.Bool("--help"),
};
fn cmdTest(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_build_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_test);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one zig source file\n");
os.exit(1);
}
// compile the test program into the cache and run
// See what the overlap is between this and build-exe etc. Depends on the command line requirements.
try stderr.print("testing file {}\n", flags.positionals.at(0));
}
// cmd:run /////////////////////////////////////////////////////////////////////////////////////////
// TODO: We may want to simplify the run interface. It should be for simple quick scripts and if you
// need something more complex use `zig build-exe` and run manually.
const usage_run =
\\usage: zig run [file] -- <runtime args>
\\
\\Options:
\\ --help Print this help and exit
\\
\\
;
const args_run_spec = []Flag {
Flag.Bool("--help"),
};
fn cmdRun(allocator: &Allocator, args: []const []const u8) !void {
var compile_args = args;
var runtime_args: []const []const u8 = []const []const u8 {};
for (args) |argv, i| {
if (mem.eql(u8, argv, "--")) {
compile_args = args[0..i];
runtime_args = args[i+1..];
break;
}
}
var flags = try Args.parse(allocator, args_run_spec, compile_args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_run);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one zig source file\n");
os.exit(1);
}
try stderr.print("runtime args:\n");
for (runtime_args) |cargs| {
try stderr.print("{}\n", cargs);
}
}
// cmd:translate-c /////////////////////////////////////////////////////////////////////////////////
const usage_translate_c =
\\usage: zig translate-c [file]
\\
\\Options:
\\ --help Print this help and exit
\\ --enable-timing-info Print timing diagnostics
\\ --output [path] Output file to write generated zig file (default: stdout)
\\
\\
;
const args_translate_c_spec = []Flag {
Flag.Bool("--help"),
Flag.Bool("--enable-timing-info"),
Flag.Arg1("--libc-include-dir"),
Flag.Arg1("--output"),
};
fn cmdTranslateC(allocator: &Allocator, args: []const []const u8) !void {
var flags = try Args.parse(allocator, args_translate_c_spec, args);
defer flags.deinit();
if (flags.present("help")) {
try stderr.write(usage_translate_c);
os.exit(0);
}
if (flags.positionals.len != 1) {
try stderr.write("expected exactly one c source file\n");
os.exit(1);
}
// set up codegen
const zig_root_source_file = null;
// can we limit this to just what we need, i'm pretty sure the C++ version
// sets way more than we need and there are very few applicable arguments.
// codegen_create(g);
// codegen_set_out_name(g, null);
// codegen_translate_c(g, flags.positional.at(0))
var output_stream = stdout;
if (flags.single("output")) |output_file| {
var file = try os.File.openWrite(allocator, output_file);
defer file.close();
var file_stream = io.FileOutStream.init(&file);
// TODO: Not being set correctly, still stdout
output_stream = &file_stream.stream;
}
// ast_render(g, output_stream, g->root_import->root, 4);
try output_stream.write("pub const example = 10;\n");
if (flags.present("enable-timing-info")) {
// codegen_print_timing_info(g, stdout);
try stderr.write("printing timing info for translate-c\n");
}
}
// cmd:help ////////////////////////////////////////////////////////////////////////////////////////
fn cmdHelp(allocator: &Allocator, args: []const []const u8) !void {
try stderr.write(usage);
}
// cmd:zen /////////////////////////////////////////////////////////////////////////////////////////
const info_zen =
\\
\\ * Communicate intent precisely.
\\ * Edge cases matter.
\\ * Favor reading code over writing code.
\\ * Only one obvious way to do things.
\\ * Runtime crashes are better than bugs.
\\ * Compile errors are better than runtime crashes.
\\ * Incremental improvements.
\\ * Avoid local maximums.
\\ * Reduce the amount one must remember.
\\ * Minimize energy spent on coding style.
\\ * Together we serve end users.
\\
\\
;
fn cmdZen(allocator: &Allocator, args: []const []const u8) !void {
try stdout.write(info_zen);
}
// cmd:internal ////////////////////////////////////////////////////////////////////////////////////
const usage_internal =
\\usage: zig internal [subcommand]
\\
\\Sub-Commands:
\\ build-info Print static compiler build-info
\\
\\
;
fn cmdInternal(allocator: &Allocator, args: []const []const u8) !void {
if (args.len == 0) {
try stderr.write(usage_internal);
os.exit(1);
}
const sub_commands = []Command {
Command { .name = "build-info", .exec = cmdInternalBuildInfo },
};
for (sub_commands) |sub_command| {
if (mem.eql(u8, sub_command.name, args[0])) {
try sub_command.exec(allocator, args[1..]);
return;
}
}
try stderr.print("unknown sub command: {}\n\n", args[0]);
try stderr.write(usage_internal);
}
fn cmdInternalBuildInfo(allocator: &Allocator, args: []const []const u8) !void {
const c = struct {
const ZIG_CMAKE_BINARY_DIR = "placeholder";
const ZIG_CXX_COMPILER = "placeholder";
const ZIG_LLVM_CONFIG_EXE = "placeholder";
const ZIG_LLD_INCLUDE_PATH = "placeholder";
const ZIG_LLD_LIBRARIES = "placeholder";
const ZIG_STD_FILES = "placeholder";
const ZIG_C_HEADER_FILES = "placeholder";
const ZIG_DIA_GUIDS_LIB = "placeholder";
};
try stdout.print(
\\ZIG_CMAKE_BINARY_DIR {}
\\ZIG_CXX_COMPILER {}
\\ZIG_LLVM_CONFIG_EXE {}
\\ZIG_LLD_INCLUDE_PATH {}
\\ZIG_LLD_LIBRARIES {}
\\ZIG_STD_FILES {}
\\ZIG_C_HEADER_FILES {}
\\ZIG_DIA_GUIDS_LIB {}
\\
,
c.ZIG_CMAKE_BINARY_DIR,
c.ZIG_CXX_COMPILER,
c.ZIG_LLVM_CONFIG_EXE,
c.ZIG_LLD_INCLUDE_PATH,
c.ZIG_LLD_LIBRARIES,
c.ZIG_STD_FILES,
c.ZIG_C_HEADER_FILES,
c.ZIG_DIA_GUIDS_LIB,
);
} | src/main.zig |
const std = @import("std");
const LineReader = @import("LineReader.zig").LineReader;
const ByteWriter = @import("ByteWriter.zig").ByteWriter;
const imageExtensions = [_][]const u8{
".png",
".jpeg",
".jpg",
".gif",
".webp",
};
const videoExtensions = [_][]const u8{
".mp4",
};
const audioExtensions = [_][]const u8{
".mp3",
".wav",
".ogg",
};
const HTTPS_SCHEME = "https";
fn trimLeft(str: []const u8) []const u8 {
return std.mem.trimLeft(u8, str, &[_]u8{' ', '\t'});
}
fn isWebUrl(url: []const u8) bool {
const scheme = for (url) |char, i| {
if (char == ':') {
break url[0..i];
} else if (char == '/') {
return true;
}
} else return true;
if (scheme.len > 5 or scheme.len < 4) {
return false;
}
for (scheme) |char, i| {
if (std.ascii.toLower(char) != HTTPS_SCHEME[i]) {
return false;
}
}
return true;
}
fn matchesExtension(url: []const u8, extensions: []const []const u8) bool {
for (extensions) |extension| {
if (url.len >= extension.len and std.mem.eql(u8, url[url.len-extension.len..], extension)) {
return true;
}
}
return false;
}
const State = struct {
bullets: bool = false,
preformatted: bool = false,
inlineImages: bool = false,
inlineVideo: bool = false,
inlineAudio: bool = false,
};
fn handleLine(line: []const u8, writer: *ByteWriter, state: *State) !void {
if (line.len >= 1 and line[0] == '*' and !state.bullets) {
state.bullets = true;
try writer.writeBytes("<ul>\n");
} else if (state.bullets and (line.len == 0 or line[0] != '*')) {
state.bullets = false;
try writer.writeBytes("</ul>\n");
}
if (state.preformatted) {
if (line.len >= 3 and line[0] == '`' and line[1] == '`' and line[2] == '`') {
state.preformatted = false;
return writer.writeBytes("</pre>\n");
} else {
try writer.writeEscapedBytes(line);
return writer.writeByte('\n');
}
}
if (line.len >= 3) {
if (line[0] == '#' and line[1] == '#' and line[2] == '#') {
try writer.writeBytes("<h3>");
try writer.writeEscapedBytes(trimLeft(line[3..]));
return writer.writeBytes("</h3>\n");
}
if (line[0] == '`' and line[1] == '`' and line[2] == '`') {
state.preformatted = true;
const altText = trimLeft(line[3..]);
if (altText.len == 0) {
return writer.writeBytes("<pre>\n");
} else {
try writer.writeBytes("<pre alt=\"");
try writer.writeEscapedBytes(altText);
return writer.writeBytes("\">\n");
}
}
}
if (line.len >= 2) {
if (line[0] == '#' and line[1] == '#') {
try writer.writeBytes("<h2>");
try writer.writeEscapedBytes(trimLeft(line[2..]));
return writer.writeBytes("</h2>\n");
}
if (line[0] == '=' and line[1] == '>') {
const contents = trimLeft(line[2..]);
var spaceIndex: usize = 0;
while (spaceIndex < contents.len) : (spaceIndex += 1) {
if (contents[spaceIndex] == ' ' or contents[spaceIndex] == '\t') break;
}
const url = contents[0..spaceIndex];
var text = trimLeft(contents[spaceIndex..]);
if (text.len == 0) {
text = url;
}
if (state.inlineImages and isWebUrl(url) and matchesExtension(url, &imageExtensions)) {
try writer.writeBytes("<a style=\"display: block;\" href=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\">");
try writer.writeBytes("<img src=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\" alt=\"");
try writer.writeEscapedBytes(text);
try writer.writeBytes("\"/>");
try writer.writeBytes("</a>\n");
} else if (state.inlineVideo and isWebUrl(url) and matchesExtension(url, &videoExtensions)) {
try writer.writeBytes("<video style=\"display: block;\" controls src=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\"><a src=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\">");
try writer.writeEscapedBytes(text);
try writer.writeBytes("</a></video>\n");
} else if (state.inlineAudio and isWebUrl(url) and matchesExtension(url, &audioExtensions)) {
try writer.writeBytes("<audio style=\"display: block;\" controls src=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\"><a src=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\">");
try writer.writeEscapedBytes(text);
try writer.writeBytes("</a></audio>\n");
} else if (isWebUrl(url)) {
try writer.writeBytes("<a style=\"display: block;\" href=\"");
try writer.writeEscapedBytes(url);
try writer.writeBytes("\">");
try writer.writeEscapedBytes(text);
try writer.writeBytes("</a>\n");
} else {
try writer.writeBytes("<p>");
try writer.writeEscapedBytes(line);
return writer.writeBytes("</p>\n");
}
return;
}
}
if (line.len >= 1) {
if (line[0] == '#') {
try writer.writeBytes("<h1>");
try writer.writeEscapedBytes(trimLeft(line[1..]));
return writer.writeBytes("</h1>\n");
}
if (line[0] == '*') {
try writer.writeBytes("<li>");
try writer.writeEscapedBytes(trimLeft(line[1..]));
return writer.writeBytes("</li>\n");
}
if (line[0] == '>') {
try writer.writeBytes("<blockquote>");
try writer.writeEscapedBytes(trimLeft(line[1..]));
return writer.writeBytes("</blockquote>\n");
}
}
try writer.writeBytes("<p>");
if (line.len == 0) {
try writer.writeBytes("<br/>");
} else {
try writer.writeEscapedBytes(line);
}
return writer.writeBytes("</p>\n");
}
const help =
\\Usage: gmi2html [options]
\\
\\Reads text/gemini from stdin and writes HTML to stdout.
\\
\\Options:
\\--inline-images Translate links to images as <img> elements
\\--inline-video Translate links to videos as <video> elements
\\--inline-audio Translate links to audio as <audio> elements
\\--inline-all Short for --inline-images --inline-video --inline-audio
\\--help Display this message
\\--version Display version
\\
;
pub fn main() anyerror!u8 {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var args = std.process.args();
defer args.deinit();
_ = args.skip();
var state = State {};
const stderr = std.io.getStdErr().writer();
const stdout = std.io.getStdOut().writer();
while (args.next(allocator)) |maybeArg| {
const arg = try maybeArg;
if (std.mem.eql(u8, arg, "--inline-images")) {
state.inlineImages = true;
} else if (std.mem.eql(u8, arg, "--inline-video")) {
state.inlineVideo = true;
} else if (std.mem.eql(u8, arg, "--inline-audio")) {
state.inlineAudio = true;
} else if (std.mem.eql(u8, arg, "--inline-all")) {
state.inlineImages = true;
state.inlineVideo = true;
state.inlineAudio = true;
} else if (std.mem.eql(u8, arg, "--help")) {
try stdout.writeAll(help);
return 0;
} else if (std.mem.eql(u8, arg, "--version")) {
try stdout.writeAll("gmi2html v0.4.0\n");
return 0;
} else {
try stderr.print("Unrecognized option: {s}\n\n", .{arg});
try stderr.writeAll(help);
return 1;
}
}
var reader = try LineReader.init(allocator, std.io.getStdIn().reader());
var writer = ByteWriter.init(stdout);
while (try reader.readLine()) |line| {
try handleLine(line, &writer, &state);
}
try writer.flush();
return 0;
} | src/main.zig |
const std = @import("std");
const mpack = @import("./mpack.zig");
const ArrayList = std.ArrayList;
const mem = std.mem;
const stringToEnum = std.meta.stringToEnum;
const dbg = std.debug.print;
//pub fn dbg(a: anytype, b: anytype) void {}
const AttrOffset = struct { start: u32, end: u32 };
attr_arena: ArrayList(u8),
attr_off: ArrayList(AttrOffset),
writer: @TypeOf(std.io.getStdOut().writer()),
cursor: struct { grid: u32, row: u16, col: u16 } = undefined,
default_colors: struct { fg: u32, bg: u32, sp: u32 } = undefined,
grid: [1]Grid,
attr_id: u16 = 0,
frame: ?anyframe = null,
const Self = @This();
const Grid = struct {
rows: u16,
cols: u16,
cell: ArrayList(Cell),
};
const charsize = 8;
const Cell = struct {
char: [charsize]u8,
attr_id: u16,
};
pub fn init(allocator: *mem.Allocator) Self {
return .{
.attr_arena = ArrayList(u8).init(allocator),
.attr_off = ArrayList(AttrOffset).init(allocator),
.writer = std.io.getStdOut().writer(),
.grid = .{.{ .rows = 0, .cols = 0, .cell = ArrayList(Cell).init(allocator) }},
};
}
pub const RPCError = mpack.Decoder.Error || error{
MalformatedRPCMessage,
InvalidRedraw,
OutOfMemory,
IOError,
};
pub fn decodeLoop(self: *Self, decoder: *mpack.Decoder) RPCError!void {
while (true) {
try decoder.start();
var msgHead = try decoder.expectArray();
if (msgHead < 3) {
return RPCError.MalformatedRPCMessage;
}
var msgKind = try decoder.expectUInt();
switch (msgKind) {
1 => try self.decodeResponse(decoder, msgHead),
2 => try self.decodeEvent(decoder, msgHead),
else => return error.MalformatedRPCMessage,
}
}
}
fn decodeResponse(self: *Self, decoder: *mpack.Decoder, arraySize: u32) RPCError!void {
_ = self;
if (arraySize != 4) {
return error.MalformatedRPCMessage;
}
var id = try decoder.expectUInt();
dbg("id: {}\n", .{id});
var state = try decoder.readHead();
dbg("{}\n", .{state});
state = try decoder.readHead();
dbg("{}\n", .{state});
}
fn decodeEvent(self: *Self, decoder: *mpack.Decoder, arraySize: u32) RPCError!void {
if (arraySize != 3) {
return error.MalformatedRPCMessage;
}
var name = try decoder.expectString();
if (mem.eql(u8, name, "redraw")) {
try self.handleRedraw(decoder);
} else {
// TODO: untested
dbg("FEEEEL: {s}\n", .{name});
try decoder.skipAhead(1); // args array
}
}
const RedrawEvents = enum {
hl_attr_define,
hl_group_set,
grid_resize,
grid_clear,
grid_line,
grid_cursor_goto,
default_colors_set,
flush,
Unknown,
};
fn handleRedraw(self: *Self, decoder: *mpack.Decoder) RPCError!void {
dbg("==BEGIN REDRAW\n", .{});
var args = try decoder.expectArray();
dbg("n-event: {}\n", .{args});
while (args > 0) : (args -= 1) {
const saved = try decoder.push();
const iargs = try decoder.expectArray();
const iname = try decoder.expectString();
const event = stringToEnum(RedrawEvents, iname) orelse .Unknown;
var iiarg: u32 = 1;
switch (event) {
.grid_resize => {
while (iiarg < iargs) : (iiarg += 1) {
try self.handleGridResize(decoder);
}
},
.grid_clear => {
while (iiarg < iargs) : (iiarg += 1) {
try self.handleGridClear(decoder);
}
},
.grid_line => try self.handleGridLine(decoder, iargs - 1),
.flush => {
//if (iargs != 2 or try decoder.expectArray() > 0) {
// return error.InvalidRedraw;
// }
try decoder.skipAhead(iargs - 1);
dbg("==FLUSHED\n", .{});
suspend {
self.frame = @frame();
}
self.frame = null;
//std.time.sleep(1000 * 1000000);
},
.hl_attr_define => {
try self.handleHlAttrDef(decoder, iargs - 1);
},
.grid_cursor_goto => {
try decoder.skipAhead(iargs - 2);
try self.handleCursorGoto(decoder);
},
.default_colors_set => {
try decoder.skipAhead(iargs - 2);
try self.handleDefaultColorsSet(decoder);
},
.hl_group_set => {
try decoder.skipAhead(iargs - 1);
},
.Unknown => {
dbg("! {s} {}\n", .{ iname, iargs - 1 });
try decoder.skipAhead(iargs - 1);
},
}
try decoder.pop(saved);
}
dbg("==DUN REDRAW\n\n", .{});
}
fn handleGridResize(self: *Self, decoder: *mpack.Decoder) RPCError!void {
const saved = try decoder.push();
const iarg = try decoder.expectArray();
const grid_id = try decoder.expectUInt();
if (grid_id != 1) {
@panic("get out!");
}
const grid = &self.grid[grid_id - 1];
grid.cols = @intCast(u16, try decoder.expectUInt());
grid.rows = @intCast(u16, try decoder.expectUInt());
try grid.cell.resize(grid.rows * grid.cols);
try decoder.skipAhead(iarg - 3);
try decoder.pop(saved);
}
fn handleGridClear(self: *Self, decoder: *mpack.Decoder) RPCError!void {
const saved = try decoder.push();
const iarg = try decoder.expectArray();
const grid_id = try decoder.expectUInt();
const grid = &self.grid[grid_id - 1];
var char: [charsize]u8 = undefined;
//char[0..2] = .{ ' ', 0 };
char[0] = ' ';
char[1] = 0;
mem.set(Cell, grid.cell.items, .{ .char = char, .attr_id = 0 });
try decoder.skipAhead(iarg - 1);
try decoder.pop(saved);
}
fn handleGridLine(self: *Self, decoder: *mpack.Decoder, nlines: u32) RPCError!void {
// dbg("==LINES {}\n", .{nlines});
var i: u32 = 0;
while (i < nlines) : (i += 1) {
const saved = try decoder.push();
const iytem = try decoder.expectArray();
const grid_id = try decoder.expectUInt();
const grid = &self.grid[grid_id - 1];
const row = try decoder.expectUInt();
const col = try decoder.expectUInt();
const ncells = try decoder.expectArray();
var pos = row * grid.cols + col;
//dbg("LINE: {} {} {} {}: [", .{ grid_id, row, col, ncells });
//self.writer.print("\x1b[{};{}H", .{ row + 1, col + 1 }) catch return RPCError.IOError;
var j: u32 = 0;
while (j < ncells) : (j += 1) {
const nsize = try decoder.expectArray();
const str = try decoder.expectString();
var used: u8 = 1;
var repeat: u64 = 1;
var attr_id: u16 = self.attr_id;
var char: [charsize]u8 = undefined;
mem.copy(u8, &char, str);
if (str.len < 8) {
char[str.len] = 0;
}
if (nsize >= 2) {
attr_id = @intCast(u16, try decoder.expectUInt());
used = 2;
if (nsize >= 3) {
repeat = try decoder.expectUInt();
used = 3;
}
}
if (attr_id != self.attr_id) {
self.attr_id = attr_id;
const slice = if (attr_id > 0) theslice: {
const islice = self.attr_off.items[attr_id];
//dbg("without chemicals {} he points {} {}", .{ attr_id, islice.start, islice.end });
break :theslice self.attr_arena.items[islice.start..islice.end];
} else "\x1b[0m";
_ = slice;
// self.writer.writeAll(slice) catch return RPCError.IOError;
}
while (repeat > 0) : (repeat -= 1) {
grid.cell.items[pos] = .{ .char = char, .attr_id = attr_id };
pos = pos + 1;
//dbg("{s}", .{str});
// self.writer.writeAll(str) catch return RPCError.IOError;
}
try decoder.skipAhead(nsize - used);
}
//dbg("]\n", .{});
try decoder.skipAhead(iytem - 4);
try decoder.pop(saved);
}
}
pub fn dumpGrid(self: *Self) RPCError!void {
self.writer.print("\x1b[H", .{}) catch return RPCError.IOError;
const grid = &self.grid[0];
var row: u16 = 0;
var attr_id: u16 = 0;
while (row < grid.rows) : (row += 1) {
if (row > 1) {
self.writer.writeAll("\r\n") catch return RPCError.IOError;
}
const o = row * grid.cols;
var col: u16 = 0;
while (col < grid.cols) : (col += 1) {
const c = grid.cell.items[o + col];
var len = mem.indexOfScalar(u8, &c.char, 0) orelse charsize;
if (c.attr_id != attr_id) {
attr_id = c.attr_id;
const slice = if (attr_id > 0) theslice: {
const islice = self.attr_off.items[attr_id];
//dbg("without chemicals {} he points {} {}", .{ attr_id, islice.start, islice.end });
break :theslice self.attr_arena.items[islice.start..islice.end];
} else "\x1b[0m";
self.writer.writeAll(slice) catch return RPCError.IOError;
}
self.writer.writeAll(c.char[0..len]) catch return RPCError.IOError;
}
}
const c = self.cursor;
self.writer.print("\x1b[{};{}H", .{ c.row + 1, c.col + 1 }) catch return RPCError.IOError;
}
//const native_endian = std.Target.current.cpu.arch.endian();
const RGB = struct { b: u8, g: u8, r: u8, a: u8 };
fn doColors(w: anytype, fg: bool, rgb: RGB) RPCError!void {
const kod = if (fg) "3" else "4";
try w.print("\x1b[{s}8;2;{};{};{}m", .{ kod, rgb.r, rgb.g, rgb.b });
}
fn handleHlAttrDef(self: *Self, decoder: *mpack.Decoder, nattrs: u32) RPCError!void {
// dbg("==ATTRS {}\n", .{nattrs});
var i: u32 = 0;
while (i < nattrs) : (i += 1) {
const saved = try decoder.push();
const nsize = try decoder.expectArray();
const id = try decoder.expectUInt();
const rgb_attrs = try decoder.expectMap();
//dbg("ATTEN: {} {}", .{ id, rgb_attrs });
var fg: ?u32 = null;
var bg: ?u32 = null;
var bold = false;
var j: u32 = 0;
while (j < rgb_attrs) : (j += 1) {
const name = try decoder.expectString();
const Keys = enum { foreground, background, bold, Unknown };
const key = stringToEnum(Keys, name) orelse .Unknown;
switch (key) {
.foreground => {
const num = try decoder.expectUInt();
//dbg(" fg={}", .{num});
fg = @intCast(u32, num);
},
.background => {
const num = try decoder.expectUInt();
//dbg(" bg={}", .{num});
bg = @intCast(u32, num);
},
.bold => {
_ = try decoder.readHead();
//dbg(" BOLDEN", .{});
bold = true;
},
.Unknown => {
//dbg(" {s}", .{name});
try decoder.skipAhead(1);
},
}
}
const pos = @intCast(u32, self.attr_arena.items.len);
const w = self.attr_arena.writer();
try w.writeAll("\x1b[0m");
if (fg) |the_fg| {
const rgb = @bitCast(RGB, the_fg);
try doColors(w, true, rgb);
}
if (bg) |the_bg| {
const rgb = @bitCast(RGB, the_bg);
try doColors(w, false, rgb);
}
if (bold) {
try w.writeAll("\x1b[1m");
}
const endpos = @intCast(u32, self.attr_arena.items.len);
try putAt(&self.attr_off, id, .{ .start = pos, .end = endpos });
//dbg("\n", .{});
try decoder.skipAhead(nsize - 2);
try decoder.pop(saved);
}
}
fn handleCursorGoto(self: *Self, decoder: *mpack.Decoder) RPCError!void {
const nsize = try decoder.expectArray();
const grid = @intCast(u32, try decoder.expectUInt());
const row = @intCast(u16, try decoder.expectUInt());
const col = @intCast(u16, try decoder.expectUInt());
try decoder.skipAhead(nsize - 3);
self.cursor = .{ .grid = grid, .row = row, .col = col };
}
fn handleDefaultColorsSet(self: *Self, decoder: *mpack.Decoder) RPCError!void {
const nsize = try decoder.expectArray();
const fg = @intCast(u32, try decoder.expectUInt());
const bg = @intCast(u32, try decoder.expectUInt());
const sp = @intCast(u32, try decoder.expectUInt());
try decoder.skipAhead(nsize - 3);
self.default_colors = .{ .fg = fg, .bg = bg, .sp = sp };
}
fn putAt(array_list: anytype, index: usize, item: anytype) !void {
if (array_list.items.len < index + 1) {
try array_list.resize(index + 1);
}
array_list.items[index] = item;
} | src/RPC.zig |
const std = @import("std");
const fmt = std.fmt;
const fs = std.fs;
const os = std.os;
pub const ProcEntry = struct {
pid: os.pid_t,
dir: fs.Dir,
oom_score: u16 = undefined,
oom_score_adj: i16 = undefined,
exe: [os.PATH_MAX-1:0]u8 = undefined,
vm_rss: u32 = undefined,
pub fn init(pid: os.pid_t, parent_dir: fs.Dir) !ProcEntry {
var pid_buf: [16]u8 = undefined;
var pid_str = try fmt.bufPrint(&pid_buf, "{}", .{pid});
var ret = ProcEntry{ .pid = pid, .dir = try parent_dir.openDir(pid_str, .{}) };
var statm = try ret.slurpIntArray(u32, 3, "statm");
ret.vm_rss = statm[1];
ret.oom_score = try ret.slurpInt(u16, "oom_score");
ret.oom_score_adj = try ret.slurpInt(i16,"oom_score_adj");
const path = try ret.readLink(ret.exe[0..], "exe");
ret.exe[path.len] = 0;
return ret;
}
pub fn slurpString(self: *ProcEntry, buf: []u8, basename: []const u8) ![]u8 {
var file = try self.dir.openFile(basename, .{});
defer file.close();
var reader = file.reader();
var pos = try reader.readAll(buf);
return buf[0..pos];
}
pub fn slurpIntArray(self: *ProcEntry, comptime T: type, comptime N: comptime_int, basename: []const u8) ![N]T {
var tmp_buf: [24 * N]u8 = undefined;
var index: usize = 0;
var ret: [N]T = undefined;
var slurped = try self.slurpString(tmp_buf[0..], basename);
var slurped_it = std.mem.tokenize(u8, slurped, " \n\t");
while (index < N) : (index += 1) {
ret[index] = try std.fmt.parseInt(T, slurped_it.next().?, 10);
}
return ret;
}
pub fn slurpInt(self: *ProcEntry, comptime T: type, basename: []const u8) !T {
// free trimming!
return (try self.slurpIntArray(T, 1, basename))[0];
}
pub fn deinit(self: *ProcEntry) void {
self.dir.close();
}
pub fn readLink(self: *ProcEntry, buf: []u8, basename: []const u8) ![]u8 {
return self.dir.readLink(basename, buf);
}
};
// Read /proc/pressure/memory.
pub const Pressure = struct { avg10: f32, avg60: f32, avg300: f32, total: u64 };
pub const MemoryPressure = struct {
Some: Pressure,
Full: Pressure,
};
// For this to work, reader must be at the beginning of a line.
pub fn readPressure(reader: anytype) !Pressure {
// buffer for chars
var tmp_buf: [32]u8 = undefined;
// floats we'll initialize
var press_floats: [3]f32 = undefined;
var total: usize = 0;
try reader.skipUntilDelimiterOrEof(' ');
for (press_floats) |_, i| {
try reader.skipUntilDelimiterOrEof('=');
var float_str = try reader.readUntilDelimiter(&tmp_buf, ' ');
press_floats[i] = try fmt.parseFloat(f32, float_str);
}
try reader.skipUntilDelimiterOrEof('=');
var int_str = try reader.readUntilDelimiter(&tmp_buf, '\n');
total = try fmt.parseUnsigned(u64, int_str, 10);
return Pressure{ .avg10 = press_floats[0], .avg60 = press_floats[1], .avg300 = press_floats[2], .total = total };
}
pub fn getMemoryPressure() !MemoryPressure {
var press_file = try fs.cwd().openFile("/proc/pressure/memory", .{});
defer press_file.close();
var reader = press_file.reader();
var some = try readPressure(&reader);
var full = try readPressure(&reader);
return MemoryPressure{ .Some = some, .Full = full };
} | src/proc.zig |
const std = @import("std");
const req = @import("request.zig");
const Client = @import("client.zig").Client;
const BasicPerformFunctionPrototype = fn (*std.mem.Allocator, []const u8) anyerror!req.Response;
pub fn get(allocator: std.mem.Allocator, url: []const u8) !req.Response {
var client = try Client.init(allocator, .{});
defer client.deinit();
var request = req.Request{
.method = .GET,
.url = url,
.use_global_connection_pool = true,
};
return try client.perform(request);
}
pub fn post(allocator: std.mem.Allocator, url: []const u8, body: ?req.Body) !req.Response {
var client = try Client.init(allocator, .{});
defer client.deinit();
var request = req.Request{
.method = .POST,
.url = url,
.body = body,
.use_global_connection_pool = true,
};
return try client.perform(request);
}
/// Caller is responsible for freeing the returned type
pub fn postAndParseResponse(
comptime Type: type,
parseOptions: std.json.ParseOptions,
allocator: std.mem.Allocator,
url: []const u8,
body: ?req.Body,
) !Type {
var response = try post(allocator, url, body);
defer response.deinit(); // we can throw the response away because parse will copy into the structure
const responseBytes = response.body orelse return error.MissingResponseBody;
return std.json.parse(Type, &std.json.TokenStream.init(responseBytes), parseOptions);
}
pub fn postJson(allocator: std.mem.Allocator, url: []const u8, jsonValue: anytype, stringifyOptions: std.json.StringifyOptions) !req.Response {
var buffer = std.ArrayList(u8).init(allocator);
defer buffer.deinit();
var writer = buffer.writer();
try std.json.stringify(jsonValue, stringifyOptions, writer);
return post(allocator, url, req.Body{ .kind = .JSON, .bytes = buffer.items });
}
/// Caller is responsible for caling std.json.parseFree (with the same parseOptions) on the returned value
const PostAndParseOptions = struct {
allocator: std.mem.Allocator,
parseOptions: std.json.ParseOptions = .{},
stringifyOptions: std.json.StringifyOptions = .{},
};
fn parseOptionsWithAllocator(allocator: std.mem.Allocator, options: std.json.ParseOptions) std.json.ParseOptions {
var newOpts = options;
newOpts.allocator = allocator;
return newOpts;
}
pub fn postJsonAndParseResponse(comptime OutputType: type, url: []const u8, jsonValue: anytype, options: PostAndParseOptions) !OutputType {
var response = try postJson(options.allocator, url, jsonValue, options.stringifyOptions);
defer response.deinit();
const responseBytes = response.body orelse return error.MissingResponseBody;
return std.json.parse(OutputType, &std.json.TokenStream.init(responseBytes), parseOptionsWithAllocator(options.allocator, options.parseOptions));
}
/// Caller is responsible for freeing the returned type
pub fn getAndParseResponse(
comptime Type: type,
parseOptions: std.json.ParseOptions,
allocator: std.mem.Allocator,
url: []const u8,
) !Type {
var response = try get(allocator, url);
defer response.deinit(); // we can throw the response away because parse will copy into the structure
const responseBody = response.body orelse return error.MissingResponseBody;
return std.json.parse(Type, &std.json.TokenStream.init(responseBody), parseOptions);
} | src/oneshot.zig |
const std = @import("std");
const math = std.math;
const affine = @import("affine.zig");
const V3 = affine.V3;
const v3 = V3.init;
const invPi: f64 = 0.31830988618379067;
const invTau: f64 = 0.15915494309189534;
const Jazbz = @import("jabz.zig").Jazbz(f64);
const gmath = @import("gmath.zig").gmath(f64);
const clamp = gmath.clamp;
const saturate = gmath.saturate;
const sq = gmath.sq;
const gmix = gmath.mix;
/// https://google.github.io/filament/Filament.html#materialsystem/standardmodelsummary
pub const Material = struct {
const Self = @This();
baseColor: Jazbz = Jazbz.grey(0.5),
/// Metallic is almost a binary value. Use values very close to 0 and 1. Intermediate values are for transitions between surface types, e.g., metal to rust.
metallic: f64 = 0,
/// Roughness clamped to 0.045 to avoid division by zero and aliasing.
roughness: f64 = 0.5,
/// Common reflectance: water→0.35, fabric→0.5-0.59, common-liquids→0.35-0.5, common-gemstones→0.56-1, plastics/glass→0.5-0.56, other dielectrics→0.35-0.56, eyes→0.39, skin→0.42, hair→0.54, teeth→0.6, default→0.5
/// Reflectance is ignored for metallic materials.
reflectance: f64 = 0,
/// Strength of the clear coat layer
clearcoat: f64 = 0,
/// Perceived smoothness or roughness of the clear coat layer.
clearcoatRoughness: f64 = 0,
pub fn mix(self: Self, other: Self, alpha: f64) Self {
return .{
.baseColor = gmix(self.baseColor, other.baseColor, alpha),
.metallic = gmix(self.metallic, other.metallic, alpha),
.roughness = gmix(self.roughness, other.roughness, alpha),
.reflectance = gmix(self.reflectance, other.reflectance, alpha),
.clearcoat = gmix(self.clearcoat, other.clearcoat, alpha),
.clearcoatRoughness = gmix(self.clearcoatRoughness, other.clearcoatRoughness, alpha),
};
}
/// https://google.github.io/filament/Filament.html#materialsystem/parameterization/craftingphysicallybasedmaterials
fn baseColorRemapped(self: *const Self) Jazbz {
const j = self.baseColor.j;
const metallicMaterials = gmix(0.67, 1, j);
const nonMetallicMaterials = gmix(0.2, 0.94, j);
return .{
.j = gmix(nonMetallicMaterials, metallicMaterials, self.metallic),
.azbz = self.baseColor.azbz,
};
}
pub fn prepare(material: *const Self) PreparedMaterial {
const dieletricf0 = Jazbz.grey(0.16 * sq(material.reflectance));
const metallicf0 = material.baseColorRemapped();
return PreparedMaterial{
.material = material,
.diffuseColor = material.baseColorRemapped().scaleJ(1 - material.metallic),
.roughness = clamp(0.045, 1, sq(material.roughness)),
.clearcoatRoughness = clamp(0.045, 1, sq(material.clearcoatRoughness)),
.f0 = gmix(dieletricf0, metallicf0, material.metallic),
};
}
};
pub const PreparedMaterial = struct {
const Self = @This();
material: *const Material,
diffuseColor: Jazbz,
roughness: f64,
clearcoatRoughness: f64,
f0: Jazbz,
/// https://google.github.io/filament/Filament.html#materialsystem/standardmodelsummary
pub fn brdf(self: *const Self, surfaceNormal: V3, viewDirection: V3, lightDirection: V3) Jazbz {
const material = self.material;
const n: V3 = surfaceNormal;
const v: V3 = viewDirection;
const l: V3 = lightDirection;
const h: V3 = v.add(l).normalize();
const NoV: f64 = math.fabs(n.dot(v)) + 1e-5;
const NoL = saturate(n.dot(l));
const NoH = saturate(n.dot(h));
const LoH = saturate(l.dot(h));
const metallicf0 = material.baseColorRemapped();
const dieletricf0 = Jazbz.grey(0.16 * sq(material.reflectance));
const f90: f64 = gmix(0.5, 2.5, sq(LoH) * self.roughness); // TODO: took this f90 from Fd_Burley, not sure what should be used
const D: f64 = D_GGX(NoH, self.roughness);
const V: f64 = V_SmithGGXCorrelated(NoV, NoL, self.roughness);
const F: Jazbz = F_Schlick_color(self.f0, f90, LoH);
const Dc: f64 = D_GGX(NoH, self.clearcoatRoughness);
const Vc: f64 = V_SmithGGXCorrelated(NoV, NoL, self.clearcoatRoughness);
//const Vc: f64 = V_Kelemen(LoH) * self.clearcoatRoughness;
const clearcoatStrength: f64 = material.clearcoat * F_Schlick(0.04, 1, LoH);
const clearcoatDamp: f64 = 1 - clearcoatStrength;
var clearcoat = Jazbz.grey(clearcoatStrength * Dc * Vc);
var specular: Jazbz = F.scaleJ(D * V);
var diffuse: Jazbz = self.diffuseColor.scaleJ(Fd_Burley(NoV, NoL, LoH, self.roughness));
//const diffuse = self.diffuseColor.scaleJ(Fd_Lambert());
//var sheen: Jazbz = Jazbz.grey(D_Charlie(NoH, self.roughness) * 0.02);
specular = specular.scaleJ(0.3);
diffuse = diffuse.scaleJ(0.7);
clearcoat = clearcoat.scaleJ(1);
return specular.scaleJ(clearcoatDamp).addLight(diffuse).scaleJ(clearcoatDamp).addLight(clearcoat).toJazbz();
}
};
fn D_GGX(NoH: f64, roughness: f64) f64 {
return sq(roughness / (1 - sq(NoH) + sq(NoH * roughness))) * invPi;
}
fn V_SmithGGXCorrelated(NoV: f64, NoL: f64, roughness: f64) f64 {
const a2 = sq(roughness);
const GGXV = NoL * math.sqrt(sq(NoV) * (1 - a2) + a2);
const GGXL = NoV * math.sqrt(sq(NoL) * (1 - a2) + a2);
return 0.5 / (GGXV + GGXL);
}
fn V_SmithGGXCorrelatedFast(NoV: f64, NoL: f64, roughness: f64) f64 {
const a = roughness;
const GGXV = NoL * (NoV * (1 - a) + a);
const GGXL = NoV * (NoL * (1 - a) + a);
return 0.5 / (GGXV + GGXL);
}
fn F_Schlick(f0: f64, f90: f64, VoH: f64) f64 {
return gmix(f0, f90, gmath.pow5(1 - VoH));
}
fn F_Schlick_color(f0: Jazbz, f90: f64, VoH: f64) Jazbz {
return gmix(f0, Jazbz.grey(f90), gmath.pow5(1 - VoH));
}
fn Fd_Lambert() f64 {
return invPi;
}
fn Fd_Burley(NoV: f64, NoL: f64, LoH: f64, roughness: f64) f64 {
const f90: f64 = gmix(0.5, 2.5, sq(LoH) * roughness);
const lightScatter: f64 = F_Schlick(1, f90, NoL);
const viewScatter: f64 = F_Schlick(1, f90, NoV);
return lightScatter * viewScatter * invPi;
}
fn V_Kelemen(LoH: f64) f64 {
return 0.25 / sq(LoH);
}
fn D_Charlie(NoH: f64, roughness: f64) f64 {
const invAlpha = 1 / roughness;
const sin2h = math.max(1 - sq(NoH), 0.0078125); // 2^(-14/2), so sin2h^2 > 0 in fp16
return gmath.pow(sin2h, invAlpha * 0.5) * (invAlpha * invTau + invPi);
}
fn V_Neubelt(NoV: f64, NoL: f64) f64 {
return saturate(0.25(NoL + NoV - NoL * NoV));
}
fn distributionCloth(Noh: f64, roughness: f64) f64 {
return D_Charlie(NoH, roughness);
}
fn visibilityCloth(NoV: f64, NoL: f64) f64 {
return V_Neubelt(NoV, NoL);
} | lib/brdf.zig |
const std = @import("std");
const log = std.log;
const assert = std.debug.assert;
const cudaz = @import("cudaz");
const cu = cudaz.cu;
const png = @import("png.zig");
const utils = @import("utils.zig");
const hw1_kernel = @import("hw1_pure_kernel.zig");
const resources_dir = "resources/hw1_resources/";
pub fn main() anyerror!void {
log.info("***** HW1 ******", .{});
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = general_purpose_allocator.allocator();
const args = try std.process.argsAlloc(alloc);
defer std.process.argsFree(alloc, args);
var stream = try cudaz.Stream.init(0);
defer stream.deinit();
const img = try png.Image.fromFilePath(alloc, resources_dir ++ "cinque_terre_small.png");
defer img.deinit();
var max_show: usize = 12;
log.info("Loaded img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(img.px.rgb24[200 .. 200 + max_show]) });
const Rgb24 = png.Rgb24;
var d_img = try cudaz.allocAndCopy(Rgb24, img.px.rgb24);
defer cudaz.free(d_img);
const Gray8 = png.Gray8;
var gray = try png.grayscale(alloc, img.width, img.height);
defer gray.deinit();
var d_gray = try cudaz.alloc(Gray8, img.width * img.height);
defer cudaz.free(d_gray);
try cudaz.memset(Gray8, d_gray, 0);
const kernel = try cudaz.FnStruct("rgba_to_greyscale", hw1_kernel.rgba_to_greyscale).init();
var timer = cudaz.GpuTimer.start(&stream);
try kernel.launch(
&stream,
cudaz.Grid.init1D(img.height * img.width, 64),
.{ std.mem.sliceAsBytes(d_img), std.mem.sliceAsBytes(d_gray) },
);
timer.stop();
try cudaz.memcpyDtoH(Gray8, gray.px.gray8, d_gray);
log.info("Got grayscale img {}x{}: ({any}...)", .{ img.width, img.height, std.mem.sliceAsBytes(gray.px.gray8[200 .. 200 + @divExact(max_show, 3)]) });
try gray.writeToFilePath(resources_dir ++ "output.png");
try utils.validate_output(alloc, resources_dir, 1.0);
} | CS344/src/hw1_pure.zig |
const std = @import("std");
const lib = @import("lib.zig");
const fs = std.fs;
const mem = std.mem;
const io = std.io;
const TangleStep = @This();
const Allocator = std.mem.Allocator;
const Builder = std.build.Builder;
const Step = std.build.Step;
const Parser = lib.Parser;
const Interpreter = lib.Interpreter;
const SourceList = std.TailQueue(Source);
const FileSource = std.build.FileSource;
const GeneratedFile = std.build.GeneratedFile;
const BufferedWriter = io.BufferedWriter(4096, fs.File.Writer);
const FileContext = lib.context.StreamContext(BufferedWriter.Writer);
pub const FileList = std.ArrayListUnmanaged([]const u8);
pub const Source = struct {
source: GeneratedFile,
path: []const u8,
};
const log = std.log.scoped(.tangle_step);
vm: Interpreter = .{},
output_dir: ?[]const u8 = null,
builder: *Builder,
files: FileList = .{},
sources: SourceList = .{},
step: Step,
pub fn create(b: *Builder) *TangleStep {
const self = b.allocator.create(TangleStep) catch @panic("Out of memory");
self.* = .{
.builder = b,
.step = Step.init(.custom, "tangle", b.allocator, make),
};
return self;
}
pub fn addFile(self: *TangleStep, path: []const u8) void {
self.files.append(self.builder.allocator, self.builder.dupe(path)) catch @panic(
\\Out of memory
);
}
pub fn getFileSource(self: *TangleStep, path: []const u8) FileSource {
var it = self.sources.first;
while (it) |node| : (it = node.next) {
if (std.mem.eql(u8, node.data.path, path))
return FileSource{ .generated = &node.data.source };
}
const node = self.builder.allocator.create(SourceList.Node) catch @panic(
\\Out of memory
);
node.* = .{
.data = .{
.source = .{ .step = &self.step },
.path = self.builder.dupe(path),
},
};
self.sources.append(node);
return FileSource{ .generated = &node.data.source };
}
fn make(step: *Step) anyerror!void {
const self = @fieldParentPtr(TangleStep, "step", step);
var hash = std.crypto.hash.blake2.Blake2b384.init(.{});
for (self.files.items) |path| {
const text = try fs.cwd().readFileAlloc(self.builder.allocator, path, 0x7fff_ffff);
var p: Parser = .{ .it = .{ .bytes = text } };
while (p.step(self.builder.allocator)) |working| {
if (!working) break;
} else |err| {
const location = p.it.locationFrom(.{});
log.err("line {d} col {d}: {s}", .{
location.line,
location.column,
@errorName(err),
});
@panic("Failed parsing module");
}
hash.update(path);
hash.update(text);
const object = p.object(path);
try self.vm.linker.objects.append(self.builder.allocator, object);
}
try self.vm.linker.link(self.builder.allocator);
var digest: [48]u8 = undefined;
hash.final(&digest);
var basename: [64]u8 = undefined;
_ = std.fs.base64_encoder.encode(&basename, &digest);
if (self.output_dir == null) {
self.output_dir = try fs.path.join(self.builder.allocator, &.{
self.builder.cache_root,
"o",
&basename,
});
}
try fs.cwd().makePath(self.output_dir.?);
var dir = try fs.cwd().openDir(self.output_dir.?, .{});
defer dir.close();
for (self.vm.linker.files.keys()) |path| {
if (path.len > 2 and mem.eql(u8, path[0..2], "~/")) {
return error.@"Absolute paths are not allowed";
} else if (mem.indexOf(u8, path, "../") != null) {
return error.@"paths containing ../ are not allowed";
}
if (fs.path.dirname(path)) |sub| try dir.makePath(sub);
const file = try dir.createFile(path, .{ .truncate = true });
defer file.close();
var buffered: BufferedWriter = .{ .unbuffered_writer = file.writer() };
const writer = buffered.writer();
var context = FileContext.init(writer);
try self.vm.callFile(self.builder.allocator, path, *FileContext, &context);
try context.stream.writeByte('\n');
try buffered.flush();
var it = self.sources.first;
while (it) |node| : (it = node.next) {
if (mem.eql(u8, node.data.path, path)) {
self.sources.remove(node);
node.data.source.path = try fs.path.join(
self.builder.allocator,
&.{ self.output_dir.?, node.data.path },
);
break;
}
}
}
if (self.sources.first) |node| {
log.err("file not found: {s}", .{node.data.path});
var it = node.next;
while (it) |next| {
log.err("file not found: {s}", .{next.data.path});
}
@panic("Files not found");
}
} | lib/TangleStep.zig |
const std = @import("std");
const debug = std.debug;
pub const IRQ_VECTOR_BASE = 0x50;
pub const Cpuid = struct {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
};
pub const CpuInfo = struct {
vendorId: [12]u8,
family: u32,
model: u32,
modelName: [48]u8,
stepping: u32,
// cacheSize: u32
pub fn init() CpuInfo {
// EAX=0: Highest Function Parameter and Manufacturer ID
const vInfo = getCpuid(0);
const vendorId = getVendorId(vInfo);
// EAX=1: EAX=1: Processor Info and Feature Bits
const pInfo = getCpuid(1);
const stepping = getSteppingId(pInfo);
const model = getModel(pInfo);
const family = getFamily(pInfo);
// EAX=80000000H: Returns CPUID's Highest Value for Extended Processor Information
const epInfo = getCpuidCount(0, 0x8b);
// EAX=80000002h,80000003h,80000004h: Processor Brand String
const modelName = getModelName();
return .{
.vendorId = vendorId,
.stepping = stepping,
.model = model,
.family = family,
.modelName = modelName,
};
}
fn getVendorId(manInfo: Cpuid) [12]u8 {
const ebx = manInfo.ebx;
const ecx = manInfo.edx;
const edx = manInfo.ecx;
const data = [3]u32{ ebx, ecx, edx };
return @bitCast([12]u8, data);
}
fn getSteppingId(pInfo: Cpuid) u32 {
return pInfo.eax & 0xF;
}
fn getModel(pInfo: Cpuid) u32 {
const family = (pInfo.eax >> 8) & 0xF;
var model = (pInfo.eax >> 4) & 0xF;
if (family == 6 or family == 15) {
const extendedModel = (pInfo.eax >> 16) & 0xF;
model = (extendedModel << 4) + model;
}
return model;
}
fn getFamily(pInfo: Cpuid) u32 {
var family = (pInfo.eax >> 8) & 0xF;
if (family == 15) {
const extendedFamily = (pInfo.eax >> 20) & 0xFF;
family = family + extendedFamily;
}
return family;
}
fn getModelName() [48]u8 {
const p1 = getCpuid(0x80000002);
const p2 = getCpuid(0x80000003);
const p3 = getCpuid(0x80000004);
const data = [12]u32{ p1.eax, p1.ebx, p1.ecx, p1.edx, p2.eax, p2.ebx, p2.ecx, p2.edx, p3.eax, p3.ebx, p3.ecx, p3.edx };
return @bitCast([48]u8, data);
}
};
fn getCpuidMax(ext: u32) u32 {
const info = cpuid(ext);
return info.eax;
}
pub fn getCpuid(leaf: u32) Cpuid {
const ext = leaf & 0x80000000;
const maxLevel = getCpuidMax(ext);
if (maxLevel == 0 or maxLevel < leaf)
return .{ .eax = 0, .ebx = 0, .ecx = 0, .edx = 0 };
return cpuid(leaf);
}
pub fn getCpuidCount(leaf: u32, count: u32) Cpuid {
const ext = leaf & 0x80000000;
const maxLevel = getCpuidMax(ext);
if (maxLevel == 0 or maxLevel < leaf)
return .{ .eax = 0, .ebx = 0, .ecx = 0, .edx = 0 };
return cpuidCount(leaf, count);
}
/// Using the specified level set the eax, ebx, ecx, and edx pointers to the
/// values returned by the processor.
///
/// See: https://en.wikipedia.org/wiki/CPUID
pub fn cpuid(level: u32) Cpuid {
var a: u32 = undefined;
var b: u32 = undefined;
var c: u32 = undefined;
var d: u32 = undefined;
asm volatile ("cpuid"
: [a] "={eax}" (a),
[b] "={ebx}" (b),
[c] "={ecx}" (c),
[d] "={edx}" (d)
: [level] "{eax}" (level)
);
return .{ .eax = a, .ebx = b, .ecx = c, .edx = d };
}
/// Using the specified level and count set the eax, ebx, ecx, and edx pointers to the
/// values returned by the processor.
///
/// See: https://en.wikipedia.org/wiki/CPUID
pub fn cpuidCount(level: u32, count: u32) Cpuid {
var a: u32 = undefined;
var b: u32 = undefined;
var c: u32 = undefined;
var d: u32 = undefined;
asm volatile ("cpuid"
: [a] "={eax}" (a),
[b] "={ebx}" (b),
[c] "={ecx}" (c),
[d] "={edx}" (d)
: [level] "{eax}" (level),
[count] "{ecx}" (count)
);
return .{ .eax = a, .ebx = b, .ecx = c, .edx = d };
}
pub fn lsb(x: u16) u8 {
return @intCast(u8, x & 0xFF);
}
pub fn lsw(x: u16) u32 {
return @intCast(u32, x) & 0xFFFF;
}
pub fn msb(x: u16) u8 {
return @intCast(u8, (x >> 8) & 0xFF);
}
pub fn msw(x: u16) u32 {
return (@intCast(u32, x) >> 16) & 0xFFFF;
} | src/kernel/arch/x86/boot/cpu.zig |
const Square = @import("../types/enums.zig").Square;
const attacks = @import("attacks.zig");
pub const file_masks = [8]u64{ 0x0101010101010101, 0x0202020202020202, 0x0404040404040404, 0x0808080808080808, 0x1010101010101010, 0x2020202020202020, 0x4040404040404040, 0x8080808080808080 };
pub const rank_masks = [8]u64{ 0xff, 0xff00, 0xff0000, 0xff000000, 0xff00000000, 0xff0000000000, 0xff000000000000, 0xff00000000000000 };
pub const xray_masks: [64][64]u64 = comptime xrayMaskBB();
pub const intervening_masks: [64][64]u64 = comptime interveningMaskBB();
fn xrayMaskBB() [64][64]u64 {
_ = @setEvalBranchQuota(33000);
var masks: [64][64]u64 = undefined;
var from: i32 = 0;
while (from < 64) : (from += 1) {
var to: i32 = 0;
while (to < 64) : (to += 1) {
masks[@intCast(usize, from)][@intCast(usize, to)] = 0;
}
}
from = 0;
while (from < 64) : (from += 1) {
var to: i32 = 0;
while (to < 64) : (to += 1) {
if (from == to) {
continue;
}
var high = to;
var low = from;
if (low > high) {
high = from;
low = to;
}
if ((high & 7) == (low & 7)) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= attacks.rookAttacks(@intToEnum(Square, @intCast(u8, high)), 0) & attacks.rookAttacks(@intToEnum(Square, @intCast(u8, low)), 0);
}
if ((high >> 3) == (low >> 3)) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= attacks.rookAttacks(@intToEnum(Square, @intCast(u8, high)), 0) & attacks.rookAttacks(@intToEnum(Square, @intCast(u8, low)), 0);
}
if ((high >> 3) - (low >> 3) == (high & 7) - (low & 7)) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= attacks.bishopAttacks(@intToEnum(Square, @intCast(u8, high)), 0) & attacks.bishopAttacks(@intToEnum(Square, @intCast(u8, low)), 0);
}
if ((high >> 3) - (low >> 3) == (low & 7) - (high & 7)) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= attacks.bishopAttacks(@intToEnum(Square, @intCast(u8, high)), 0) & attacks.bishopAttacks(@intToEnum(Square, @intCast(u8, low)), 0);
}
}
}
return masks;
}
fn interveningMaskBB() [64][64]u64 {
_ = @setEvalBranchQuota(33000);
var masks: [64][64]u64 = undefined;
var from: i32 = 0;
while (from < 64) : (from += 1) {
var to: i32 = 0;
while (to < 64) : (to += 1) {
masks[@intCast(usize, from)][@intCast(usize, to)] = 0;
}
}
from = 0;
while (from < 64) : (from += 1) {
var to: i32 = 0;
while (to < 64) : (to += 1) {
if (from == to) {
continue;
}
var high = to;
var low = from;
if (low > high) {
high = from;
low = to;
}
if ((high & 7) == (low & 7)) {
high -= 8;
while (high > low) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= @intToEnum(Square, @intCast(u8, high)).toBitboard();
high -= 8;
}
}
if ((high >> 3) == (low >> 3)) {
high -= 1;
while (high > low) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= @intToEnum(Square, @intCast(u8, high)).toBitboard();
high -= 1;
}
}
if ((high >> 3) - (low >> 3) == (high & 7) - (low & 7)) {
high -= 9;
while (high > low) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= @intToEnum(Square, @intCast(u8, high)).toBitboard();
high -= 9;
}
}
if ((high >> 3) - (low >> 3) == (low & 7) - (high & 7)) {
high -= 7;
while (high > low) {
masks[@intCast(usize, from)][@intCast(usize, to)] |= @intToEnum(Square, @intCast(u8, high)).toBitboard();
high -= 7;
}
}
}
}
return masks;
} | src/bitboards/masks.zig |
const std = @import("std");
const input = @import("input.zig");
pub fn run(stdout: anytype) anyerror!void {
{
var input_ = try input.readFile("inputs/day20");
defer input_.deinit();
const result = try part1(&input_);
try stdout.print("20a: {}\n", .{ result });
std.debug.assert(result == 5680);
}
{
var input_ = try input.readFile("inputs/day20");
defer input_.deinit();
const result = try part2(&input_);
try stdout.print("20b: {}\n", .{ result });
std.debug.assert(result == 19766);
}
}
fn part1(input_: anytype) !usize {
return solve(input_, 2);
}
fn part2(input_: anytype) !usize {
return solve(input_, 50);
}
fn solve(input_: anytype, comptime num_steps: usize) !usize {
const num_rows = 100 + num_steps * 2 + 2 * 2;
const num_cols = 100 + num_steps * 2 + 2 * 2;
var algorithm: [512]u1 = undefined;
{
const line = (try input_.next()) orelse return error.InvalidInput;
if (line.len != 512) {
return error.InvalidInput;
}
for (line) |c, i| {
algorithm[i] = switch (c) {
'#' => 1,
'.' => 0,
else => return error.InvalidInput,
};
}
}
var image: [num_rows][num_cols]u1 = [_][num_cols]u1 { [_]u1 { 0 } ** num_cols } ** num_rows;
_ = try input_.next();
{
var row_i: usize = num_steps + 2;
while (try input_.next()) |line| {
for (line) |c, col_i_| {
const col_i = num_steps + col_i_ + 2;
image[row_i][col_i] = switch (c) {
'#' => 1,
'.' => 0,
else => return error.InvalidInput,
};
}
row_i += 1;
}
}
{
var new_image = image;
var step_i: usize = 1;
while (step_i <= num_steps) : (step_i += 1) {
for (new_image) |*row, row_i| {
for (row) |*new_b, col_i| {
const up = std.math.sub(usize, row_i, 1) catch row_i;
const down = if (std.math.add(usize, row_i, 1) catch null) |down_| if (down_ < num_rows) down_ else row_i else row_i;
const left = std.math.sub(usize, col_i, 1) catch col_i;
const right = if (std.math.add(usize, col_i, 1) catch null) |right_| if (right_ < num_cols) right_ else col_i else col_i;
var index: u9 = 0;
for ([_]usize { up, row_i, down }) |row_j| {
for ([_]usize { left, col_i, right }) |col_j| {
index = (index << 1) | image[row_j][col_j];
}
}
new_b.* = algorithm[index];
}
}
image = new_image;
}
}
var result: usize = 0;
for (image) |row| {
for (row) |b| {
result += b;
}
}
return result;
}
test "day 20 example 1" {
const input_ =
\\..#.#..#####.#.#.#.###.##.....###.##.#..###.####..#####..#....#..#..##..###..######.###...####..#..#####..##..#.#####...##.#.#..#.##..#.#......#.###.######.###.####...#.##.##..#..#..#####.....#.#....###..#.##......#.....#..#..#..##..#...##.######.####.####.#.#...#.......#..#.#.#...####.##.#......#..#...##.#.##..#...##.#.##..###.#......#.#.......#.#.#.####.###.##...#.....####.#..#..#.##.#....##..#.####....##...##..#...#......#.#.......#.......##..####..#...#.#.#...##..#.#..###..#####........#..####......#..#
\\
\\#..#.
\\#....
\\##..#
\\..#..
\\..###
;
try std.testing.expectEqual(@as(usize, 35), try part1(&input.readString(input_)));
try std.testing.expectEqual(@as(usize, 3351), try part2(&input.readString(input_)));
} | src/day20.zig |
const print = @import("std").debug.print; // Oops!
const Narcissus = struct {
me: *Narcissus = undefined,
myself: *Narcissus = undefined,
echo: void = undefined,
fn fetchTheMostBeautifulType() type {
return @This();
}
};
pub fn main() void {
var narcissus: Narcissus = Narcissus{};
// Oops! We cannot leave the 'me' and 'myself' fields
// undefined. Please set them here:
narcissus.me = &narcissus;
narcissus.myself = &narcissus;
// This determines a "peer type" from three separate
// references (they just happen to all be the same object).
const T1 = @TypeOf(narcissus, narcissus.me.*, narcissus.myself.*);
// Oh dear, we seem to have done something wrong when calling
// this function. It is namespaced to the struct, but doesn't
// use the method syntax (there's no self parameter). Please
// fix this call:
const T2 = Narcissus.fetchTheMostBeautifulType();
print("A {} loves all {}es. ", .{ T1, T2 });
// His final words as he was looking in
// those waters he habitually watched
// were these:
// "Alas, my beloved boy, in vain!"
// The place gave every word back in reply.
// He cried:
// "Farewell."
// And Echo called:
// "Farewell!"
//
// --Ovid, The Metamorphoses
// translated by <NAME>
print("He has room in his heart for:", .{});
// A StructFields array
const fields = @typeInfo(Narcissus).Struct.fields;
// 'fields' is a slice of StructFields. Here's the declaration:
//
// pub const StructField = struct {
// name: []const u8,
// field_type: type,
// default_value: anytype,
// is_comptime: bool,
// alignment: comptime_int,
// };
//
// Please complete these 'if' statements so that the field
// name will not be printed if the field is of type 'void'
// (which is a zero-bit type that takes up no space at all!):
comptime var i = 0;
inline while (i < fields.len) : (i += 1)
if (fields[i].field_type != void)
print(" {s}", .{fields[i].name});
// Yuck, look at all that repeated code above! I don't know
// about you, but it makes me itchy.
//
// Alas, we can't use a regular 'for' loop here because
// 'fields' can only be evaluated at compile time. It seems
// like we're overdue to learn about this "comptime" stuff,
// isn't it? :-)
print(".\n", .{});
} | exercises/065_builtins2.zig |
const std = @import("std");
const testing = std.testing;
const StringTable = @import("./strtab.zig").StringTable;
const allocator = std.heap.page_allocator;
pub const Food = struct {
const Mask = struct {
bits: [256]u1,
pub fn init() Mask {
var self = Mask{
.bits = [_]u1{0} ** 256,
};
return self;
}
pub fn show(self: Mask) void {
var print = false;
for (self.bits) |_, j| {
const p = 256 - j - 1;
const b = self.bits[p];
print = print or b == 1;
if (!print) continue;
std.debug.warn("{}", .{b});
}
}
pub fn check(self: Mask, bit: usize) bool {
return self.bits[bit] == 1;
}
pub fn set(self: *Mask, bit: usize) void {
self.bits[bit] = 1;
}
pub fn clr(self: *Mask, bit: usize) void {
self.bits[bit] = 0;
}
pub fn and_with(self: *Mask, other: Mask) void {
for (other.bits) |b, p| {
if (self.bits[p] == 0 or b == 0) {
self.bits[p] = 0;
}
}
}
};
const Allergen = struct {
code: usize,
mask: Mask,
pub fn init(code: usize, mask: Mask) Allergen {
var self = Allergen{
.code = code,
.mask = mask,
};
return self;
}
};
allergens: std.AutoHashMap(usize, Allergen),
lines: std.ArrayList(Mask),
foods_st: StringTable,
allergens_st: StringTable,
pub fn init() Food {
var self = Food{
.allergens = std.AutoHashMap(usize, Allergen).init(allocator),
.lines = std.ArrayList(Mask).init(allocator),
.foods_st = StringTable.init(allocator),
.allergens_st = StringTable.init(allocator),
};
return self;
}
pub fn deinit(self: *Food) void {
self.allergens_st.deinit();
self.foods_st.deinit();
self.lines.deinit();
self.allergens.deinit();
}
pub fn add_line(self: *Food, line: []const u8) void {
var zone: usize = 0;
var mask = Mask.init();
var it = std.mem.tokenize(u8, line, " ,()");
while (it.next()) |str| {
if (std.mem.eql(u8, str, "contains")) {
self.lines.append(mask) catch unreachable;
zone += 1;
continue;
}
if (zone == 0) {
const code = self.foods_st.add(str);
// std.debug.warn("FOOD {} {}\n", .{ code, str });
mask.set(code);
continue;
}
if (zone == 1) {
const code = self.allergens_st.add(str);
var allergen: *Allergen = undefined;
if (!self.allergens.contains(code)) {
// std.debug.warn("ALLERGEN NEW {} {}:", .{ code, str });
var value = Allergen.init(code, mask);
_ = self.allergens.put(code, value) catch unreachable;
allergen = &value;
} else {
// std.debug.warn("ALLERGEN OLD {} {}:", .{ code, str });
var entry = self.allergens.getEntry(code).?;
allergen = &entry.value_ptr.*;
allergen.*.mask.and_with(mask);
}
// allergen.*.mask.show();
// std.debug.warn("\n", .{});
continue;
}
@panic("ZONE");
}
}
pub fn count_without_allergens(self: Food) usize {
var foods = [_]u8{1} ** 256;
var it1 = self.allergens.iterator();
while (it1.next()) |kv| {
const allergen = kv.value_ptr.*;
// const allergen_name = self.allergens_st.get_str(allergen.code);
// std.debug.print("ALLERGEN {} {} removes", .{ allergen.code, allergen_name });
for (allergen.mask.bits) |b, p| {
if (b == 0) continue;
foods[p] = 0;
// const food_name = self.foods_st.get_str(p);
// std.debug.print(" {}", .{food_name});
}
// std.debug.print("\n", .{});
}
var total: usize = 0;
for (foods) |b, p| {
if (p >= self.foods_st.size()) continue;
// const food_name = self.foods_st.get_str(p);
if (b == 0) {
// std.debug.print("FOOD {} {} is inert\n", .{ p, food_name });
continue;
}
var count: usize = 0;
var pl: usize = 0;
while (pl < self.lines.items.len) : (pl += 1) {
const orig = self.lines.items[pl];
if (!orig.check(p)) continue;
count += 1;
}
// std.debug.print("FOOD {} {} appears in {} lines\n", .{ p, food_name, count });
total += count;
}
return total;
}
const Data = struct {
food_code: usize,
allergen_code: usize,
};
pub fn map_foods_to_allergens(self: *Food, buf: *[1024]u8) []const u8 {
var data: [256]Data = undefined;
var mapped_count: usize = 0;
var mapped = [_]bool{false} ** 256;
while (true) {
var changes: usize = 0;
var it = self.allergens.iterator();
while (it.next()) |kv| {
const allergen = kv.value_ptr.*;
if (mapped[allergen.code]) continue;
var count_food: usize = 0;
var food_code: usize = 0;
for (allergen.mask.bits) |b, p| {
if (b == 0) continue;
count_food += 1;
food_code = p;
}
if (count_food != 1) continue;
// const allergen_name = self.allergens_st.get_str(allergen.code);
// const food_name = self.foods_st.get_str(food_code);
// std.debug.warn("ALLERGEN {} MAPS TO FOOD {}\n", .{ allergen_name, food_name });
mapped[allergen.code] = true;
data[mapped_count].food_code = food_code;
data[mapped_count].allergen_code = allergen.code;
mapped_count += 1;
changes += 1;
var it2 = self.allergens.iterator();
while (it2.next()) |kv2| {
if (kv2.key_ptr.* == allergen.code) continue;
kv2.value_ptr.*.mask.clr(food_code);
}
}
if (changes == 0) break;
}
// std.debug.warn("FOUND {} MAPPINGS\n", .{mapped_count});
std.sort.sort(Data, data[0..mapped_count], self, cmp);
var p: usize = 0;
var bp: usize = 0;
while (p < mapped_count) : (p += 1) {
const food_name = self.foods_st.get_str(data[p].food_code).?;
// std.debug.warn("MAPPING {} => [{}]\n", .{ p, food_name });
if (p > 0) {
std.mem.copy(u8, buf[bp..], ",");
bp += 1;
}
std.mem.copy(u8, buf[bp..], food_name);
bp += food_name.len;
}
return buf[0..bp];
}
fn cmp(self: *Food, l: Data, r: Data) bool {
const lan = self.allergens_st.get_str(l.allergen_code).?;
const ran = self.allergens_st.get_str(r.allergen_code).?;
return std.mem.lessThan(u8, lan, ran);
}
};
test "sample part a" {
const data: []const u8 =
\\mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
\\trh fvjkl sbzzf mxmxvkd (contains dairy)
\\sqjhc fvjkl (contains soy)
\\sqjhc mxmxvkd sbzzf (contains fish)
;
var food = Food.init();
defer food.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
food.add_line(line);
}
const count = food.count_without_allergens();
try testing.expect(count == 5);
}
test "sample with gonzo names" {
const data: []const u8 =
\\A B C D (contains d, f)
\\E F G A (contains d)
\\C F (contains s)
\\C A G (contains f)
;
var food = Food.init();
defer food.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
food.add_line(line);
}
const count = food.count_without_allergens();
try testing.expect(count == 5);
}
test "sample part b" {
const data: []const u8 =
\\mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
\\trh fvjkl sbzzf mxmxvkd (contains dairy)
\\sqjhc fvjkl (contains soy)
\\sqjhc mxmxvkd sbzzf (contains fish)
;
var food = Food.init();
defer food.deinit();
var it = std.mem.split(u8, data, "\n");
while (it.next()) |line| {
food.add_line(line);
}
var buf: [1024]u8 = undefined;
var list = food.map_foods_to_allergens(&buf);
try testing.expect(std.mem.eql(u8, list, "mxmxvkd,sqjhc,fvjkl"));
} | 2020/p21/food.zig |
const std = @import("std");
const tools = @import("tools");
const with_trace = true;
const assert = std.debug.assert;
fn trace(comptime fmt: []const u8, args: anytype) void {
if (with_trace) std.debug.print(fmt, args);
}
pub fn main() anyerror!void {
const stdout = std.io.getStdOut().writer();
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = arena.allocator();
const limit = 1 * 1024 * 1024 * 1024;
const text = try std.fs.cwd().readFileAlloc(allocator, "day21.txt", limit);
defer allocator.free(text);
var string: [8]u8 = undefined;
var orig: [8]u8 = undefined;
const permuts = 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1;
var p: u32 = 0;
while (p < permuts) : (p += 1) {
{
std.mem.copy(u8, &string, "abcdefgh");
var mod: u32 = 8;
var k = p;
for (string) |*c, i| {
const t = c.*;
c.* = string[i + k % mod];
string[i + k % mod] = t;
k /= mod;
mod -= 1;
}
}
std.mem.copy(u8, &orig, &string);
var it = std.mem.tokenize(u8, text, "\n");
while (it.next()) |line| {
if (tools.match_pattern("swap position {} with position {}", line)) |vals| {
//trace("swap @{}/@{}\n", .{ vals[0].imm, vals[1].imm });
const min = @intCast(usize, vals[0].imm);
const max = @intCast(usize, vals[1].imm);
const t = string[min];
string[min] = string[max];
string[max] = t;
} else if (tools.match_pattern("rotate left {} steps", line)) |vals| {
const n = @intCast(usize, vals[0].imm);
std.mem.rotate(u8, &string, (n % string.len));
} else if (tools.match_pattern("rotate left {} step", line)) |vals| {
const n = @intCast(usize, vals[0].imm);
assert(n == 1);
std.mem.rotate(u8, &string, (n % string.len));
} else if (tools.match_pattern("rotate right {} steps", line)) |vals| {
const n = @intCast(usize, vals[0].imm);
std.mem.rotate(u8, &string, string.len - (n % string.len));
} else if (tools.match_pattern("rotate right {} step", line)) |vals| {
const n = @intCast(usize, vals[0].imm);
assert(n == 1);
std.mem.rotate(u8, &string, string.len - (n % string.len));
} else if (tools.match_pattern("reverse positions {} through {}", line)) |vals| {
const min = @intCast(usize, vals[0].imm);
const max = @intCast(usize, vals[1].imm);
std.mem.reverse(u8, string[min .. max + 1]);
} else if (tools.match_pattern("move position {} to position {}", line)) |vals| {
const from = @intCast(usize, vals[0].imm);
const to = @intCast(usize, vals[1].imm);
const t = string[from];
if (from < to) {
std.mem.copy(u8, string[from..to], string[from + 1 .. to + 1]);
} else {
std.mem.copyBackwards(u8, string[to + 1 .. from + 1], string[to..from]);
}
string[to] = t;
} else if (tools.match_pattern("swap letter {} with letter {}", line)) |vals| {
const a = vals[0].name[0];
const b = vals[1].name[0];
for (string) |*c| {
if (c.* == a) {
c.* = b;
} else if (c.* == b) {
c.* = a;
}
}
} else if (tools.match_pattern("rotate based on position of letter {}", line)) |vals| {
const a = vals[0].name[0];
const idx = blk: {
for (string) |c, i| {
if (c == a) break :blk i;
}
unreachable;
};
const n = idx + 1 + if (idx >= 4) @as(usize, 1) else @as(usize, 0);
std.mem.rotate(u8, &string, string.len - (n % string.len));
} else {
trace("ignoring '{}'\n", .{line});
assert(tools.match_pattern("rotate left {} step", line) == null);
}
}
trace("{} -> {}'\n", .{ orig[0..], string[0..] });
if (std.mem.eql(u8, string[0..], "fbgdceah"))
break;
}
try stdout.print("====================================\n", .{});
} | 2016/day21.zig |
// Copyright (c) 2018 <NAME>
// 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.
//
// From https://github.com/TM35-Metronome/metronome
//
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const log = @import("../md/log.zig");
test "Utf8View Index" {
const s = try Utf8View.init("noël n");
var it = s.iterator();
testing.expect(std.mem.eql(u8, "n", it.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "o", it.peek(1)));
testing.expect(std.mem.eql(u8, "oë", it.peek(2)));
testing.expect(std.mem.eql(u8, "oël", it.peek(3)));
testing.expect(std.mem.eql(u8, "oël ", it.peek(4)));
testing.expect(std.mem.eql(u8, "oël n", it.peek(10)));
testing.expect(std.mem.eql(u8, "o", it.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "ë", it.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "l", it.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, " ", it.nextCodepointSlice().?));
testing.expect(std.mem.eql(u8, "n", it.nextCodepointSlice().?));
testing.expect(it.nextCodepointSlice() == null);
testing.expect(std.mem.eql(u8, "n", s.index(0).?));
testing.expect(std.mem.eql(u8, "ë", s.index(2).?));
testing.expect(std.mem.eql(u8, "o", s.index(1).?));
testing.expect(std.mem.eql(u8, "l", s.index(3).?));
testing.expect(std.mem.eql(u8, &[_]u8{}, it.peek(1)));
}
/// Improved Utf8View which also keeps track of the length in codepoints
pub const Utf8View = struct {
bytes: []const u8,
len: usize,
pub fn init(str: []const u8) !Utf8View {
return Utf8View{
.bytes = str,
.len = try utf8Len(str),
};
}
/// Returns the codepoint at i. Returns null if i is greater than the length of the view.
pub fn index(view: Utf8View, i: usize) ?[]const u8 {
if (i >= view.len) {
return null;
}
var y: usize = 0;
var it = view.iterator();
var rune: ?[]const u8 = null;
while (y < i + 1) : (y += 1) if (it.nextCodepointSlice()) |r| {
rune = r;
};
if (rune) |nrune|
_ = std.unicode.utf8Decode(nrune) catch unreachable;
return rune;
}
pub fn slice(view: Utf8View, start: usize, end: usize) Utf8View {
var len: usize = 0;
var i: usize = 0;
var it = view.iterator();
while (i < start) : (i += 1)
len += @boolToInt(it.nextCodepointSlice() != null);
const start_i = it.i;
while (i < end) : (i += 1)
len += @boolToInt(it.nextCodepointSlice() != null);
return .{
.bytes = view.bytes[start_i..it.i],
.len = len,
};
}
pub fn iterator(view: Utf8View) std.unicode.Utf8Iterator {
return std.unicode.Utf8View.initUnchecked(view.bytes).iterator();
}
};
/// Given a string of words, this function will split the string into lines where
/// a maximum of `max_line_len` characters can occure on each line.
pub fn splitIntoLines(allocator: *mem.Allocator, max_line_len: usize, string: Utf8View) !Utf8View {
var res = std.ArrayList(u8).init(allocator);
errdefer res.deinit();
// A decent estimate that will most likely ensure that we only do one allocation.
try res.ensureCapacity(string.len + (string.len / max_line_len) + 1);
var curr_line_len: usize = 0;
var it = mem.tokenize(string.bytes, " \n");
while (it.next()) |word_bytes| {
const word = Utf8View.init(word_bytes) catch unreachable;
const next_line_len = word.len + curr_line_len + (1 * @boolToInt(curr_line_len != 0));
if (next_line_len > max_line_len) {
try res.appendSlice("\n");
try res.appendSlice(word_bytes);
curr_line_len = word.len;
} else {
if (curr_line_len != 0)
try res.appendSlice(" ");
try res.appendSlice(word_bytes);
curr_line_len = next_line_len;
}
}
return Utf8View.init(res.toOwnedSlice()) catch unreachable;
}
fn utf8Len(s: []const u8) !usize {
var res: usize = 0;
var i: usize = 0;
while (i < s.len) : (res += 1) {
if (std.unicode.utf8ByteSequenceLength(s[i])) |cp_len| {
if (i + cp_len > s.len) {
return error.InvalidUtf8;
}
if (std.unicode.utf8Decode(s[i .. i + cp_len])) |_| {} else |_| {
return error.InvalidUtf8;
}
i += cp_len;
} else |err| {
return error.InvalidUtf8;
}
}
return res;
} | src/unicode/unicode.zig |
const std = @import("std");
usingnamespace @import("common.zig");
usingnamespace @import("location.zig");
usingnamespace @import("lexer.zig");
usingnamespace @import("ast.zig");
usingnamespace @import("types.zig");
usingnamespace @import("error_handler.zig");
pub const Parser = struct {
allocator: *std.mem.Allocator,
lexer: Lexer,
errorReporter: *ErrorReporter,
errorMsgBuffer: std.ArrayList(u8),
nextId: usize = 0,
const Self = @This();
const Context = struct {
allowLambda: bool = true,
allowTuple: bool = true,
pub fn with(self: Context, comptime field: []const u8, value: anytype) Context {
var result = self;
@field(result, field) = value;
return result;
}
};
pub fn init(lexer: Lexer, allocator: *std.mem.Allocator, errorReporter: *ErrorReporter) Self {
return Self{
.allocator = allocator,
.lexer = lexer,
.errorReporter = errorReporter,
.errorMsgBuffer = std.ArrayList(u8).init(allocator),
};
}
pub fn deinit(self: *Self) void {
self.errorMsgBuffer.deinit();
}
fn reportError(self: *Self, location: *const Location, comptime format: []const u8, args: anytype) void {
self.errorMsgBuffer.resize(0) catch unreachable;
std.fmt.format(self.errorMsgBuffer.writer(), format, args) catch {};
self.errorReporter.report(self.errorMsgBuffer.items, location);
}
fn allocateAst(self: *Self, location: Location, spec: AstSpec) !*Ast {
var ast = try self.allocator.create(Ast);
ast.* = Ast{
.id = self.nextId,
.location = location,
.typ = UnknownType,
.spec = spec,
};
self.nextId += 1;
return ast;
}
fn skipToken(self: *Self) void {
_ = self.lexer.read();
}
fn check(self: *Self, kind: TokenKind) ?Token {
if (self.lexer.peek()) |token| {
if (token.kind == kind) {
return token;
} else {
return null;
}
}
return null;
}
fn checkExpression(self: *Self, ctx: Context) bool {
if (self.lexer.peek()) |token| {
switch (token.kind) {
.Identifier,
.String,
.Int,
.Float,
.ParenLeft,
.BraceLeft,
.BracketLeft,
.Ampersand,
.Plus,
.Minus,
=> return true,
.Bar => return ctx.allowLambda,
else => return false,
}
}
return false;
}
fn checkDelimiter(self: *Self, ctx: Context) bool {
if (self.lexer.peek()) |token| {
switch (token.kind) {
.Comma,
.ParenRight,
.BraceRight,
.BracketRight,
=> return true,
else => return false,
}
}
return false;
}
fn consume(self: *Self, kind: TokenKind, report: bool) ?Token {
if (self.lexer.peek()) |token| {
if (token.kind == kind) {
_ = self.lexer.read();
return token;
} else {
if (report) {
self.reportError(&token.location, "Expected {any}, found {any}", .{ kind, token.kind });
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
} else {
@panic("consume");
}
}
return null;
}
}
return null;
}
fn skipNewline(self: *Self) bool {
if (self.lexer.peek()) |token| {
if (token.kind == .Newline) {
_ = self.lexer.read();
return true;
} else {
return false;
}
}
return false;
}
pub fn parseTopLevelExpression(self: *Self) anyerror!?*Ast {
_ = self.skipNewline();
if (try self.parseExpression(.{})) |expr| {
_ = self.consume(.Newline, true);
return expr;
}
return null;
}
fn parseExpression(self: *Self, ctx: Context) anyerror!?*Ast {
while (self.lexer.peek()) |token| {
switch (token.kind) {
else => |kind| {
var expr = (try self.parseAssignmentOrDeclOrLess(ctx)) orelse {
_ = self.lexer.read();
continue;
};
if (self.lexer.peek()) |next| {
switch (next.kind) {
else => return expr,
}
}
return expr;
},
}
}
return null;
}
fn parseAssignmentOrDeclOrLess(self: *Self, ctx: Context) anyerror!?*Ast {
var subCtx = ctx.with("allowTuple", ctx.allowTuple);
var expr = (try self.parseCommaOrLess(subCtx)) orelse return null;
if (self.lexer.peek()) |next| {
switch (next.kind) {
// _ =
.Equal => {
self.skipToken();
_ = self.skipNewline();
var value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .Assignment = .{
.pattern = expr,
.value = value,
} });
},
// _ :
.Colon => {
self.skipToken();
_ = self.skipNewline();
if (self.lexer.peek()) |next2| {
switch (next2.kind) {
// _ ::
.Colon => {
self.skipToken();
const value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .ConstDecl = .{
.pattern = expr,
.typ = null,
.value = value,
} });
},
// _ :=
.Equal => {
self.skipToken();
const value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .VarDecl = .{
.pattern = expr,
.typ = null,
.value = value,
} });
},
// _ : _
else => {
const typ = (try self.parseCommaOrLess(subCtx)) orelse return null;
if (self.lexer.peek()) |next3| {
switch (next3.kind) {
// _ : _ :
.Colon => {
self.skipToken();
_ = self.skipNewline();
const value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .ConstDecl = .{
.pattern = expr,
.typ = typ,
.value = value,
} });
},
// _ : _ =
.Equal => {
self.skipToken();
_ = self.skipNewline();
const value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .VarDecl = .{
.pattern = expr,
.typ = typ,
.value = value,
} });
},
// _ : _
.Newline => {
return try self.allocateAst(expr.location, AstSpec{ .VarDecl = .{
.pattern = expr,
.typ = typ,
.value = null,
} });
},
else => {
if (!self.checkDelimiter(ctx)) {
self.reportError(&next3.location, "Expected '=' or ':', found {}", .{next3.kind});
return null;
}
},
}
}
// _ : _
return try self.allocateAst(expr.location, AstSpec{ .VarDecl = .{
.pattern = expr,
.typ = typ,
.value = null,
} });
},
}
}
var value = (try self.parseCommaOrLess(subCtx)) orelse return null;
return try self.allocateAst(expr.location, AstSpec{ .Assignment = .{
.pattern = expr,
.value = value,
} });
},
else => return expr,
}
}
return expr;
}
fn parseCommaOrLess(self: *Self, ctx: Context) anyerror!?*Ast {
var expr = (try self.parsePipeOrLess(ctx)) orelse return null;
if (ctx.allowTuple and self.check(.Comma) != null) {
var args = std.ArrayList(*Ast).init(self.allocator);
try args.append(expr);
while (self.lexer.peek()) |next| {
switch (next.kind) {
.Comma => {
self.skipToken();
_ = self.skipNewline();
if (self.checkExpression(ctx)) {
if (try self.parsePipeOrLess(ctx)) |e| {
try args.append(e);
}
} else {
break;
}
},
else => break,
}
}
return try self.allocateAst(expr.location, AstSpec{ .Tuple = .{
.values = args,
} });
}
return expr;
}
fn parsePipeOrLess(self: *Self, ctx: Context) anyerror!?*Ast {
var expr = (try self.parseCallOrLess(ctx)) orelse return null;
while (self.lexer.peek()) |next| {
switch (next.kind) {
.Arrow => {
self.skipToken();
_ = self.skipNewline();
var right = (try self.parseCallOrLess(ctx)) orelse return null;
var pipe = try self.allocateAst(expr.location, AstSpec{ .Pipe = .{
.left = expr,
.right = right,
} });
expr = pipe;
},
else => return expr,
}
}
return expr;
}
pub fn parseCallOrLess(self: *Self, ctx: Context) anyerror!?*Ast {
var expr = (try self.parseAtomic(ctx)) orelse return null;
while (self.lexer.peek()) |next| {
switch (next.kind) {
.ParenLeft => {
expr = (try self.parseCall(expr, ctx)) orelse return expr;
},
.Period => {
self.skipToken();
const right = (try self.parseAtomic(ctx)) orelse return expr;
expr = try self.allocateAst(expr.location, AstSpec{ .Access = .{
.left = expr,
.right = right,
} });
},
else => return expr,
}
}
return expr;
}
pub fn parseBlock(self: *Self, ctx: Context) anyerror!?*Ast {
const braceLeft = self.consume(.BraceLeft, true) orelse return null;
var body = std.ArrayList(*Ast).init(self.allocator);
errdefer body.deinit();
_ = self.skipNewline();
while (self.lexer.peek()) |token| {
if (token.kind == .BraceRight) {
break;
}
if (try self.parseExpression(ctx)) |expr| {
try body.append(expr);
if (self.check(.BraceRight) == null) {
_ = self.consume(.Newline, true);
}
} else {
self.reportError(&braceLeft.location, "Expected expression.", .{});
self.skipToken();
_ = self.skipNewline();
}
}
const braceRight = self.consume(.BraceRight, true) orelse return null;
var ast = try self.allocateAst(braceLeft.location, AstSpec{ .Block = .{
.body = body,
} });
return ast;
}
pub fn parseCall(self: *Self, func: *Ast, ctx: Context) anyerror!?*Ast {
const parenLeft = self.consume(.ParenLeft, true) orelse return null;
var args = std.ArrayList(*Ast).init(self.allocator);
errdefer args.deinit();
var state: enum { AfterOpen, AfterExpr, AfterComma } = .AfterOpen;
const argCtx = ctx.with("allowTuple", false);
while (self.lexer.peek()) |token| {
if (token.kind == .ParenRight) {
break;
}
switch (state) {
.AfterOpen => {
_ = self.skipNewline();
if (try self.parseExpression(argCtx)) |expr| {
try args.append(expr);
} else {
self.reportError(&parenLeft.location, "Expected argument.", .{});
self.skipToken();
}
state = .AfterExpr;
},
.AfterExpr => {
if (!self.skipNewline()) {
_ = self.consume(.Comma, true);
} else if (self.check(.ParenRight) == null) {
_ = self.consume(.Comma, false);
}
state = .AfterComma;
},
.AfterComma => {
_ = self.skipNewline();
if (try self.parseExpression(argCtx)) |expr| {
try args.append(expr);
} else {
self.reportError(&parenLeft.location, "Expected argument.", .{});
self.skipToken();
}
state = .AfterExpr;
},
}
}
const parenRight = self.consume(.ParenRight, true) orelse return null;
// If the call if followed by a specific kind of token parse the post call expression
if (self.lexer.peek()) |token| {
switch (token.kind) {
.Identifier,
.String,
.Int,
.Float,
.BraceLeft,
.Bar,
=> {
if (token.kind != .Bar or ctx.allowLambda) {
//var block = (try self.parsePipeOrLess(ctx)) orelse return null;
var block = (try self.parseCallOrLess(ctx)) orelse return null;
try args.append(block);
}
},
else => {},
}
}
var ast = try self.allocateAst(func.location, AstSpec{ .Call = .{
.func = func,
.args = args,
} });
return ast;
}
pub fn parseLambda(self: *Self, ctx: Context) anyerror!?*Ast {
const parenLeft = self.consume(.Bar, true) orelse return null;
var args = std.ArrayList(*Ast).init(self.allocator);
errdefer args.deinit();
var state: enum { AfterOpen, AfterExpr, AfterComma } = .AfterOpen;
const argCtx = ctx.with("allowLambda", false).with("allowTuple", false);
_ = self.skipNewline();
while (self.lexer.peek()) |token| {
if (token.kind == .Bar) {
break;
}
switch (state) {
.AfterOpen => {
_ = self.skipNewline();
if (try self.parseExpression(argCtx)) |expr| {
try args.append(expr);
} else {
self.reportError(&parenLeft.location, "Expected argument.", .{});
self.skipToken();
}
state = .AfterExpr;
},
.AfterExpr => {
if (!self.skipNewline()) {
_ = self.consume(.Comma, true);
} else if (self.check(.Bar) == null) {
_ = self.consume(.Comma, false);
}
state = .AfterComma;
},
.AfterComma => {
_ = self.skipNewline();
if (try self.parseExpression(argCtx)) |expr| {
try args.append(expr);
} else {
self.reportError(&parenLeft.location, "Expected argument.", .{});
self.skipToken();
}
state = .AfterExpr;
},
}
}
const parenRight = self.consume(.Bar, true) orelse return null;
_ = self.skipNewline();
var body = (try self.parseCallOrLess(ctx)) orelse return null;
var ast = try self.allocateAst(parenLeft.location, AstSpec{ .Lambda = .{
.body = body,
.args = args,
} });
return ast;
}
pub fn parseAtomic(self: *Self, ctx: Context) anyerror!?*Ast {
if (self.lexer.peek()) |token| {
switch (token.kind) {
.Identifier => {
self.skipToken();
var ast = try self.allocateAst(token.location, AstSpec{ .Identifier = .{ .name = token.data.text } });
return ast;
},
.String => {
self.skipToken();
var ast = try self.allocateAst(token.location, AstSpec{ .String = .{ .value = token.data.text } });
return ast;
},
.Int => {
self.skipToken();
var ast = try self.allocateAst(token.location, AstSpec{ .Int = .{ .value = token.data.int } });
return ast;
},
.Float => {
self.skipToken();
var ast = try self.allocateAst(token.location, AstSpec{ .Float = .{ .value = token.data.float } });
return ast;
},
.ParenLeft => {
self.skipToken();
_ = self.skipNewline();
var endsInComma = false;
var values = try self.parseValues(ctx, &endsInComma);
_ = self.consume(.ParenRight, true);
if (endsInComma or values.items.len != 1) {
return try self.allocateAst(token.location, AstSpec{ .Tuple = .{
.values = values,
} });
}
const result = values.items[0];
values.deinit();
return result;
},
.BraceLeft => return self.parseBlock(ctx),
.Bar => {
if (ctx.allowLambda) {
return self.parseLambda(ctx);
} else {
return null;
}
},
else => |kind| {
self.reportError(&token.location, "Unexpected token: {any}", .{kind});
if (@errorReturnTrace()) |trace| {
std.debug.dumpStackTrace(trace.*);
} else {
@panic("parseAtomic");
}
return null;
},
}
}
return null;
}
pub fn parseValues(self: *Self, ctx: Context, endsInComma: *bool) anyerror!List(*Ast) {
var values = List(*Ast).init(self.allocator);
errdefer values.deinit();
while (self.lexer.peek()) |_| {
if (self.check(.ParenRight)) |_| {
break;
}
if (try self.parseExpression(Context{ .allowTuple = false, .allowLambda = false })) |ast| {
try values.append(ast);
}
endsInComma.* = false;
if (self.lexer.peek() == null or self.check(.ParenRight) != null) {
break;
}
_ = self.consume(.Comma, true);
_ = self.skipNewline();
endsInComma.* = true;
}
return values;
}
};
fn parseOne(allocator: *std.mem.Allocator, input: []const u8) !?*Ast {
var errorReporter = NullErrorReporter{};
var parser = Parser.init(try Lexer.init(input), allocator, &errorReporter.reporter);
errdefer parser.deinit();
if (try parser.parseTopLevelExpression()) |expr| {
std.testing.expect(parser.lexer.peek() == null);
return expr;
}
return null;
}
////////////////////////////////////////////
// Tests //
////////////////////////////////////////////
test "identifier" {
var allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator.deinit();
if (try parseOne(&allocator.allocator, "id")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Identifier);
std.testing.expectEqualStrings("id", ast.spec.Identifier.name);
} else {
std.testing.expect(false);
}
}
test "string" {
var allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator.deinit();
if (try parseOne(&allocator.allocator, "\"hello world,\nwassup?\"")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .String);
std.testing.expectEqualStrings("hello world,\nwassup?", ast.spec.String.value);
} else {
std.testing.expect(false);
}
}
test "number" {
var allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator.deinit();
// decimal
if (try parseOne(&allocator.allocator, "123")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Int);
std.testing.expectEqual(@as(u128, 123), ast.spec.Int.value);
} else {
std.testing.expect(false);
}
// hex
if (try parseOne(&allocator.allocator, "0x123")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Int);
std.testing.expectEqual(@as(u128, 291), ast.spec.Int.value);
} else {
std.testing.expect(false);
}
// binary
if (try parseOne(&allocator.allocator, "0b10110")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Int);
std.testing.expectEqual(@as(u128, 22), ast.spec.Int.value);
} else {
std.testing.expect(false);
}
}
test "block" {
var allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer allocator.deinit();
// empty
if (try parseOne(&allocator.allocator, "{}")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Block);
var block = &ast.spec.Block;
std.testing.expectEqual(@as(u128, 0), block.body.items.len);
} else {
std.testing.expect(false);
}
// empty
if (try parseOne(&allocator.allocator, "{\n}")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Block);
var block = &ast.spec.Block;
std.testing.expectEqual(@as(u128, 0), block.body.items.len);
} else {
std.testing.expect(false);
}
// non empty
if (try parseOne(&allocator.allocator, "{\n5\nalol\n}")) |ast| {
std.testing.expect(@as(std.meta.Tag(AstSpec), ast.spec) == .Block);
var block = &ast.spec.Block;
std.testing.expectEqual(@as(u128, 2), block.body.items.len);
std.testing.expect(@as(std.meta.Tag(AstSpec), block.body.items[0].spec) == .Int);
std.testing.expectEqual(@as(u128, 5), block.body.items[0].spec.Int.value);
std.testing.expect(@as(std.meta.Tag(AstSpec), block.body.items[1].spec) == .Identifier);
std.testing.expectEqualStrings("lol", block.body.items[1].spec.Identifier.name);
} else {
std.testing.expect(false);
}
} | src/parser.zig |
const std = @import("../std.zig");
const builtin = @import("builtin");
const assert = std.debug.assert;
const macho = std.macho;
const native_arch = builtin.target.cpu.arch;
const maxInt = std.math.maxInt;
const iovec_const = std.os.iovec_const;
extern "c" fn __error() *c_int;
pub extern "c" fn NSVersionOfRunTimeLibrary(library_name: [*:0]const u8) u32;
pub extern "c" fn _NSGetExecutablePath(buf: [*:0]u8, bufsize: *u32) c_int;
pub extern "c" fn _dyld_image_count() u32;
pub extern "c" fn _dyld_get_image_header(image_index: u32) ?*mach_header;
pub extern "c" fn _dyld_get_image_vmaddr_slide(image_index: u32) usize;
pub extern "c" fn _dyld_get_image_name(image_index: u32) [*:0]const u8;
pub const COPYFILE_ACL = 1 << 0;
pub const COPYFILE_STAT = 1 << 1;
pub const COPYFILE_XATTR = 1 << 2;
pub const COPYFILE_DATA = 1 << 3;
pub const copyfile_state_t = *opaque {};
pub extern "c" fn fcopyfile(from: fd_t, to: fd_t, state: ?copyfile_state_t, flags: u32) c_int;
pub extern "c" fn @"realpath$DARWIN_EXTSN"(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8;
pub const realpath = @"realpath$DARWIN_EXTSN";
pub extern "c" fn __getdirentries64(fd: c_int, buf_ptr: [*]u8, buf_len: usize, basep: *i64) isize;
const private = struct {
extern "c" fn fstat(fd: fd_t, buf: *Stat) c_int;
/// On x86_64 Darwin, fstat has to be manully linked with $INODE64 suffix to
/// force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstat$INODE64"(fd: fd_t, buf: *Stat) c_int;
extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *Stat, flags: u32) c_int;
/// On x86_64 Darwin, fstatat has to be manully linked with $INODE64 suffix to
/// force 64bit version.
/// Note that this is fixed on aarch64 and no longer necessary.
extern "c" fn @"fstatat$INODE64"(dirfd: fd_t, path_name: [*:0]const u8, buf: *Stat, flags: u32) c_int;
};
pub const fstat = if (native_arch == .aarch64) private.fstat else private.@"fstat$INODE64";
pub const fstatat = if (native_arch == .aarch64) private.fstatat else private.@"fstatat$INODE64";
pub extern "c" fn mach_absolute_time() u64;
pub extern "c" fn mach_timebase_info(tinfo: ?*mach_timebase_info_data) void;
pub extern "c" fn malloc_size(?*const c_void) usize;
pub extern "c" fn posix_memalign(memptr: *?*c_void, alignment: usize, size: usize) c_int;
pub extern "c" fn kevent64(
kq: c_int,
changelist: [*]const kevent64_s,
nchanges: c_int,
eventlist: [*]kevent64_s,
nevents: c_int,
flags: c_uint,
timeout: ?*const timespec,
) c_int;
const mach_hdr = if (@sizeOf(usize) == 8) mach_header_64 else mach_header;
/// The value of the link editor defined symbol _MH_EXECUTE_SYM is the address
/// of the mach header in a Mach-O executable file type. It does not appear in
/// any file type other than a MH_EXECUTE file type. The type of the symbol is
/// absolute as the header is not part of any section.
/// This symbol is populated when linking the system's libc, which is guaranteed
/// on this operating system. However when building object files or libraries,
/// the system libc won't be linked until the final executable. So we
/// export a weak symbol here, to be overridden by the real one.
var dummy_execute_header: mach_hdr = undefined;
pub extern var _mh_execute_header: mach_hdr;
comptime {
if (builtin.target.isDarwin()) {
@export(dummy_execute_header, .{ .name = "_mh_execute_header", .linkage = .Weak });
}
}
pub const mach_header_64 = macho.mach_header_64;
pub const mach_header = macho.mach_header;
pub const _errno = __error;
pub extern "c" fn @"close$NOCANCEL"(fd: fd_t) c_int;
pub extern "c" fn mach_host_self() mach_port_t;
pub extern "c" fn clock_get_time(clock_serv: clock_serv_t, cur_time: *mach_timespec_t) kern_return_t;
pub const sf_hdtr = extern struct {
headers: [*]const iovec_const,
hdr_cnt: c_int,
trailers: [*]const iovec_const,
trl_cnt: c_int,
};
pub extern "c" fn sendfile(
in_fd: fd_t,
out_fd: fd_t,
offset: off_t,
len: *off_t,
sf_hdtr: ?*sf_hdtr,
flags: u32,
) c_int;
pub fn sigaddset(set: *sigset_t, signo: u5) void {
set.* |= @as(u32, 1) << (signo - 1);
}
pub extern "c" fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) c_int;
pub const AI = struct {
/// get address to use bind()
pub const PASSIVE = 0x00000001;
/// fill ai_canonname
pub const CANONNAME = 0x00000002;
/// prevent host name resolution
pub const NUMERICHOST = 0x00000004;
/// prevent service name resolution
pub const NUMERICSERV = 0x00001000;
};
pub const EAI = enum(c_int) {
/// address family for hostname not supported
ADDRFAMILY = 1,
/// temporary failure in name resolution
AGAIN = 2,
/// invalid value for ai_flags
BADFLAGS = 3,
/// non-recoverable failure in name resolution
FAIL = 4,
/// ai_family not supported
FAMILY = 5,
/// memory allocation failure
MEMORY = 6,
/// no address associated with hostname
NODATA = 7,
/// hostname nor servname provided, or not known
NONAME = 8,
/// servname not supported for ai_socktype
SERVICE = 9,
/// ai_socktype not supported
SOCKTYPE = 10,
/// system error returned in errno
SYSTEM = 11,
/// invalid value for hints
BADHINTS = 12,
/// resolved protocol is unknown
PROTOCOL = 13,
/// argument buffer overflow
OVERFLOW = 14,
_,
};
pub const EAI_MAX = 15;
pub const pthread_mutex_t = extern struct {
__sig: c_long = 0x32AAABA7,
__opaque: [__PTHREAD_MUTEX_SIZE__]u8 = [_]u8{0} ** __PTHREAD_MUTEX_SIZE__,
};
pub const pthread_cond_t = extern struct {
__sig: c_long = 0x3CB0B1BB,
__opaque: [__PTHREAD_COND_SIZE__]u8 = [_]u8{0} ** __PTHREAD_COND_SIZE__,
};
pub const pthread_rwlock_t = extern struct {
__sig: c_long = 0x2DA8B3B4,
__opaque: [192]u8 = [_]u8{0} ** 192,
};
pub const sem_t = c_int;
const __PTHREAD_MUTEX_SIZE__ = if (@sizeOf(usize) == 8) 56 else 40;
const __PTHREAD_COND_SIZE__ = if (@sizeOf(usize) == 8) 40 else 24;
pub const pthread_attr_t = extern struct {
__sig: c_long,
__opaque: [56]u8,
};
const pthread_t = std.c.pthread_t;
pub extern "c" fn pthread_threadid_np(thread: ?pthread_t, thread_id: *u64) c_int;
pub extern "c" fn pthread_setname_np(name: [*:0]const u8) E;
pub extern "c" fn pthread_getname_np(thread: std.c.pthread_t, name: [*:0]u8, len: usize) E;
pub extern "c" fn arc4random_buf(buf: [*]u8, len: usize) void;
// Grand Central Dispatch is exposed by libSystem.
pub extern "c" fn dispatch_release(object: *c_void) void;
pub const dispatch_semaphore_t = *opaque {};
pub extern "c" fn dispatch_semaphore_create(value: isize) ?dispatch_semaphore_t;
pub extern "c" fn dispatch_semaphore_wait(dsema: dispatch_semaphore_t, timeout: dispatch_time_t) isize;
pub extern "c" fn dispatch_semaphore_signal(dsema: dispatch_semaphore_t) isize;
pub const dispatch_time_t = u64;
pub const DISPATCH_TIME_NOW = @as(dispatch_time_t, 0);
pub const DISPATCH_TIME_FOREVER = ~@as(dispatch_time_t, 0);
pub extern "c" fn dispatch_time(when: dispatch_time_t, delta: i64) dispatch_time_t;
const dispatch_once_t = usize;
const dispatch_function_t = fn (?*c_void) callconv(.C) void;
pub extern fn dispatch_once_f(
predicate: *dispatch_once_t,
context: ?*c_void,
function: dispatch_function_t,
) void;
// Undocumented futex-like API available on darwin 16+
// (macOS 10.12+, iOS 10.0+, tvOS 10.0+, watchOS 3.0+, catalyst 13.0+).
//
// [ulock.h]: https://github.com/apple/darwin-xnu/blob/master/bsd/sys/ulock.h
// [sys_ulock.c]: https://github.com/apple/darwin-xnu/blob/master/bsd/kern/sys_ulock.c
pub const UL_COMPARE_AND_WAIT = 1;
pub const UL_UNFAIR_LOCK = 2;
// Obsolete/deprecated
pub const UL_OSSPINLOCK = UL_COMPARE_AND_WAIT;
pub const UL_HANDOFFLOCK = UL_UNFAIR_LOCK;
pub const ULF_WAKE_ALL = 0x100;
pub const ULF_WAKE_THREAD = 0x200;
pub const ULF_WAIT_WORKQ_DATA_CONTENTION = 0x10000;
pub const ULF_WAIT_CANCEL_POINT = 0x20000;
pub const ULF_NO_ERRNO = 0x1000000;
// The following are only supported on darwin 19+
// (macOS 10.15+, iOS 13.0+)
pub const UL_COMPARE_AND_WAIT_SHARED = 3;
pub const UL_UNFAIR_LOCK64_SHARED = 4;
pub const UL_COMPARE_AND_WAIT64 = 5;
pub const UL_COMPARE_AND_WAIT64_SHARED = 6;
pub const ULF_WAIT_ADAPTIVE_SPIN = 0x40000;
pub extern "c" fn __ulock_wait2(op: u32, addr: ?*const c_void, val: u64, timeout_ns: u64, val2: u64) c_int;
pub extern "c" fn __ulock_wait(op: u32, addr: ?*const c_void, val: u64, timeout_us: u32) c_int;
pub extern "c" fn __ulock_wake(op: u32, addr: ?*const c_void, val: u64) c_int;
pub const OS_UNFAIR_LOCK_INIT = os_unfair_lock{};
pub const os_unfair_lock_t = *os_unfair_lock;
pub const os_unfair_lock = extern struct {
_os_unfair_lock_opaque: u32 = 0,
};
pub extern "c" fn os_unfair_lock_lock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_unlock(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_trylock(o: os_unfair_lock_t) bool;
pub extern "c" fn os_unfair_lock_assert_owner(o: os_unfair_lock_t) void;
pub extern "c" fn os_unfair_lock_assert_not_owner(o: os_unfair_lock_t) void;
// XXX: close -> close$NOCANCEL
// XXX: getdirentries -> _getdirentries64
pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int;
pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int;
pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int;
pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int;
pub extern "c" fn sched_yield() c_int;
pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int;
pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int;
pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int;
pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *Stat) c_int;
pub extern "c" fn sigfillset(set: ?*sigset_t) void;
pub extern "c" fn alarm(seconds: c_uint) c_uint;
pub extern "c" fn sigwait(set: ?*sigset_t, sig: ?*c_int) c_int;
// See: https://opensource.apple.com/source/xnu/xnu-6153.141.1/bsd/sys/_types.h.auto.html
// TODO: audit mode_t/pid_t, should likely be u16/i32
pub const fd_t = c_int;
pub const pid_t = c_int;
pub const mode_t = c_uint;
pub const uid_t = u32;
pub const gid_t = u32;
pub const in_port_t = u16;
pub const sa_family_t = u8;
pub const socklen_t = u32;
pub const sockaddr = extern struct {
len: u8,
family: sa_family_t,
data: [14]u8,
pub const SS_MAXSIZE = 128;
pub const storage = std.x.os.Socket.Address.Native.Storage;
pub const in = extern struct {
len: u8 = @sizeOf(in),
family: sa_family_t = AF.INET,
port: in_port_t,
addr: u32,
zero: [8]u8 = [8]u8{ 0, 0, 0, 0, 0, 0, 0, 0 },
};
pub const in6 = extern struct {
len: u8 = @sizeOf(in6),
family: sa_family_t = AF.INET6,
port: in_port_t,
flowinfo: u32,
addr: [16]u8,
scope_id: u32,
};
/// UNIX domain socket
pub const un = extern struct {
len: u8 = @sizeOf(un),
family: sa_family_t = AF.UNIX,
path: [104]u8,
};
};
pub const timeval = extern struct {
tv_sec: c_long,
tv_usec: i32,
};
pub const timezone = extern struct {
tz_minuteswest: i32,
tz_dsttime: i32,
};
pub const mach_timebase_info_data = extern struct {
numer: u32,
denom: u32,
};
pub const off_t = i64;
pub const ino_t = u64;
pub const Flock = extern struct {
l_start: off_t,
l_len: off_t,
l_pid: pid_t,
l_type: i16,
l_whence: i16,
};
pub const Stat = extern struct {
dev: i32,
mode: u16,
nlink: u16,
ino: ino_t,
uid: uid_t,
gid: gid_t,
rdev: i32,
atimesec: isize,
atimensec: isize,
mtimesec: isize,
mtimensec: isize,
ctimesec: isize,
ctimensec: isize,
birthtimesec: isize,
birthtimensec: isize,
size: off_t,
blocks: i64,
blksize: i32,
flags: u32,
gen: u32,
lspare: i32,
qspare: [2]i64,
pub fn atime(self: @This()) timespec {
return timespec{
.tv_sec = self.atimesec,
.tv_nsec = self.atimensec,
};
}
pub fn mtime(self: @This()) timespec {
return timespec{
.tv_sec = self.mtimesec,
.tv_nsec = self.mtimensec,
};
}
pub fn ctime(self: @This()) timespec {
return timespec{
.tv_sec = self.ctimesec,
.tv_nsec = self.ctimensec,
};
}
};
pub const timespec = extern struct {
tv_sec: isize,
tv_nsec: isize,
};
pub const sigset_t = u32;
pub const empty_sigset: sigset_t = 0;
pub const SIG = struct {
pub const ERR = @intToPtr(?Sigaction.sigaction_fn, maxInt(usize));
pub const DFL = @intToPtr(?Sigaction.sigaction_fn, 0);
pub const IGN = @intToPtr(?Sigaction.sigaction_fn, 1);
pub const HOLD = @intToPtr(?Sigaction.sigaction_fn, 5);
/// block specified signal set
pub const _BLOCK = 1;
/// unblock specified signal set
pub const _UNBLOCK = 2;
/// set specified signal set
pub const _SETMASK = 3;
/// hangup
pub const HUP = 1;
/// interrupt
pub const INT = 2;
/// quit
pub const QUIT = 3;
/// illegal instruction (not reset when caught)
pub const ILL = 4;
/// trace trap (not reset when caught)
pub const TRAP = 5;
/// abort()
pub const ABRT = 6;
/// pollable event ([XSR] generated, not supported)
pub const POLL = 7;
/// compatibility
pub const IOT = ABRT;
/// EMT instruction
pub const EMT = 7;
/// floating point exception
pub const FPE = 8;
/// kill (cannot be caught or ignored)
pub const KILL = 9;
/// bus error
pub const BUS = 10;
/// segmentation violation
pub const SEGV = 11;
/// bad argument to system call
pub const SYS = 12;
/// write on a pipe with no one to read it
pub const PIPE = 13;
/// alarm clock
pub const ALRM = 14;
/// software termination signal from kill
pub const TERM = 15;
/// urgent condition on IO channel
pub const URG = 16;
/// sendable stop signal not from tty
pub const STOP = 17;
/// stop signal from tty
pub const TSTP = 18;
/// continue a stopped process
pub const CONT = 19;
/// to parent on child stop or exit
pub const CHLD = 20;
/// to readers pgrp upon background tty read
pub const TTIN = 21;
/// like TTIN for output if (tp->t_local<OSTOP)
pub const TTOU = 22;
/// input/output possible signal
pub const IO = 23;
/// exceeded CPU time limit
pub const XCPU = 24;
/// exceeded file size limit
pub const XFSZ = 25;
/// virtual time alarm
pub const VTALRM = 26;
/// profiling time alarm
pub const PROF = 27;
/// window size changes
pub const WINCH = 28;
/// information request
pub const INFO = 29;
/// user defined signal 1
pub const USR1 = 30;
/// user defined signal 2
pub const USR2 = 31;
};
pub const siginfo_t = extern struct {
signo: c_int,
errno: c_int,
code: c_int,
pid: pid_t,
uid: uid_t,
status: c_int,
addr: *c_void,
value: extern union {
int: c_int,
ptr: *c_void,
},
si_band: c_long,
_pad: [7]c_ulong,
};
/// Renamed from `sigaction` to `Sigaction` to avoid conflict with function name.
pub const Sigaction = extern struct {
pub const handler_fn = fn (c_int) callconv(.C) void;
pub const sigaction_fn = fn (c_int, *const siginfo_t, ?*const c_void) callconv(.C) void;
handler: extern union {
handler: ?handler_fn,
sigaction: ?sigaction_fn,
},
mask: sigset_t,
flags: c_uint,
};
pub const dirent = extern struct {
d_ino: usize,
d_seekoff: usize,
d_reclen: u16,
d_namlen: u16,
d_type: u8,
d_name: u8, // field address is address of first byte of name
pub fn reclen(self: dirent) u16 {
return self.d_reclen;
}
};
/// Renamed from `kevent` to `Kevent` to avoid conflict with function name.
pub const Kevent = extern struct {
ident: usize,
filter: i16,
flags: u16,
fflags: u32,
data: isize,
udata: usize,
};
// sys/types.h on macos uses #pragma pack(4) so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@offsetOf(Kevent, "ident") == 0);
assert(@offsetOf(Kevent, "filter") == 8);
assert(@offsetOf(Kevent, "flags") == 10);
assert(@offsetOf(Kevent, "fflags") == 12);
assert(@offsetOf(Kevent, "data") == 16);
assert(@offsetOf(Kevent, "udata") == 24);
}
pub const kevent64_s = extern struct {
ident: u64,
filter: i16,
flags: u16,
fflags: u32,
data: i64,
udata: u64,
ext: [2]u64,
};
// sys/types.h on macos uses #pragma pack() so these checks are
// to make sure the struct is laid out the same. These values were
// produced from C code using the offsetof macro.
comptime {
assert(@offsetOf(kevent64_s, "ident") == 0);
assert(@offsetOf(kevent64_s, "filter") == 8);
assert(@offsetOf(kevent64_s, "flags") == 10);
assert(@offsetOf(kevent64_s, "fflags") == 12);
assert(@offsetOf(kevent64_s, "data") == 16);
assert(@offsetOf(kevent64_s, "udata") == 24);
assert(@offsetOf(kevent64_s, "ext") == 32);
}
pub const mach_port_t = c_uint;
pub const clock_serv_t = mach_port_t;
pub const clock_res_t = c_int;
pub const mach_port_name_t = natural_t;
pub const natural_t = c_uint;
pub const mach_timespec_t = extern struct {
tv_sec: c_uint,
tv_nsec: clock_res_t,
};
pub const kern_return_t = c_int;
pub const host_t = mach_port_t;
pub const CALENDAR_CLOCK = 1;
pub const PATH_MAX = 1024;
pub const IOV_MAX = 16;
pub const STDIN_FILENO = 0;
pub const STDOUT_FILENO = 1;
pub const STDERR_FILENO = 2;
pub const PROT = struct {
/// [MC2] no permissions
pub const NONE = 0x00;
/// [MC2] pages can be read
pub const READ = 0x01;
/// [MC2] pages can be written
pub const WRITE = 0x02;
/// [MC2] pages can be executed
pub const EXEC = 0x04;
};
pub const MAP = struct {
/// allocated from memory, swap space
pub const ANONYMOUS = 0x1000;
/// map from file (default)
pub const FILE = 0x0000;
/// interpret addr exactly
pub const FIXED = 0x0010;
/// region may contain semaphores
pub const HASSEMAPHORE = 0x0200;
/// changes are private
pub const PRIVATE = 0x0002;
/// share changes
pub const SHARED = 0x0001;
/// don't cache pages for this mapping
pub const NOCACHE = 0x0400;
/// don't reserve needed swap area
pub const NORESERVE = 0x0040;
pub const FAILED = @intToPtr(*c_void, maxInt(usize));
};
pub const SA = struct {
/// take signal on signal stack
pub const ONSTACK = 0x0001;
/// restart system on signal return
pub const RESTART = 0x0002;
/// reset to SIG.DFL when taking signal
pub const RESETHAND = 0x0004;
/// do not generate SIG.CHLD on child stop
pub const NOCLDSTOP = 0x0008;
/// don't mask the signal we're delivering
pub const NODEFER = 0x0010;
/// don't keep zombies around
pub const NOCLDWAIT = 0x0020;
/// signal handler with SIGINFO args
pub const SIGINFO = 0x0040;
/// do not bounce off kernel's sigtramp
pub const USERTRAMP = 0x0100;
/// signal handler with SIGINFO args with 64bit regs information
pub const @"64REGSET" = 0x0200;
};
pub const F_OK = 0;
pub const X_OK = 1;
pub const W_OK = 2;
pub const R_OK = 4;
pub const O = struct {
pub const PATH = 0x0000;
/// open for reading only
pub const RDONLY = 0x0000;
/// open for writing only
pub const WRONLY = 0x0001;
/// open for reading and writing
pub const RDWR = 0x0002;
/// do not block on open or for data to become available
pub const NONBLOCK = 0x0004;
/// append on each write
pub const APPEND = 0x0008;
/// create file if it does not exist
pub const CREAT = 0x0200;
/// truncate size to 0
pub const TRUNC = 0x0400;
/// error if CREAT and the file exists
pub const EXCL = 0x0800;
/// atomically obtain a shared lock
pub const SHLOCK = 0x0010;
/// atomically obtain an exclusive lock
pub const EXLOCK = 0x0020;
/// do not follow symlinks
pub const NOFOLLOW = 0x0100;
/// allow open of symlinks
pub const SYMLINK = 0x200000;
/// descriptor requested for event notifications only
pub const EVTONLY = 0x8000;
/// mark as close-on-exec
pub const CLOEXEC = 0x1000000;
pub const ACCMODE = 3;
pub const ALERT = 536870912;
pub const ASYNC = 64;
pub const DIRECTORY = 1048576;
pub const DP_GETRAWENCRYPTED = 1;
pub const DP_GETRAWUNENCRYPTED = 2;
pub const DSYNC = 4194304;
pub const FSYNC = SYNC;
pub const NOCTTY = 131072;
pub const POPUP = 2147483648;
pub const SYNC = 128;
};
pub const SEEK = struct {
pub const SET = 0x0;
pub const CUR = 0x1;
pub const END = 0x2;
};
pub const DT = struct {
pub const UNKNOWN = 0;
pub const FIFO = 1;
pub const CHR = 2;
pub const DIR = 4;
pub const BLK = 6;
pub const REG = 8;
pub const LNK = 10;
pub const SOCK = 12;
pub const WHT = 14;
};
/// no flag value
pub const KEVENT_FLAG_NONE = 0x000;
/// immediate timeout
pub const KEVENT_FLAG_IMMEDIATE = 0x001;
/// output events only include change
pub const KEVENT_FLAG_ERROR_EVENTS = 0x002;
/// add event to kq (implies enable)
pub const EV_ADD = 0x0001;
/// delete event from kq
pub const EV_DELETE = 0x0002;
/// enable event
pub const EV_ENABLE = 0x0004;
/// disable event (not reported)
pub const EV_DISABLE = 0x0008;
/// only report one occurrence
pub const EV_ONESHOT = 0x0010;
/// clear event state after reporting
pub const EV_CLEAR = 0x0020;
/// force immediate event output
/// ... with or without EV_ERROR
/// ... use KEVENT_FLAG_ERROR_EVENTS
/// on syscalls supporting flags
pub const EV_RECEIPT = 0x0040;
/// disable event after reporting
pub const EV_DISPATCH = 0x0080;
/// unique kevent per udata value
pub const EV_UDATA_SPECIFIC = 0x0100;
/// ... in combination with EV_DELETE
/// will defer delete until udata-specific
/// event enabled. EINPROGRESS will be
/// returned to indicate the deferral
pub const EV_DISPATCH2 = EV_DISPATCH | EV_UDATA_SPECIFIC;
/// report that source has vanished
/// ... only valid with EV_DISPATCH2
pub const EV_VANISHED = 0x0200;
/// reserved by system
pub const EV_SYSFLAGS = 0xF000;
/// filter-specific flag
pub const EV_FLAG0 = 0x1000;
/// filter-specific flag
pub const EV_FLAG1 = 0x2000;
/// EOF detected
pub const EV_EOF = 0x8000;
/// error, data contains errno
pub const EV_ERROR = 0x4000;
pub const EV_POLL = EV_FLAG0;
pub const EV_OOBAND = EV_FLAG1;
pub const EVFILT_READ = -1;
pub const EVFILT_WRITE = -2;
/// attached to aio requests
pub const EVFILT_AIO = -3;
/// attached to vnodes
pub const EVFILT_VNODE = -4;
/// attached to struct proc
pub const EVFILT_PROC = -5;
/// attached to struct proc
pub const EVFILT_SIGNAL = -6;
/// timers
pub const EVFILT_TIMER = -7;
/// Mach portsets
pub const EVFILT_MACHPORT = -8;
/// Filesystem events
pub const EVFILT_FS = -9;
/// User events
pub const EVFILT_USER = -10;
/// Virtual memory events
pub const EVFILT_VM = -12;
/// Exception events
pub const EVFILT_EXCEPT = -15;
pub const EVFILT_SYSCOUNT = 17;
/// On input, NOTE_TRIGGER causes the event to be triggered for output.
pub const NOTE_TRIGGER = 0x01000000;
/// ignore input fflags
pub const NOTE_FFNOP = 0x00000000;
/// and fflags
pub const NOTE_FFAND = 0x40000000;
/// or fflags
pub const NOTE_FFOR = 0x80000000;
/// copy fflags
pub const NOTE_FFCOPY = 0xc0000000;
/// mask for operations
pub const NOTE_FFCTRLMASK = 0xc0000000;
pub const NOTE_FFLAGSMASK = 0x00ffffff;
/// low water mark
pub const NOTE_LOWAT = 0x00000001;
/// OOB data
pub const NOTE_OOB = 0x00000002;
/// vnode was removed
pub const NOTE_DELETE = 0x00000001;
/// data contents changed
pub const NOTE_WRITE = 0x00000002;
/// size increased
pub const NOTE_EXTEND = 0x00000004;
/// attributes changed
pub const NOTE_ATTRIB = 0x00000008;
/// link count changed
pub const NOTE_LINK = 0x00000010;
/// vnode was renamed
pub const NOTE_RENAME = 0x00000020;
/// vnode access was revoked
pub const NOTE_REVOKE = 0x00000040;
/// No specific vnode event: to test for EVFILT_READ activation
pub const NOTE_NONE = 0x00000080;
/// vnode was unlocked by flock(2)
pub const NOTE_FUNLOCK = 0x00000100;
/// process exited
pub const NOTE_EXIT = 0x80000000;
/// process forked
pub const NOTE_FORK = 0x40000000;
/// process exec'd
pub const NOTE_EXEC = 0x20000000;
/// shared with EVFILT_SIGNAL
pub const NOTE_SIGNAL = 0x08000000;
/// exit status to be returned, valid for child process only
pub const NOTE_EXITSTATUS = 0x04000000;
/// provide details on reasons for exit
pub const NOTE_EXIT_DETAIL = 0x02000000;
/// mask for signal & exit status
pub const NOTE_PDATAMASK = 0x000fffff;
pub const NOTE_PCTRLMASK = (~NOTE_PDATAMASK);
pub const NOTE_EXIT_DETAIL_MASK = 0x00070000;
pub const NOTE_EXIT_DECRYPTFAIL = 0x00010000;
pub const NOTE_EXIT_MEMORY = 0x00020000;
pub const NOTE_EXIT_CSERROR = 0x00040000;
/// will react on memory pressure
pub const NOTE_VM_PRESSURE = 0x80000000;
/// will quit on memory pressure, possibly after cleaning up dirty state
pub const NOTE_VM_PRESSURE_TERMINATE = 0x40000000;
/// will quit immediately on memory pressure
pub const NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000;
/// there was an error
pub const NOTE_VM_ERROR = 0x10000000;
/// data is seconds
pub const NOTE_SECONDS = 0x00000001;
/// data is microseconds
pub const NOTE_USECONDS = 0x00000002;
/// data is nanoseconds
pub const NOTE_NSECONDS = 0x00000004;
/// absolute timeout
pub const NOTE_ABSOLUTE = 0x00000008;
/// ext[1] holds leeway for power aware timers
pub const NOTE_LEEWAY = 0x00000010;
/// system does minimal timer coalescing
pub const NOTE_CRITICAL = 0x00000020;
/// system does maximum timer coalescing
pub const NOTE_BACKGROUND = 0x00000040;
pub const NOTE_MACH_CONTINUOUS_TIME = 0x00000080;
/// data is mach absolute time units
pub const NOTE_MACHTIME = 0x00000100;
pub const AF = struct {
pub const UNSPEC = 0;
pub const LOCAL = 1;
pub const UNIX = LOCAL;
pub const INET = 2;
pub const SYS_CONTROL = 2;
pub const IMPLINK = 3;
pub const PUP = 4;
pub const CHAOS = 5;
pub const NS = 6;
pub const ISO = 7;
pub const OSI = ISO;
pub const ECMA = 8;
pub const DATAKIT = 9;
pub const CCITT = 10;
pub const SNA = 11;
pub const DECnet = 12;
pub const DLI = 13;
pub const LAT = 14;
pub const HYLINK = 15;
pub const APPLETALK = 16;
pub const ROUTE = 17;
pub const LINK = 18;
pub const XTP = 19;
pub const COIP = 20;
pub const CNT = 21;
pub const RTIP = 22;
pub const IPX = 23;
pub const SIP = 24;
pub const PIP = 25;
pub const ISDN = 28;
pub const E164 = ISDN;
pub const KEY = 29;
pub const INET6 = 30;
pub const NATM = 31;
pub const SYSTEM = 32;
pub const NETBIOS = 33;
pub const PPP = 34;
pub const MAX = 40;
};
pub const PF = struct {
pub const UNSPEC = AF.UNSPEC;
pub const LOCAL = AF.LOCAL;
pub const UNIX = PF.LOCAL;
pub const INET = AF.INET;
pub const IMPLINK = AF.IMPLINK;
pub const PUP = AF.PUP;
pub const CHAOS = AF.CHAOS;
pub const NS = AF.NS;
pub const ISO = AF.ISO;
pub const OSI = AF.ISO;
pub const ECMA = AF.ECMA;
pub const DATAKIT = AF.DATAKIT;
pub const CCITT = AF.CCITT;
pub const SNA = AF.SNA;
pub const DECnet = AF.DECnet;
pub const DLI = AF.DLI;
pub const LAT = AF.LAT;
pub const HYLINK = AF.HYLINK;
pub const APPLETALK = AF.APPLETALK;
pub const ROUTE = AF.ROUTE;
pub const LINK = AF.LINK;
pub const XTP = AF.XTP;
pub const COIP = AF.COIP;
pub const CNT = AF.CNT;
pub const SIP = AF.SIP;
pub const IPX = AF.IPX;
pub const RTIP = AF.RTIP;
pub const PIP = AF.PIP;
pub const ISDN = AF.ISDN;
pub const KEY = AF.KEY;
pub const INET6 = AF.INET6;
pub const NATM = AF.NATM;
pub const SYSTEM = AF.SYSTEM;
pub const NETBIOS = AF.NETBIOS;
pub const PPP = AF.PPP;
pub const MAX = AF.MAX;
};
pub const SYSPROTO_EVENT = 1;
pub const SYSPROTO_CONTROL = 2;
pub const SOCK = struct {
pub const STREAM = 1;
pub const DGRAM = 2;
pub const RAW = 3;
pub const RDM = 4;
pub const SEQPACKET = 5;
pub const MAXADDRLEN = 255;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other `SOCK` bits.
pub const CLOEXEC = 1 << 15;
/// Not actually supported by Darwin, but Zig supplies a shim.
/// This numerical value is not ABI-stable. It need only not conflict
/// with any other `SOCK` bits.
pub const NONBLOCK = 1 << 16;
};
pub const IPPROTO = struct {
pub const ICMP = 1;
pub const ICMPV6 = 58;
pub const TCP = 6;
pub const UDP = 17;
pub const IP = 0;
pub const IPV6 = 41;
};
pub const SOL = struct {
pub const SOCKET = 0xffff;
};
pub const SO = struct {
pub const DEBUG = 0x0001;
pub const ACCEPTCONN = 0x0002;
pub const REUSEADDR = 0x0004;
pub const KEEPALIVE = 0x0008;
pub const DONTROUTE = 0x0010;
pub const BROADCAST = 0x0020;
pub const USELOOPBACK = 0x0040;
pub const LINGER = 0x1080;
pub const OOBINLINE = 0x0100;
pub const REUSEPORT = 0x0200;
pub const ACCEPTFILTER = 0x1000;
pub const SNDBUF = 0x1001;
pub const RCVBUF = 0x1002;
pub const SNDLOWAT = 0x1003;
pub const RCVLOWAT = 0x1004;
pub const SNDTIMEO = 0x1005;
pub const RCVTIMEO = 0x1006;
pub const ERROR = 0x1007;
pub const TYPE = 0x1008;
pub const NREAD = 0x1020;
pub const NKE = 0x1021;
pub const NOSIGPIPE = 0x1022;
pub const NOADDRERR = 0x1023;
pub const NWRITE = 0x1024;
pub const REUSESHAREUID = 0x1025;
};
pub const W = struct {
/// [XSI] no hang in wait/no child to reap
pub const NOHANG = 0x00000001;
/// [XSI] notify on stop, untraced child
pub const UNTRACED = 0x00000002;
pub fn EXITSTATUS(x: u32) u8 {
return @intCast(u8, x >> 8);
}
pub fn TERMSIG(x: u32) u32 {
return status(x);
}
pub fn STOPSIG(x: u32) u32 {
return x >> 8;
}
pub fn IFEXITED(x: u32) bool {
return status(x) == 0;
}
pub fn IFSTOPPED(x: u32) bool {
return status(x) == stopped and STOPSIG(x) != 0x13;
}
pub fn IFSIGNALED(x: u32) bool {
return status(x) != stopped and status(x) != 0;
}
fn status(x: u32) u32 {
return x & 0o177;
}
const stopped = 0o177;
};
pub const E = enum(u16) {
/// No error occurred.
SUCCESS = 0,
/// Operation not permitted
PERM = 1,
/// No such file or directory
NOENT = 2,
/// No such process
SRCH = 3,
/// Interrupted system call
INTR = 4,
/// Input/output error
IO = 5,
/// Device not configured
NXIO = 6,
/// Argument list too long
@"2BIG" = 7,
/// Exec format error
NOEXEC = 8,
/// Bad file descriptor
BADF = 9,
/// No child processes
CHILD = 10,
/// Resource deadlock avoided
DEADLK = 11,
/// Cannot allocate memory
NOMEM = 12,
/// Permission denied
ACCES = 13,
/// Bad address
FAULT = 14,
/// Block device required
NOTBLK = 15,
/// Device / Resource busy
BUSY = 16,
/// File exists
EXIST = 17,
/// Cross-device link
XDEV = 18,
/// Operation not supported by device
NODEV = 19,
/// Not a directory
NOTDIR = 20,
/// Is a directory
ISDIR = 21,
/// Invalid argument
INVAL = 22,
/// Too many open files in system
NFILE = 23,
/// Too many open files
MFILE = 24,
/// Inappropriate ioctl for device
NOTTY = 25,
/// Text file busy
TXTBSY = 26,
/// File too large
FBIG = 27,
/// No space left on device
NOSPC = 28,
/// Illegal seek
SPIPE = 29,
/// Read-only file system
ROFS = 30,
/// Too many links
MLINK = 31,
/// Broken pipe
PIPE = 32,
// math software
/// Numerical argument out of domain
DOM = 33,
/// Result too large
RANGE = 34,
// non-blocking and interrupt i/o
/// Resource temporarily unavailable
/// This is the same code used for `WOULDBLOCK`.
AGAIN = 35,
/// Operation now in progress
INPROGRESS = 36,
/// Operation already in progress
ALREADY = 37,
// ipc/network software -- argument errors
/// Socket operation on non-socket
NOTSOCK = 38,
/// Destination address required
DESTADDRREQ = 39,
/// Message too long
MSGSIZE = 40,
/// Protocol wrong type for socket
PROTOTYPE = 41,
/// Protocol not available
NOPROTOOPT = 42,
/// Protocol not supported
PROTONOSUPPORT = 43,
/// Socket type not supported
SOCKTNOSUPPORT = 44,
/// Operation not supported
/// The same code is used for `NOTSUP`.
OPNOTSUPP = 45,
/// Protocol family not supported
PFNOSUPPORT = 46,
/// Address family not supported by protocol family
AFNOSUPPORT = 47,
/// Address already in use
ADDRINUSE = 48,
/// Can't assign requested address
// ipc/network software -- operational errors
ADDRNOTAVAIL = 49,
/// Network is down
NETDOWN = 50,
/// Network is unreachable
NETUNREACH = 51,
/// Network dropped connection on reset
NETRESET = 52,
/// Software caused connection abort
CONNABORTED = 53,
/// Connection reset by peer
CONNRESET = 54,
/// No buffer space available
NOBUFS = 55,
/// Socket is already connected
ISCONN = 56,
/// Socket is not connected
NOTCONN = 57,
/// Can't send after socket shutdown
SHUTDOWN = 58,
/// Too many references: can't splice
TOOMANYREFS = 59,
/// Operation timed out
TIMEDOUT = 60,
/// Connection refused
CONNREFUSED = 61,
/// Too many levels of symbolic links
LOOP = 62,
/// File name too long
NAMETOOLONG = 63,
/// Host is down
HOSTDOWN = 64,
/// No route to host
HOSTUNREACH = 65,
/// Directory not empty
// quotas & mush
NOTEMPTY = 66,
/// Too many processes
PROCLIM = 67,
/// Too many users
USERS = 68,
/// Disc quota exceeded
// Network File System
DQUOT = 69,
/// Stale NFS file handle
STALE = 70,
/// Too many levels of remote in path
REMOTE = 71,
/// RPC struct is bad
BADRPC = 72,
/// RPC version wrong
RPCMISMATCH = 73,
/// RPC prog. not avail
PROGUNAVAIL = 74,
/// Program version wrong
PROGMISMATCH = 75,
/// Bad procedure for program
PROCUNAVAIL = 76,
/// No locks available
NOLCK = 77,
/// Function not implemented
NOSYS = 78,
/// Inappropriate file type or format
FTYPE = 79,
/// Authentication error
AUTH = 80,
/// Need authenticator
NEEDAUTH = 81,
// Intelligent device errors
/// Device power is off
PWROFF = 82,
/// Device error, e.g. paper out
DEVERR = 83,
/// Value too large to be stored in data type
OVERFLOW = 84,
// Program loading errors
/// Bad executable
BADEXEC = 85,
/// Bad CPU type in executable
BADARCH = 86,
/// Shared library version mismatch
SHLIBVERS = 87,
/// Malformed Macho file
BADMACHO = 88,
/// Operation canceled
CANCELED = 89,
/// Identifier removed
IDRM = 90,
/// No message of desired type
NOMSG = 91,
/// Illegal byte sequence
ILSEQ = 92,
/// Attribute not found
NOATTR = 93,
/// Bad message
BADMSG = 94,
/// Reserved
MULTIHOP = 95,
/// No message available on STREAM
NODATA = 96,
/// Reserved
NOLINK = 97,
/// No STREAM resources
NOSR = 98,
/// Not a STREAM
NOSTR = 99,
/// Protocol error
PROTO = 100,
/// STREAM ioctl timeout
TIME = 101,
/// No such policy registered
NOPOLICY = 103,
/// State not recoverable
NOTRECOVERABLE = 104,
/// Previous owner died
OWNERDEAD = 105,
/// Interface output queue is full
QFULL = 106,
_,
};
pub const SIGSTKSZ = 131072;
pub const MINSIGSTKSZ = 32768;
pub const SS_ONSTACK = 1;
pub const SS_DISABLE = 4;
pub const stack_t = extern struct {
sp: [*]u8,
size: isize,
flags: i32,
};
pub const S = struct {
pub const IFMT = 0o170000;
pub const IFIFO = 0o010000;
pub const IFCHR = 0o020000;
pub const IFDIR = 0o040000;
pub const IFBLK = 0o060000;
pub const IFREG = 0o100000;
pub const IFLNK = 0o120000;
pub const IFSOCK = 0o140000;
pub const IFWHT = 0o160000;
pub const ISUID = 0o4000;
pub const ISGID = 0o2000;
pub const ISVTX = 0o1000;
pub const IRWXU = 0o700;
pub const IRUSR = 0o400;
pub const IWUSR = 0o200;
pub const IXUSR = 0o100;
pub const IRWXG = 0o070;
pub const IRGRP = 0o040;
pub const IWGRP = 0o020;
pub const IXGRP = 0o010;
pub const IRWXO = 0o007;
pub const IROTH = 0o004;
pub const IWOTH = 0o002;
pub const IXOTH = 0o001;
pub fn ISFIFO(m: u32) bool {
return m & IFMT == IFIFO;
}
pub fn ISCHR(m: u32) bool {
return m & IFMT == IFCHR;
}
pub fn ISDIR(m: u32) bool {
return m & IFMT == IFDIR;
}
pub fn ISBLK(m: u32) bool {
return m & IFMT == IFBLK;
}
pub fn ISREG(m: u32) bool {
return m & IFMT == IFREG;
}
pub fn ISLNK(m: u32) bool {
return m & IFMT == IFLNK;
}
pub fn ISSOCK(m: u32) bool {
return m & IFMT == IFSOCK;
}
pub fn IWHT(m: u32) bool {
return m & IFMT == IFWHT;
}
};
pub const HOST_NAME_MAX = 72;
pub const AT = struct {
pub const FDCWD = -2;
/// Use effective ids in access check
pub const EACCESS = 0x0010;
/// Act on the symlink itself not the target
pub const SYMLINK_NOFOLLOW = 0x0020;
/// Act on target of symlink
pub const SYMLINK_FOLLOW = 0x0040;
/// Path refers to directory
pub const REMOVEDIR = 0x0080;
};
pub const addrinfo = extern struct {
flags: i32,
family: i32,
socktype: i32,
protocol: i32,
addrlen: socklen_t,
canonname: ?[*:0]u8,
addr: ?*sockaddr,
next: ?*addrinfo,
};
pub const RTLD = struct {
pub const LAZY = 0x1;
pub const NOW = 0x2;
pub const LOCAL = 0x4;
pub const GLOBAL = 0x8;
pub const NOLOAD = 0x10;
pub const NODELETE = 0x80;
pub const FIRST = 0x100;
pub const NEXT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -1)));
pub const DEFAULT = @intToPtr(*c_void, @bitCast(usize, @as(isize, -2)));
pub const SELF = @intToPtr(*c_void, @bitCast(usize, @as(isize, -3)));
pub const MAIN_ONLY = @intToPtr(*c_void, @bitCast(usize, @as(isize, -5)));
};
pub const F = struct {
/// duplicate file descriptor
pub const DUPFD = 0;
/// get file descriptor flags
pub const GETFD = 1;
/// set file descriptor flags
pub const SETFD = 2;
/// get file status flags
pub const GETFL = 3;
/// set file status flags
pub const SETFL = 4;
/// get SIGIO/SIGURG proc/pgrp
pub const GETOWN = 5;
/// set SIGIO/SIGURG proc/pgrp
pub const SETOWN = 6;
/// get record locking information
pub const GETLK = 7;
/// set record locking information
pub const SETLK = 8;
/// F.SETLK; wait if blocked
pub const SETLKW = 9;
/// F.SETLK; wait if blocked, return on timeout
pub const SETLKWTIMEOUT = 10;
pub const FLUSH_DATA = 40;
/// Used for regression test
pub const CHKCLEAN = 41;
/// Preallocate storage
pub const PREALLOCATE = 42;
/// Truncate a file without zeroing space
pub const SETSIZE = 43;
/// Issue an advisory read async with no copy to user
pub const RDADVISE = 44;
/// turn read ahead off/on for this fd
pub const RDAHEAD = 45;
/// turn data caching off/on for this fd
pub const NOCACHE = 48;
/// file offset to device offset
pub const LOG2PHYS = 49;
/// return the full path of the fd
pub const GETPATH = 50;
/// fsync + ask the drive to flush to the media
pub const FULLFSYNC = 51;
/// find which component (if any) is a package
pub const PATHPKG_CHECK = 52;
/// "freeze" all fs operations
pub const FREEZE_FS = 53;
/// "thaw" all fs operations
pub const THAW_FS = 54;
/// turn data caching off/on (globally) for this file
pub const GLOBAL_NOCACHE = 55;
/// add detached signatures
pub const ADDSIGS = 59;
/// add signature from same file (used by dyld for shared libs)
pub const ADDFILESIGS = 61;
/// used in conjunction with F.NOCACHE to indicate that DIRECT, synchonous writes
/// should not be used (i.e. its ok to temporaily create cached pages)
pub const NODIRECT = 62;
///Get the protection class of a file from the EA, returns int
pub const GETPROTECTIONCLASS = 63;
///Set the protection class of a file for the EA, requires int
pub const SETPROTECTIONCLASS = 64;
///file offset to device offset, extended
pub const LOG2PHYS_EXT = 65;
///get record locking information, per-process
pub const GETLKPID = 66;
///Mark the file as being the backing store for another filesystem
pub const SETBACKINGSTORE = 70;
///return the full path of the FD, but error in specific mtmd circumstances
pub const GETPATH_MTMINFO = 71;
///Returns the code directory, with associated hashes, to the caller
pub const GETCODEDIR = 72;
///No SIGPIPE generated on EPIPE
pub const SETNOSIGPIPE = 73;
///Status of SIGPIPE for this fd
pub const GETNOSIGPIPE = 74;
///For some cases, we need to rewrap the key for AKS/MKB
pub const TRANSCODEKEY = 75;
///file being written to a by single writer... if throttling enabled, writes
///may be broken into smaller chunks with throttling in between
pub const SINGLE_WRITER = 76;
///Get the protection version number for this filesystem
pub const GETPROTECTIONLEVEL = 77;
///Add detached code signatures (used by dyld for shared libs)
pub const FINDSIGS = 78;
///Add signature from same file, only if it is signed by Apple (used by dyld for simulator)
pub const ADDFILESIGS_FOR_DYLD_SIM = 83;
///fsync + issue barrier to drive
pub const BARRIERFSYNC = 85;
///Add signature from same file, return end offset in structure on success
pub const ADDFILESIGS_RETURN = 97;
///Check if Library Validation allows this Mach-O file to be mapped into the calling process
pub const CHECK_LV = 98;
///Deallocate a range of the file
pub const PUNCHHOLE = 99;
///Trim an active file
pub const TRIM_ACTIVE_FILE = 100;
///mark the dup with FD_CLOEXEC
pub const DUPFD_CLOEXEC = 67;
/// shared or read lock
pub const RDLCK = 1;
/// unlock
pub const UNLCK = 2;
/// exclusive or write lock
pub const WRLCK = 3;
};
pub const FCNTL_FS_SPECIFIC_BASE = 0x00010000;
///close-on-exec flag
pub const FD_CLOEXEC = 1;
pub const LOCK = struct {
pub const SH = 1;
pub const EX = 2;
pub const UN = 8;
pub const NB = 4;
};
pub const nfds_t = u32;
pub const pollfd = extern struct {
fd: fd_t,
events: i16,
revents: i16,
};
pub const POLL = struct {
pub const IN = 0x001;
pub const PRI = 0x002;
pub const OUT = 0x004;
pub const RDNORM = 0x040;
pub const WRNORM = OUT;
pub const RDBAND = 0x080;
pub const WRBAND = 0x100;
pub const EXTEND = 0x0200;
pub const ATTRIB = 0x0400;
pub const NLINK = 0x0800;
pub const WRITE = 0x1000;
pub const ERR = 0x008;
pub const HUP = 0x010;
pub const NVAL = 0x020;
pub const STANDARD = IN | PRI | OUT | RDNORM | RDBAND | WRBAND | ERR | HUP | NVAL;
};
pub const CLOCK = struct {
pub const REALTIME = 0;
pub const MONOTONIC = 6;
pub const MONOTONIC_RAW = 4;
pub const MONOTONIC_RAW_APPROX = 5;
pub const UPTIME_RAW = 8;
pub const UPTIME_RAW_APPROX = 9;
pub const PROCESS_CPUTIME_ID = 12;
pub const THREAD_CPUTIME_ID = 16;
};
/// Max open files per process
/// https://opensource.apple.com/source/xnu/xnu-4903.221.2/bsd/sys/syslimits.h.auto.html
pub const OPEN_MAX = 10240;
pub const rusage = extern struct {
utime: timeval,
stime: timeval,
maxrss: isize,
ixrss: isize,
idrss: isize,
isrss: isize,
minflt: isize,
majflt: isize,
nswap: isize,
inblock: isize,
oublock: isize,
msgsnd: isize,
msgrcv: isize,
nsignals: isize,
nvcsw: isize,
nivcsw: isize,
pub const SELF = 0;
pub const CHILDREN = -1;
};
pub const rlimit_resource = enum(c_int) {
CPU = 0,
FSIZE = 1,
DATA = 2,
STACK = 3,
CORE = 4,
RSS = 5,
MEMLOCK = 6,
NPROC = 7,
NOFILE = 8,
_,
pub const AS: rlimit_resource = .RSS;
};
pub const rlim_t = u64;
pub const RLIM = struct {
/// No limit
pub const INFINITY: rlim_t = (1 << 63) - 1;
pub const SAVED_MAX = INFINITY;
pub const SAVED_CUR = INFINITY;
};
pub const rlimit = extern struct {
/// Soft limit
cur: rlim_t,
/// Hard limit
max: rlim_t,
};
pub const SHUT = struct {
pub const RD = 0;
pub const WR = 1;
pub const RDWR = 2;
};
// Term
pub const VEOF = 0;
pub const VEOL = 1;
pub const VEOL2 = 2;
pub const VERASE = 3;
pub const VWERASE = 4;
pub const VKILL = 5;
pub const VREPRINT = 6;
pub const VINTR = 8;
pub const VQUIT = 9;
pub const VSUSP = 10;
pub const VDSUSP = 11;
pub const VSTART = 12;
pub const VSTOP = 13;
pub const VLNEXT = 14;
pub const VDISCARD = 15;
pub const VMIN = 16;
pub const VTIME = 17;
pub const VSTATUS = 18;
pub const NCCS = 20; // 2 spares (7, 19)
pub const IGNBRK = 0x00000001; // ignore BREAK condition
pub const BRKINT = 0x00000002; // map BREAK to SIGINTR
pub const IGNPAR = 0x00000004; // ignore (discard) parity errors
pub const PARMRK = 0x00000008; // mark parity and framing errors
pub const INPCK = 0x00000010; // enable checking of parity errors
pub const ISTRIP = 0x00000020; // strip 8th bit off chars
pub const INLCR = 0x00000040; // map NL into CR
pub const IGNCR = 0x00000080; // ignore CR
pub const ICRNL = 0x00000100; // map CR to NL (ala CRMOD)
pub const IXON = 0x00000200; // enable output flow control
pub const IXOFF = 0x00000400; // enable input flow control
pub const IXANY = 0x00000800; // any char will restart after stop
pub const IMAXBEL = 0x00002000; // ring bell on input queue full
pub const IUTF8 = 0x00004000; // maintain state for UTF-8 VERASE
pub const OPOST = 0x00000001; //enable following output processing
pub const ONLCR = 0x00000002; // map NL to CR-NL (ala CRMOD)
pub const OXTABS = 0x00000004; // expand tabs to spaces
pub const ONOEOT = 0x00000008; // discard EOT's (^D) on output)
pub const OCRNL = 0x00000010; // map CR to NL on output
pub const ONOCR = 0x00000020; // no CR output at column 0
pub const ONLRET = 0x00000040; // NL performs CR function
pub const OFILL = 0x00000080; // use fill characters for delay
pub const NLDLY = 0x00000300; // \n delay
pub const TABDLY = 0x00000c04; // horizontal tab delay
pub const CRDLY = 0x00003000; // \r delay
pub const FFDLY = 0x00004000; // form feed delay
pub const BSDLY = 0x00008000; // \b delay
pub const VTDLY = 0x00010000; // vertical tab delay
pub const OFDEL = 0x00020000; // fill is DEL, else NUL
pub const NL0 = 0x00000000;
pub const NL1 = 0x00000100;
pub const NL2 = 0x00000200;
pub const NL3 = 0x00000300;
pub const TAB0 = 0x00000000;
pub const TAB1 = 0x00000400;
pub const TAB2 = 0x00000800;
pub const TAB3 = 0x00000004;
pub const CR0 = 0x00000000;
pub const CR1 = 0x00001000;
pub const CR2 = 0x00002000;
pub const CR3 = 0x00003000;
pub const FF0 = 0x00000000;
pub const FF1 = 0x00004000;
pub const BS0 = 0x00000000;
pub const BS1 = 0x00008000;
pub const VT0 = 0x00000000;
pub const VT1 = 0x00010000;
pub const CIGNORE = 0x00000001; // ignore control flags
pub const CSIZE = 0x00000300; // character size mask
pub const CS5 = 0x00000000; // 5 bits (pseudo)
pub const CS6 = 0x00000100; // 6 bits
pub const CS7 = 0x00000200; // 7 bits
pub const CS8 = 0x00000300; // 8 bits
pub const CSTOPB = 0x0000040; // send 2 stop bits
pub const CREAD = 0x00000800; // enable receiver
pub const PARENB = 0x00001000; // parity enable
pub const PARODD = 0x00002000; // odd parity, else even
pub const HUPCL = 0x00004000; // hang up on last close
pub const CLOCAL = 0x00008000; // ignore modem status lines
pub const CCTS_OFLOW = 0x00010000; // CTS flow control of output
pub const CRTSCTS = (CCTS_OFLOW | CRTS_IFLOW);
pub const CRTS_IFLOW = 0x00020000; // RTS flow control of input
pub const CDTR_IFLOW = 0x00040000; // DTR flow control of input
pub const CDSR_OFLOW = 0x00080000; // DSR flow control of output
pub const CCAR_OFLOW = 0x00100000; // DCD flow control of output
pub const MDMBUF = 0x00100000; // old name for CCAR_OFLOW
pub const ECHOKE = 0x00000001; // visual erase for line kill
pub const ECHOE = 0x00000002; // visually erase chars
pub const ECHOK = 0x00000004; // echo NL after line kill
pub const ECHO = 0x00000008; // enable echoing
pub const ECHONL = 0x00000010; // echo NL even if ECHO is off
pub const ECHOPRT = 0x00000020; // visual erase mode for hardcopy
pub const ECHOCTL = 0x00000040; // echo control chars as ^(Char)
pub const ISIG = 0x00000080; // enable signals INTR, QUIT, [D]SUSP
pub const ICANON = 0x00000100; // canonicalize input lines
pub const ALTWERASE = 0x00000200; // use alternate WERASE algorithm
pub const IEXTEN = 0x00000400; // enable DISCARD and LNEXT
pub const EXTPROC = 0x00000800; // external processing
pub const TOSTOP = 0x00400000; // stop background jobs from output
pub const FLUSHO = 0x00800000; // output being flushed (state)
pub const NOKERNINFO = 0x02000000; // no kernel output from VSTATUS
pub const PENDIN = 0x20000000; // XXX retype pending input (state)
pub const NOFLSH = 0x80000000; // don't flush after interrupt
pub const TCSANOW = 0; // make change immediate
pub const TCSADRAIN = 1; // drain output, then change
pub const TCSAFLUSH = 2; // drain output, flush input
pub const TCSASOFT = 0x10; // flag - don't alter h.w. state
pub const TCSA = enum(c_uint) {
NOW,
DRAIN,
FLUSH,
_,
};
pub const B0 = 0;
pub const B50 = 50;
pub const B75 = 75;
pub const B110 = 110;
pub const B134 = 134;
pub const B150 = 150;
pub const B200 = 200;
pub const B300 = 300;
pub const B600 = 600;
pub const B1200 = 1200;
pub const B1800 = 1800;
pub const B2400 = 2400;
pub const B4800 = 4800;
pub const B9600 = 9600;
pub const B19200 = 19200;
pub const B38400 = 38400;
pub const B7200 = 7200;
pub const B14400 = 14400;
pub const B28800 = 28800;
pub const B57600 = 57600;
pub const B76800 = 76800;
pub const B115200 = 115200;
pub const B230400 = 230400;
pub const EXTA = 19200;
pub const EXTB = 38400;
pub const TCIFLUSH = 1;
pub const TCOFLUSH = 2;
pub const TCIOFLUSH = 3;
pub const TCOOFF = 1;
pub const TCOON = 2;
pub const TCIOFF = 3;
pub const TCION = 4;
pub const cc_t = u8;
pub const speed_t = u64;
pub const tcflag_t = u64;
pub const termios = extern struct {
iflag: tcflag_t, // input flags
oflag: tcflag_t, // output flags
cflag: tcflag_t, // control flags
lflag: tcflag_t, // local flags
cc: [NCCS]cc_t, // control chars
ispeed: speed_t align(8), // input speed
ospeed: speed_t, // output speed
};
pub const winsize = extern struct {
ws_row: u16,
ws_col: u16,
ws_xpixel: u16,
ws_ypixel: u16,
};
pub const T = struct {
pub const IOCGWINSZ = ior(0x40000000, 't', 104, @sizeOf(winsize));
};
pub const IOCPARM_MASK = 0x1fff;
fn ior(inout: u32, group: usize, num: usize, len: usize) usize {
return (inout | ((len & IOCPARM_MASK) << 16) | ((group) << 8) | (num));
}
// CPU families mapping
pub const CPUFAMILY = enum(u32) {
UNKNOWN = 0,
POWERPC_G3 = 0xcee41549,
POWERPC_G4 = 0x77c184ae,
POWERPC_G5 = 0xed76d8aa,
INTEL_6_13 = 0xaa33392b,
INTEL_PENRYN = 0x78ea4fbc,
INTEL_NEHALEM = 0x6b5a4cd2,
INTEL_WESTMERE = 0x573b5eec,
INTEL_SANDYBRIDGE = 0x5490b78c,
INTEL_IVYBRIDGE = 0x1f65e835,
INTEL_HASWELL = 0x10b282dc,
INTEL_BROADWELL = 0x582ed09c,
INTEL_SKYLAKE = 0x37fc219f,
INTEL_KABYLAKE = 0x0f817246,
ARM_9 = 0xe73283ae,
ARM_11 = 0x8ff620d8,
ARM_XSCALE = 0x53b005f5,
ARM_12 = 0xbd1b0ae9,
ARM_13 = 0x0cc90e64,
ARM_14 = 0x96077ef1,
ARM_15 = 0xa8511bca,
ARM_SWIFT = 0x1e2d6381,
ARM_CYCLONE = 0x37a09642,
ARM_TYPHOON = 0x2c91a47e,
ARM_TWISTER = 0x92fb37c8,
ARM_HURRICANE = 0x67ceee93,
ARM_MONSOON_MISTRAL = 0xe81e7ef6,
ARM_VORTEX_TEMPEST = 0x07d34b9f,
ARM_LIGHTNING_THUNDER = 0x462504d2,
ARM_FIRESTORM_ICESTORM = 0x1b588bb3,
_,
}; | lib/std/c/darwin.zig |
const partOne = 133 * 134 / 2;
const std = @import("std");
const Allocator = std.mem.Allocator;
const List = std.ArrayList;
const Str = []const u8;
const BitSet = std.DynamicBitSet;
const StrMap = std.StringHashMap;
const HashMap = std.HashMap;
const Map = std.AutoHashMap;
const PriorityQueue = std.PriorityQueue;
const assert = std.debug.assert;
const tokenize = std.mem.tokenize;
const print = std.debug.print;
const parseInt = std.fmt.parseInt;
const abs = std.math.absInt;
fn sort(comptime T: type, items: []T) void {
std.sort.sort(T, items, {}, comptime std.sort.asc(T));
}
fn println(x: Str) void {
print("{s}\n", .{x});
}
const TargetBox = struct {
startX: i32,
endX: i32,
startY: i32,
endY: i32,
};
const inputFile = TargetBox{
.startX = 175,
.endX = 227,
.startY = -134,
.endY = -79,
};
/// Solves for the smallest y where T(y) >= x
fn inverseTriangularGeq(x: i32) i32 {
assert(x >= 0);
// n^2 + n - 2*x = 0;
// real solution for n is (-1 + sqrt(1 + 8 * x)) / 2.0
const n: f32 = (@sqrt(@intToFloat(f32, 1 + 8 * x)) - 1.0) / 2.0;
return @floatToInt(i32, @ceil(n));
}
/// Simulates a single run of whether
fn doesHitTargetBox(target: TargetBox, initialX: i32, initialY: i32) bool {
var x = initialX;
var vx = initialX;
var y = initialY;
var vy = initialY;
while (true) {
// bounds check
if (x > target.endX or y < target.startY) return false;
if (x >= target.startX and x <= target.endX and y >= target.startY and y <= target.endY) return true;
if (vx > 0) vx -= 1;
vy -= 1;
x += vx;
y += vy;
}
}
fn partTwo(target: TargetBox) usize {
// search in the range that is reachable in min 2 steps
// the range of 1 step is easily computable
// we use divTrunc because we want 2x > -135
const minY = @divTrunc(target.startY + 1, 2);
const maxY = (abs(target.startY) catch unreachable) - 1;
const minX = inverseTriangularGeq(target.startX);
const maxX = @divFloor(target.endX, 2) + 1;
var result = @intCast(usize, (target.endX - target.startX + 1) * (target.endY - target.startY + 1));
var x = minX;
while (x <= maxX) : (x += 1) {
var y = minY;
while (y <= maxY) : (y += 1) {
if (doesHitTargetBox(target, x, y)) {
result += 1;
}
}
}
return result;
}
pub fn main() !void {
// Standard boilerplate for Aoc problems
const stdout = std.io.getStdOut().writer();
// var gpa = std.heap.GeneralPurposeAllocator(.{}){};
// var gpaAllocator = gpa.allocator();
// defer assert(!gpa.deinit()); // Check for memory leaks
// var arena = std.heap.ArenaAllocator.init(gpaAllocator);
// defer arena.deinit();
// var allocator = arena.allocator();
try stdout.print("Part 1: {d}Part2: {d}\n", .{ partOne, partTwo(inputFile) });
}
test "Part 2" {
const testInput = TargetBox{
.startX = 20,
.endX = 30,
.startY = -10,
.endY = -5,
};
try std.testing.expectEqual(@as(usize, 112), partTwo(testInput));
} | src/day17.zig |
const std = @import("std");
const assert = std.debug.assert;
const kernel = @import("root");
const lib = kernel.lib;
pub const vga = @import("x86/vga.zig");
pub const serial = @import("x86/serial.zig");
pub const pic = @import("x86/pic.zig");
pub const keyboard = @import("x86/keyboard.zig");
pub const mm = @import("x86/mm.zig");
pub const multiboot = @import("x86/multiboot.zig");
pub const acpi = @import("x86/acpi.zig");
pub const pci = @import("x86/pci.zig");
pub const apic = @import("x86/apic.zig");
pub const trampoline = @import("x86/trampoline.zig");
pub const smp = @import("x86/smp.zig");
pub const gdt = @import("x86/gdt.zig");
pub const framebuffer = @import("x86/framebuffer.zig");
comptime {
// Force multiboot evaluation to make multiboot_entry present
_ = multiboot;
}
pub const logger = @TypeOf(kernel.logger).childOf(@typeName(@This())){};
const GDT = gdt.GlobalDescriptorTable(8);
const IDT = InterruptDescriptorTable;
pub var main_gdt align(64) = GDT.new();
pub var main_tss align(64) = std.mem.zeroes(gdt.TSS);
pub var main_idt align(64) = std.mem.zeroes(IDT);
/// Physical-address width supported by the processor. <= 52
pub var cpu_phys_bits: u6 = undefined;
pub const CPUIDInfo = packed struct {
eax: u32,
ebx: u32,
ecx: u32,
edx: u32,
fn to_bytes(self: @This()) [16]u8 {
var output: [16]u8 = undefined;
std.mem.copy(u8, output[0..4], std.mem.toBytes(self.eax)[0..]);
std.mem.copy(u8, output[4..8], std.mem.toBytes(self.ebx)[0..]);
std.mem.copy(u8, output[8..12], std.mem.toBytes(self.ecx)[0..]);
std.mem.copy(u8, output[12..16], std.mem.toBytes(self.edx)[0..]);
return output;
}
};
pub inline fn cpuid(leaf: u32, subleaf: u32) CPUIDInfo {
var info: CPUIDInfo = undefined;
asm volatile (
\\ cpuid
\\ movl %%eax, 0(%[info])
\\ movl %%ebx, 4(%[info])
\\ movl %%ecx, 8(%[info])
\\ movl %%edx, 12(%[info])
:
: [leaf] "{eax}" (leaf),
[subleaf] "{ecx}" (subleaf),
[info] "r" (&info),
: "eax", "ebx", "ecx", "edx", "m"
);
return info;
}
pub const CR3 = struct {
pub inline fn read() u64 {
return asm volatile ("movq %%cr3, %[ret]"
: [ret] "=rax" (-> u64),
);
}
pub inline fn write(value: u64) void {
asm volatile ("movq %[value], %%cr3"
:
: [value] "{rax}" (value),
);
}
};
pub const CR2 = struct {
pub inline fn read() u64 {
return asm volatile ("movq %%cr2, %[ret]"
: [ret] "=rax" (-> u64),
);
}
};
pub inline fn ltr(selector: u16) void {
asm volatile ("ltr %[selector]"
:
: [selector] "{ax}" (selector),
);
}
pub inline fn lgdt(addr: u64) void {
asm volatile ("lgdt (%[addr])"
:
: [addr] "{rdi}" (addr),
);
}
pub inline fn out(comptime T: type, address: u16, value: T) void {
switch (T) {
u8 => asm volatile ("out %[value], %[address]"
:
: [address] "{dx}" (address),
[value] "{al}" (value),
),
u16 => asm volatile ("out %[value], %[address]"
:
: [address] "{dx}" (address),
[value] "{ax}" (value),
),
u32 => asm volatile ("out %[value], %[address]"
:
: [address] "dx" (address),
[value] "{eax}" (value),
),
else => @compileError("Invalid write type"),
}
}
pub inline fn in(comptime T: type, address: u16) T {
return switch (T) {
u8 => asm volatile ("in %[address], %[ret]"
: [ret] "={al}" (-> u8),
: [address] "{dx}" (address),
),
u16 => asm volatile ("in %[address], %%ax"
: [ret] "={ax}" (-> u16),
: [address] "{dx}" (address),
),
u32 => asm volatile ("in %[address], %%eax"
: [ret] "={ax}" (-> u32),
: [address] "dx" (address),
),
else => @compileError("Invalid read type"),
};
}
pub inline fn hlt() void {
asm volatile ("hlt");
}
pub inline fn cli() void {
asm volatile ("cli");
}
pub inline fn sti() void {
asm volatile ("sti");
}
pub inline fn lidt(addr: u64) void {
asm volatile ("lidt (%[addr])"
:
: [addr] "{rdi}" (addr),
);
}
pub inline fn set_ds(selector: u16) void {
asm volatile ("movl %[selector], %%ds"
:
: [selector] "{eax}" (selector),
);
}
pub inline fn set_es(selector: u16) void {
asm volatile ("movl %[selector], %%es"
:
: [selector] "{eax}" (selector),
);
}
pub inline fn set_fs(selector: u16) void {
asm volatile ("movl %[selector], %%fs"
:
: [selector] "{eax}" (selector),
);
}
pub inline fn set_gs(selector: u16) void {
asm volatile ("movl %[selector], %%gs"
:
: [selector] "{eax}" (selector),
);
}
pub inline fn set_ss(selector: u16) void {
asm volatile ("movl %[selector], %%ss"
:
: [selector] "{eax}" (selector),
);
}
pub inline fn rdmsr(which: u32) u64 {
return asm volatile (
\\ rdmsr
\\ # results are in EDX:EAX
\\ shl $32, %%rdx
\\ or %%rdx, %%rax
: [ret] "={rax}" (-> u64),
: [which] "{ecx}" (which),
: "rdx"
);
}
pub inline fn wrmsr(which: u32, value: u64) void {
return asm volatile ("wrmsr"
:
: [high] "{edx}" (value >> 32),
[low] "{eax}" (@truncate(u32, value)),
[which] "{ecx}" (which),
);
}
// This subsection discusses usage of each register. Registers %rbp, %rbx and
// %r12 through %r15 “belong” to the calling function and the called function is
// required to preserve their values
pub extern fn asm_switch_task(from: *TaskRegs, to: *TaskRegs) callconv(.C) void;
comptime {
asm (
\\.type asm_switch_task @function;
\\asm_switch_task:
\\ # Save registers
\\ push %rbp
\\ push %rbx
\\ push %r12
\\ push %r13
\\ push %r14
\\ push %r15
\\ # Switch stack
\\ mov %rsp, 0(%rdi)
\\ mov 0(%rsi), %rsp
\\ # Restore registers
\\ pop %r15
\\ pop %r14
\\ pop %r13
\\ pop %r12
\\ pop %rbx
\\ pop %rbp
\\ retq
);
}
pub inline fn get_phy_mask() u64 {
const one: u64 = 1;
return @shlExact(one, cpu_phys_bits) - 1;
}
pub const TaskRegs = packed struct {
// Layout must be kept in sync with asm_switch_stack
rsp: u64,
stack_bottom: u64,
const Self = @This();
pub fn setup(func: fn () noreturn, thread_stack: []u8) TaskRegs {
// 7 == #saved registers + return address
const reg_area_size = @sizeOf(u64) * 7;
var reg_area = thread_stack[thread_stack.len - reg_area_size ..];
var rip_area = reg_area[6 * @sizeOf(u64) ..];
std.mem.set(u8, reg_area, 0);
std.mem.writeIntNative(u64, @ptrCast(*[8]u8, rip_area), @ptrToInt(func));
return TaskRegs{ .rsp = @ptrToInt(reg_area.ptr), .stack_bottom = @ptrToInt(reg_area.ptr) };
}
pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, stream: anytype) !void {
_ = fmt;
try stream.writeAll(@typeName(Self));
try stream.writeAll("{rsp=0x");
try std.fmt.formatInt(self.rsp, 16, .lower, options, stream);
try stream.writeAll("}");
}
};
pub const InterruptDescriptorTable = packed struct {
entries: [256]Entry,
pub const Entry = packed struct {
raw: packed struct {
offset_low: u16,
selector: u16,
ist: u8,
type_attr: u8,
offset_mid: u16,
offset_high: u32,
reserved__: u32,
},
comptime {
assert(@sizeOf(@This()) == 16);
}
pub fn new(addr: u64, code_selector: gdt.SegmentSelector, _: u3, dpl: u2) Entry {
return .{
.raw = .{
.reserved__ = 0,
.offset_low = @intCast(u16, addr & 0xffff),
.offset_high = @intCast(u32, addr >> 32),
.offset_mid = @intCast(u16, (addr >> 16) & 0xffff),
.ist = 0,
.type_attr = 0b10001110 | (@as(u8, dpl) << 5),
.selector = code_selector.raw,
},
};
}
};
const Self = @This();
pub fn set_entry(self: *Self, which: u16, entry: Entry) void {
self.entries[which] = entry;
}
pub fn load(self: Self) void {
const descriptor = packed struct {
size: u16,
base: u64,
}{
.base = @ptrToInt(&self.entries),
.size = @sizeOf(@TypeOf(self.entries)) - 1,
};
lidt(@ptrToInt(&descriptor));
}
};
pub const InterruptFrame = packed struct {
rip: u64,
cs: u64,
flags: u64,
rsp: u64,
ss: u64,
comptime {
assert(@sizeOf(InterruptFrame) == 40);
}
pub fn format(
self: InterruptFrame,
fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
_ = try writer.write("InterruptFrame{");
_ = try writer.print("rip={x}:{x}", .{ self.cs, self.rip });
_ = try writer.print(" rsp={x}:{x}", .{ self.ss, self.rsp });
_ = try writer.write("}");
}
};
pub fn get_vendor_string() [12]u8 {
const info = cpuid(0, 0);
const vals = [_]u32{ info.ebx, info.edx, info.ecx };
var result: [@sizeOf(@TypeOf(vals))]u8 = undefined;
std.mem.copy(u8, &result, std.mem.asBytes(&vals));
return result;
}
pub fn get_maxphyaddr() u6 {
const info = cpuid(0x80000008, 0);
return @truncate(u6, info.eax);
}
pub fn hang() noreturn {
while (true) {
cli();
hlt();
}
}
pub fn syscall_supported() bool {
const info = cpuid(0x80000001, 0);
return ((info.edx >> 11) & 1) != 0;
}
pub fn MSR(n: u32) type {
return struct {
pub inline fn read() u64 {
return rdmsr(n);
}
pub inline fn write(value: u64) void {
wrmsr(n, value);
}
};
}
pub const APIC_BASE = MSR(0x0000_001B);
pub const EFER = MSR(0xC000_0080);
pub const IA32_STAR = MSR(0xC000_0081);
pub const IA32_LSTAR = MSR(0xC000_0082);
pub const FSBASE = MSR(0xC000_0100);
pub const GSBASE = MSR(0xC000_0101);
pub const KERNEL_GSBASE = MSR(0xC000_0102);
fn format_to_vga(buffer: []const u8) void {
vga.getConsole().writer().writeAll(buffer) catch {};
}
fn format_to_com1(buffer: []const u8) void {
serial.SerialPort(1).writer().writeAll(buffer) catch {};
}
const Node = kernel.logging.SinkNode;
var vga_node = Node{ .data = format_to_vga };
var serial_node = Node{ .data = format_to_com1 };
pub const KERNEL_STACK_SIZE = 1 * 0x1000;
extern var KERNEL_BASE: [*]align(0x1000) u8;
extern var KERNEL_VIRT_BASE: *align(0x1000) u8;
pub var stack: [KERNEL_STACK_SIZE * 2]u8 align(0x10) = undefined;
pub fn boot_entry() noreturn {
kernel.logging.register_sink(&vga_node);
kernel.logging.register_sink(&serial_node);
kernel.task.init_task.regs.rsp = 0x2137;
kernel.task.init_task.regs.stack_bottom = @ptrToInt(&stack) + stack.len;
kernel.task.init_task.stack = &stack;
// setup identity mapping
const VIRT_START = kernel.mm.VirtualAddress.new(@ptrToInt(&KERNEL_VIRT_BASE));
const SIZE = lib.MiB(16);
mm.directMapping().* = kernel.mm.DirectMapping.init(VIRT_START, SIZE);
logger.debug("CR3: 0x{x}\n", .{CR3.read()});
logger.info("CPU Vendor: {e}\n", .{std.fmt.fmtSliceEscapeLower(&get_vendor_string())});
logger.debug("Kernel end: {x}\n", .{mm.get_kernel_end()});
logger.info("Booting the kernel...\n", .{});
logger.info("Command line: {s}\n", .{multiboot.get_cmdline()});
kernel.main.kmain();
hang();
}
pub fn idle() void {
while (true) {
hlt();
}
}
pub fn enable_interrupts() void {
sti();
}
const userspace_location = 0x1337000;
pub fn setup_userspace() !void {
const frame = try kernel.mm.frameAllocator().alloc_zero_frame();
_ = try kernel.mm.kernel_vm.map_memory(
kernel.mm.VirtualAddress.new(userspace_location),
frame,
0x1000,
kernel.mm.VirtualMemory.Protection{
.read = true,
.write = true,
.execute = true,
.user = true,
},
);
const program =
"\x90" ++ // nop
"\x90" ++ // nop
"\xcc" ++ // int3
"\x66\x87\xdb" ++ // bochs breakpoint
"\x0f\x05" ++ // syscall
"\xeb\xfc" // jmp to syscall
;
std.mem.copy(u8, @intToPtr([*]u8, userspace_location)[0..0x1000], program);
}
pub fn enter_userspace() void {
exit_to_userspace(userspace_location, 0x0);
}
const InterruptStub = fn () callconv(.Naked) void;
const CpuException = enum(u8) {
DivisionByZero = 0,
Debug = 1,
NonMaskableInterrupt = 2,
Breakpoint = 3,
Overflow = 4,
BoundRangeExceeded = 5,
InvalidOpcode = 6,
DeviceNotAvailable = 7,
DoubleFault = 8,
CoprocessorSegmentOverrun = 9,
InvalidTSS = 10,
SegmentNotPresent = 11,
StackSegmentFault = 12,
GeneralProtectionFault = 13,
PageFault = 14,
X87FloatingPointException = 16,
AlignmentCheck = 17,
MachineCheck = 18,
SIMDFloatingPointException = 19,
VirtualizationException = 20,
SecurityException = 30,
_,
};
fn has_error_code(vector: u16) bool {
return switch (vector) {
// Double Fault
0x8 => true,
// Invalid TSS
// Segment not present
// SS fault
// GP fault
// Page fault
0xa...0xe => true,
// Alignment check
0x11 => true,
// Security exception
0x1e => true,
else => false,
};
}
pub const IntHandler = fn (u8, u64, *InterruptFrame) callconv(.C) void;
pub const CoreBlock = struct {
current_task: *kernel.task.Task,
};
var initial_core_block: CoreBlock = CoreBlock{
.current_task = &kernel.task.init_task,
};
pub const GSStruct = packed struct {
cb: *CoreBlock,
scratch_space: u64,
};
var boot_cpu_gsstruct: GSStruct = GSStruct{
.cb = &initial_core_block,
.scratch_space = 0,
};
pub inline fn getCoreBlock() *CoreBlock {
const blockptr = asm volatile ("mov %%gs:0x0,%[ret]"
: [ret] "={rax}" (-> u64),
);
return @intToPtr(*CoreBlock, blockptr);
}
/// Generate stub for n-th exception
fn exception_stub(comptime n: u8) InterruptStub {
// Have to bump this, otherwise compilation fails
@setEvalBranchQuota(2000);
comptime var buffer = std.mem.zeroes([3]u8);
_ = std.fmt.formatIntBuf(buffer[0..], n, 10, .lower, std.fmt.FormatOptions{});
// Can I return function directly?
return struct {
pub fn f() callconv(.Naked) noreturn {
// Clear direction flag
asm volatile ("cld");
// Push fake error code
if (comptime !has_error_code(n)) {
asm volatile ("push $0");
}
// Push interrupt number
asm volatile (".byte 0x6a");
switch (n) {
0 => asm volatile (".byte 0x0"),
1 => asm volatile (".byte 0x1"),
2 => asm volatile (".byte 0x2"),
3 => asm volatile (".byte 0x3"),
4 => asm volatile (".byte 0x4"),
5 => asm volatile (".byte 0x5"),
6 => asm volatile (".byte 0x6"),
7 => asm volatile (".byte 0x7"),
8 => asm volatile (".byte 0x8"),
9 => asm volatile (".byte 0x9"),
10 => asm volatile (".byte 0xa"),
11 => asm volatile (".byte 0xb"),
12 => asm volatile (".byte 0xc"),
13 => asm volatile (".byte 0xd"),
14 => asm volatile (".byte 0xe"),
15 => asm volatile (".byte 0xf"),
16 => asm volatile (".byte 0x10"),
17 => asm volatile (".byte 0x11"),
18 => asm volatile (".byte 0x12"),
19 => asm volatile (".byte 0x13"),
20 => asm volatile (".byte 0x14"),
21 => asm volatile (".byte 0x15"),
22 => asm volatile (".byte 0x16"),
23 => asm volatile (".byte 0x17"),
24 => asm volatile (".byte 0x18"),
25 => asm volatile (".byte 0x19"),
26 => asm volatile (".byte 0x1a"),
27 => asm volatile (".byte 0x1b"),
28 => asm volatile (".byte 0x1c"),
29 => asm volatile (".byte 0x1d"),
30 => asm volatile (".byte 0x1e"),
31 => asm volatile (".byte 0x1f"),
32 => asm volatile (".byte 0x20"),
else => asm volatile (".byte 0x0"),
}
// Call common interrupt entry
asm volatile ("call common_entry");
// Pop interrupt number and maybe error code
asm volatile ("add $0x10, %%rsp");
// Return from interrupt
asm volatile ("iretq");
unreachable;
}
}.f;
}
comptime {
asm (
\\.global common_entry;
\\.type common_entry, @function;
\\ common_entry:
\\ push %rax
\\ push %rcx
\\ push %rdx
\\ push %rdi
\\ push %rsi
\\ push %r8
\\ push %r9
\\ push %r10
\\ push %r11
\\ // Stack layout:
\\ // [interrupt frame]
\\ // [error code]
\\ // [interrupt number]
\\ // [return address to stub]
\\ // [saved rax]
\\ // [saved rcx]
\\ // [saved rdx]
\\ // [saved rdi]
\\ // [saved rsi]
\\ // [saved r8]
\\ // [saved r9]
\\ // [saved r10]
\\ // [saved r11] <- rsp
\\ xor %edi, %edi
\\ movb 80(%rsp), %dil // load u8 interrupt number
\\ movl 88(%rsp), %esi // load error code
\\ lea 96(%rsp), %rdx
\\ call hello_handler
\\ pop %r11
\\ pop %r10
\\ pop %r9
\\ pop %r8
\\ pop %rsi
\\ pop %rdi
\\ pop %rdx
\\ pop %rcx
\\ pop %rax
\\ ret
);
}
fn keyboard_echo() void {
const scancode = @intToEnum(keyboard.Scancode, in(u8, 0x60));
if (scancode.to_ascii()) |c| {
switch (c) {
else => {},
}
}
pic.Master.send_eoi();
}
export fn hello_handler(interrupt_num: u8, error_code: u64, frame: *InterruptFrame) callconv(.C) void {
_ = error_code;
switch (interrupt_num) {
@enumToInt(CpuException.Breakpoint) => {
logger.log("BREAKPOINT\n", .{});
logger.log("======================\n", .{});
logger.log("{x}\n", .{frame});
logger.log("======================\n", .{});
},
0x31 => {
logger.log("{x}\n", .{frame});
keyboard_echo();
},
@enumToInt(CpuException.GeneralProtectionFault) => {
@panic("General Protection Fault");
},
@enumToInt(CpuException.PageFault) => {
logger.log("#PF at {x}!\n", .{CR2.read()});
hang();
},
else => {
const ex = @intToEnum(CpuException, interrupt_num);
logger.log("Received unknown interrupt {}\n", .{ex});
logger.log("{x}\n", .{frame});
hang();
},
}
}
const exception_stubs = init: {
@setEvalBranchQuota(100000);
var stubs: [256]InterruptStub = undefined;
for (stubs) |*pt, i| {
pt.* = exception_stub(i);
}
break :init stubs;
};
pub fn switch_task(from: *kernel.task.Task, to: *kernel.task.Task) void {
main_tss.rsp[0] = @ptrToInt(to.stack.ptr) + to.stack.len;
asm_switch_task(&from.regs, &to.regs);
}
fn syscall_entry() callconv(.Naked) void {
comptime {
std.debug.assert(@offsetOf(kernel.task.Task, "regs") == 0);
std.debug.assert(@offsetOf(TaskRegs, "stack_bottom") == 8);
}
asm volatile (
\\ // Switch to kernel GS
\\ swapgs
\\ // Save userspace stack
\\ mov %%rsp, %%gs:0x8
\\ // Load kernel stack from task
\\ mov %%gs:0x0, %%rsp // rsp == *CoreBlock
\\ mov 0(%%rsp), %%rsp // rsp == *Task
\\ mov 8(%%rsp), %%rsp // rsp == kernel_rsp
\\ push %%rcx
\\ push %%r11
\\ call handle_syscall
\\ pop %%r11
\\ pop %%rcx
\\ // Switch to user GS
\\ swapgs
\\ // Go back to userspace
\\ sysretq
);
}
comptime {
asm (
\\.global handle_syscall;
\\.type handle_syscall, @function;
);
}
export fn handle_syscall() callconv(.C) u64 {
kernel.syscall.syscall_dispatch();
return 0;
}
pub fn exit_to_userspace(rip: u64, rsp: u64) noreturn {
const flags: u64 = 0;
asm volatile (
\\ swapgs
\\ sysretq
:
: [rip] "{rcx}" (rip),
[rsp] "{rsp}" (rsp),
[flags] "{r11}" (flags),
);
unreachable;
}
fn setup_syscall() void {
if (!syscall_supported()) {
@panic("Syscall not supported");
}
EFER.write(EFER.read() | 1);
main_tss.rsp[0] = @ptrToInt(&stack[0]) + stack.len;
// Setup sysret instruction
// Stack segment — IA32_STAR[63:48] + 8.
// Target code segment — Reads a non-NULL selector from IA32_STAR[63:48] + 16.
const sysret_selector = @as(u64, user_base.raw);
const syscall_selector = @as(u64, null_entry.raw);
IA32_STAR.write((sysret_selector << 48) | (syscall_selector << 32));
IA32_LSTAR.write(@ptrToInt(syscall_entry));
}
pub var null_entry: gdt.SegmentSelector = undefined;
pub var kernel_code: gdt.SegmentSelector = undefined;
pub var kernel_data: gdt.SegmentSelector = undefined;
pub var user_base: gdt.SegmentSelector = undefined;
pub var user_code: gdt.SegmentSelector = undefined;
pub var user_data: gdt.SegmentSelector = undefined;
pub fn init_cpu() !void {
cpu_phys_bits = get_maxphyaddr();
const Entry = GDT.Entry;
null_entry = main_gdt.add_entry(Entry.nil);
// kernel data must be just after code - required by syscall instruction
kernel_data = main_gdt.add_entry(Entry.KernelData);
kernel_code = main_gdt.add_entry(Entry.KernelCode);
// user data must be just user code - required by syscall instruction
user_base = main_gdt.add_entry(Entry.nil);
user_data = main_gdt.add_entry(Entry.UserData);
user_code = main_gdt.add_entry(Entry.UserCode);
// Kinda ugly, refactor this
logger.log("TSS is at {*}\n", .{&main_tss});
const tss_base = main_gdt.add_entry(Entry.TaskState(&main_tss)[0]);
_ = main_gdt.add_entry(Entry.TaskState(&main_tss)[1]);
main_gdt.load();
set_ds(null_entry.raw);
set_es(null_entry.raw);
set_fs(null_entry.raw);
set_gs(null_entry.raw);
set_ss(kernel_data.raw);
main_gdt.reload_cs(kernel_code);
ltr(tss_base.raw);
for (exception_stubs) |ptr, i| {
const addr: u64 = @ptrToInt(ptr);
const dpl: u2 = if (i == 3) 3 else 0;
main_idt.set_entry(@intCast(u16, i), IDT.Entry.new(addr, kernel_code, 0, dpl));
}
main_idt.load();
GSBASE.write(@ptrToInt(&boot_cpu_gsstruct));
setup_syscall();
//pic.remap(0x30, 0x38);
//// enable only keyboard interrupt
//pic.Master.data_write(0xfd);
//pic.Slave.data_write(0xff);
}
pub fn init() void {
framebuffer.init();
trampoline.init();
acpi.init();
apic.init();
pci.init();
smp.init();
} | kernel/arch/x86.zig |
const std = @import("std");
const opt = @import("opt.zig");
const warn = std.debug.warn;
const Allocator = std.mem.Allocator;
const stdout = &std.io.getStdOut().outStream();
/// Print uniq adjacent lines... no flags yet
pub fn uniq(file: std.fs.File, options: PrintOptions) !void {
// read first line of input
var old_line: []u8 = get_line(std.heap.page_allocator, file) catch |err| {
if (err == error.EndOfStream) {
return;
}
return err;
};
var line: []u8 = undefined;
var matched: u32 = 0;
// Read until EOF
while (true) {
// read input & break if end of file
line = get_line(std.heap.page_allocator, file) catch |err| {
if (err == error.EndOfStream) break;
return err;
};
// if not equal check if should print
if (!std.mem.eql(u8, old_line, line)) {
switch (options) {
.Duplicate => if (matched > 0) warn("{}\n", .{old_line}),
.Unique => if (matched == 0) warn("{}\n", .{old_line}),
.Count => warn("{:>4} {}\n", .{ matched + 1, old_line }),
else => warn("{}\n", .{old_line}),
}
matched = 0;
} else {
// Save matched till last line of match & then try to print
matched += 1;
}
// free memory for lines we no longer need
std.heap.page_allocator.free(old_line);
old_line = line;
}
switch (options) {
.Duplicate => if (matched > 0) warn("{}\n", .{old_line}),
.Unique => if (matched == 0) warn("{}\n", .{old_line}),
.Count => warn("{:>4} {}\n", .{ matched + 1, old_line }),
else => warn("{}\n", .{old_line}),
}
std.heap.page_allocator.free(old_line);
}
/// Get a single line of file -- needs to be freed bor
pub fn get_line(allocator: *Allocator, file: std.fs.File) ![]u8 {
var char: u8 = undefined;
var stream = std.fs.File.inStream(file);
var i: u64 = 0;
char = try stream.readByte(); // err if no stream
var buffer: []u8 = try allocator.alloc(u8, 0);
while (char != -1) : (char = stream.readByte() catch {
return buffer;
}) {
if (char == '\n') break;
buffer = try allocator.realloc(buffer, i + 1);
buffer[i] = char;
i += 1;
}
return buffer;
}
const UniqFlags = enum {
Help,
Version,
OnlyUnique,
OnlyDuplicate,
OnlyCount,
};
var flags = [_]opt.Flag(UniqFlags){
.{
.name = UniqFlags.Help,
.long = "help",
},
.{
.name = UniqFlags.Version,
.long = "version",
},
.{
.name = UniqFlags.OnlyUnique,
.short = 'u',
},
.{
.name = UniqFlags.OnlyDuplicate,
.short = 'd',
},
.{
.name = UniqFlags.OnlyCount,
.short = 'c',
},
};
const PrintOptions = enum {
Unique,
Duplicate,
Count,
Default,
};
pub fn main(args: [][]u8) anyerror!u8 {
var options: PrintOptions = PrintOptions.Default;
var it = opt.FlagIterator(UniqFlags).init(flags[0..], args);
while (it.next_flag() catch {
return 1;
}) |flag| {
switch (flag.name) {
UniqFlags.Help => {
warn("{} [-c | -d | -u ] [FILE_NAME]\n", .{args[0]});
return 0;
},
UniqFlags.Version => {
warn("TODO", .{});
return 0;
},
UniqFlags.OnlyUnique => {
options = PrintOptions.Unique;
},
UniqFlags.OnlyDuplicate => {
options = PrintOptions.Duplicate;
},
UniqFlags.OnlyCount => {
options = PrintOptions.Count;
},
}
}
var input = it.next_arg();
if (input) |name| {
const file = std.fs.cwd().openFile(name[0..], std.fs.File.OpenFlags{ .read = true, .write = false }) catch |err| {
try stdout.print("Error: cannot open file {}\n", .{name});
return 1;
};
try uniq(file, options);
file.close();
} else {
// stdin
try uniq(std.io.getStdIn(), options);
}
return 0;
} | src/uniq.zig |
const std = @import("std");
const stdin = std.io.getStdIn().reader();
const stdout = std.io.getStdOut().writer();
fn readInto(arr: []bit, off: usize) !bool {
var buf: [1000]u8 = undefined;
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |line| {
for (line) |c, i| {
arr[i + off] = if (c == '.') 0 else 1;
}
return true;
}
return false;
}
fn ignoreLine() !void {
var buf: [1000]u8 = undefined;
if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |line| {}
}
const N: usize = 210; // > 2 * it + width
const bit = i8;
var conv: [1 << 9]bit = undefined;
var mat: [N][N]bit = undefined;
var tmp: [N][N]bit = undefined;
var boundary: bit = 0;
fn at(i: usize, j: usize) bit {
if (i < 0 or i >= N or j < 0 or j >= N)
return boundary;
return mat[i][j];
}
fn enhanceAt(i: usize, j: usize) bit {
if (i == 0 or i == N - 1 or j == 0 or j == N - 1)
return boundary;
var ix: usize = 0;
for ([_]usize{ i - 1, i, i + 1 }) |ii| {
for ([_]usize{ j - 1, j, j + 1 }) |jj| {
ix <<= 1;
var cur = at(ii, jj);
if (cur == 1) ix += 1;
}
}
return conv[ix];
}
fn enhance() void {
if (boundary == 0) {
boundary = conv[0];
} else {
boundary = conv[511];
}
for (mat) |row, i| {
for (row) |cell, j| {
tmp[i][j] = enhanceAt(i, j);
}
}
mat = tmp;
}
fn enhanceN(n: u32) void {
var i: u32 = 0;
while (i < n) : (i += 1) enhance();
}
fn countLit() i32 {
var res: i32 = 0;
for (mat) |row| {
for (row) |cell| res += cell;
}
return res;
}
pub fn main() !void {
if (try readInto(&conv, 0)) {}
try ignoreLine();
const off: usize = 51;
var i: usize = off;
while (try readInto(&mat[i], off)) : (i += 1) {}
// part 1
enhanceN(2);
try stdout.print("{}\n", .{countLit()});
// part 2
enhanceN(48);
try stdout.print("{}\n", .{countLit()});
} | day20.zig |
const std = @import("std");
const Builder = std.build.Builder;
const Pkg = std.build.Pkg;
fn addIupReference(step: *std.build.LibExeObjStep) !void {
if (step.target.isWindows()) {
// workarround, forcing MSVC ABI
step.target.abi = .msvc;
step.linkSystemLibrary("Gdi32");
step.linkSystemLibrary("User32");
step.linkSystemLibrary("Shell32");
step.linkSystemLibrary("Comctl32");
step.linkSystemLibrary("Comdlg32");
step.linkSystemLibrary("Ole32");
step.linkSystemLibrary("Advapi32");
// Workarround for
// #9002 Find native include and libraries is broken with msvc ABI
// https://github.com/ziglang/zig/issues/9002
step.addLibPath("lib/uwp");
step.addLibPath("lib/um");
step.addLibPath("lib/ucrt");
step.addLibPath("C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\Community\\VC\\Tools\\MSVC\\14.16.27023\\lib\\x64");
// Link againts .lib files
step.addLibPath("lib/win64");
step.linkSystemLibrary("iupfiledlg");
step.linkSystemLibrary("iupole");
step.linkSystemLibrary("iupgl");
step.linkSystemLibrary("zlib1");
}
// Please visit IUP's download page for your platform
// https://sourceforge.net/projects/iup/files/3.30/
//
// Dependencies for libim and libcd also required
// https://sourceforge.net/projects/imtoolkit/files/3.15/
// https://sourceforge.net/projects/canvasdraw/files/5.14/
step.linkSystemLibrary("ftgl");
step.linkSystemLibrary("iupcd");
step.linkSystemLibrary("iupgl");
step.linkSystemLibrary("iup_mglplot");
step.linkSystemLibrary("iup");
step.linkSystemLibrary("iupcontrols");
step.linkSystemLibrary("iupimglib");
step.linkSystemLibrary("iup_plot");
step.linkSystemLibrary("iuptuio");
step.linkSystemLibrary("iupglcontrols");
step.linkSystemLibrary("iupim");
step.linkSystemLibrary("iup_scintilla");
step.linkSystemLibrary("iupweb");
// Includes .h
step.addIncludeDir("lib/include");
}
pub fn build(b: *Builder) !void {
const mode = b.standardReleaseOptions();
const lib = b.addStaticLibrary("ziup", "src/iup.zig");
lib.setBuildMode(mode);
lib.linkLibC();
try addIupReference(lib);
lib.install();
var main_tests = b.addTest("src/iup.zig");
main_tests.setBuildMode(mode);
main_tests.linkLibC();
try addIupReference(main_tests);
const test_step = b.step("test", "Run library tests");
test_step.dependOn(&main_tests.step);
addExample(b, "run", "src/notepad_example.zig");
addExample(b, "tabs", "src/tabs_example.zig");
addExample(b, "button", "src/button_example.zig");
addExample(b, "image", "src/image_example.zig");
addExample(b, "list", "src/list_example.zig");
addExample(b, "tree", "src/tree_example.zig");
addExample(b, "mdi", "src/mdi_example.zig");
addExample(b, "gauge", "src/gauge_example.zig");
}
fn addExample(b: *Builder, comptime name: []const u8, comptime file: []const u8) void {
const mode = b.standardReleaseOptions();
const example = b.addExecutable(name, file);
example.setBuildMode(mode);
example.linkLibC();
try addIupReference(example);
example.install();
const example_cmd = example.run();
example_cmd.step.dependOn(b.getInstallStep());
const example_step = b.step(name, "Example: " ++ name);
example_step.dependOn(&example_cmd.step);
} | build.zig |
const std = @import("std");
const upaya = @import("upaya");
usingnamespace upaya.imgui;
pub fn main() !void {
upaya.run(.{
.init = init,
.update = update,
.setupDockLayout = setupDockLayout,
.docking = true,
});
}
fn init() void {}
fn update() void {
// note: the MenuItems do not automatically bind to keys. The shortcut field is just for the UI. You can add listeners for the key combos
// like this:
const io = igGetIO();
if ((io.KeyCtrl or io.KeySuper) and ogKeyPressed(upaya.sokol.SAPP_KEYCODE_S)) {
onSave();
}
upaya.menu.draw(&[_]upaya.MenuItem{ .{
.label = "File",
.children = &[_]upaya.MenuItem{
.{ .label = "New", .shortcut = "cmd+n" },
.{ .label = "Save", .shortcut = "cmd+s", .action = onSave },
},
}, .{
.label = "Edit",
.children = &[_]upaya.MenuItem{
.{ .label = "Copy", .shortcut = "cmd+c" },
.{ .label = "Paste", .shortcut = "cmd+v" },
},
} });
_ = igBegin("Properties", null, ImGuiWindowFlags_None);
ogAddRectFilled(igGetWindowDrawList(), ogGetCursorScreenPos(), ogGetContentRegionAvail(), upaya.colors.rgbToU32(255, 0, 0));
igEnd();
_ = igBegin("Top Left", null, ImGuiWindowFlags_None);
ogAddRectFilled(igGetWindowDrawList(), ogGetCursorScreenPos(), ogGetContentRegionAvail(), upaya.colors.rgbToU32(0, 0, 255));
igEnd();
_ = igBegin("Bottom Left 1", null, ImGuiWindowFlags_None);
ogAddRectFilled(igGetWindowDrawList(), ogGetCursorScreenPos(), ogGetContentRegionAvail(), upaya.colors.rgbToU32(0, 255, 0));
igEnd();
_ = igBegin("Bottom Left 2", null, ImGuiWindowFlags_None);
ogAddRectFilled(igGetWindowDrawList(), ogGetCursorScreenPos(), ogGetContentRegionAvail(), upaya.colors.rgbToU32(100, 100, 100));
igEnd();
igSetNextWindowSize(.{ .x = 100, .y = 75 }, ImGuiCond_FirstUseEver);
_ = igBegin("Floating", null, ImGuiWindowFlags_None);
igEnd();
}
fn onSave() void {
var file = upaya.filebrowser.saveFileDialog("Save File", "", "*.txt");
if (file != null) {
std.debug.print("save file: {s}\n", .{file});
}
}
fn setupDockLayout(id: ImGuiID) void {
var dock_main_id = id;
// dock_main_id is the left node after this
const right_id = igDockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.35, null, &dock_main_id);
igDockBuilderDockWindow("Properties", right_id);
// dock_main_id is the bottom node after this
const tl_id = igDockBuilderSplitNode(dock_main_id, ImGuiDir_Up, 0.48, null, &dock_main_id);
igDockBuilderDockWindow("Top Left", tl_id);
igDockBuilderDockWindow("Bottom Left 1", dock_main_id);
igDockBuilderDockWindow("Bottom Left 2", dock_main_id);
igDockBuilderFinish(id);
} | examples/docking.zig |
const std = @import("std");
const Source = @This();
pub const Id = enum(u32) {
unused = 0,
generated = 1,
_,
};
pub const Location = struct {
id: Id = .unused,
byte_offset: u32 = 0,
line: u32 = 0,
pub fn eql(a: Location, b: Location) bool {
return a.id == b.id and a.byte_offset == b.byte_offset and a.line == b.line;
}
};
path: []const u8,
buf: []const u8,
id: Id,
invalid_utf8_loc: ?Location = null,
const LineCol = struct { line: []const u8, col: u32, width: u32 };
pub fn lineCol(source: Source, byte_offset: u32) LineCol {
var start: usize = 0;
if (std.mem.lastIndexOfScalar(u8, source.buf[0..byte_offset], '\n')) |some| start = some + 1;
var i: usize = start;
var col: u32 = 1;
var width: u32 = 0;
while (i < byte_offset) : (col += 1) { // TODO this is still incorrect, but better
const len = std.unicode.utf8ByteSequenceLength(source.buf[i]) catch unreachable;
const cp = std.unicode.utf8Decode(source.buf[i..][0..len]) catch unreachable;
width += codepointWidth(cp);
i += len;
}
return .{ .line = std.mem.sliceTo(source.buf[start..], '\n'), .col = col, .width = width };
}
fn codepointWidth(cp: u32) u32 {
return switch (cp) {
0x1100...0x115F,
0x2329,
0x232A,
0x2E80...0x303F,
0x3040...0x3247,
0x3250...0x4DBF,
0x4E00...0xA4C6,
0xA960...0xA97C,
0xAC00...0xD7A3,
0xF900...0xFAFF,
0xFE10...0xFE19,
0xFE30...0xFE6B,
0xFF01...0xFF60,
0xFFE0...0xFFE6,
0x1B000...0x1B001,
0x1F200...0x1F251,
0x20000...0x3FFFD,
0x1F300...0x1F5FF,
0x1F900...0x1F9FF,
=> 2,
else => 1,
};
}
/// Returns the first offset, if any, in buf where an invalid utf8 sequence
/// is found. Code adapted from std.unicode.utf8ValidateSlice
fn offsetOfInvalidUtf8(buf: []const u8) ?u32 {
std.debug.assert(buf.len <= std.math.maxInt(u32));
var i: u32 = 0;
while (i < buf.len) {
if (std.unicode.utf8ByteSequenceLength(buf[i])) |cp_len| {
if (i + cp_len > buf.len) return i;
if (std.meta.isError(std.unicode.utf8Decode(buf[i .. i + cp_len]))) return i;
i += cp_len;
} else |_| return i;
}
return null;
}
pub fn checkUtf8(source: *Source) void {
if (offsetOfInvalidUtf8(source.buf)) |offset| {
source.invalid_utf8_loc = Location{ .id = source.id, .byte_offset = offset };
}
} | src/Source.zig |
const std = @import("std");
const ds = @import("ds.zig");
// Stores allocator with data ptr.
pub fn Box(comptime T: type) type {
if (@typeInfo(T) == .Pointer and @typeInfo(T).Pointer.size == .Slice) {
return BoxSlice(T);
} else if (@typeInfo(T) == .Struct) {
return BoxPtr(T);
}
@compileError("not supported");
}
fn BoxSlice(comptime T: type) type {
return struct {
const Self = @This();
slice: T,
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator, slice: T) Self {
return .{
.alloc = alloc,
.slice = slice,
};
}
pub fn deinit(self: *const Self) void {
self.alloc.free(self.slice);
}
};
}
fn BoxPtr(comptime T: type) type {
return struct {
const Self = @This();
ptr: *T,
alloc: std.mem.Allocator,
pub fn init(alloc: std.mem.Allocator, ptr: *T) Self {
return .{
.alloc = alloc,
.ptr = ptr,
};
}
pub fn create(alloc: std.mem.Allocator) !Self {
return Self{
.alloc = alloc,
.ptr = try alloc.create(T),
};
}
pub fn createInit(alloc: std.mem.Allocator, _init: T) !Self {
const new = Self{
.alloc = alloc,
.ptr = try alloc.create(T),
};
new.ptr.* = _init;
return new;
}
pub fn deinit(self: *Self) void {
// Contained item deinit is called if it exists.
if (@hasDecl(T, "deinit")) {
self.ptr.deinit();
}
self.alloc.destroy(self.ptr);
}
pub fn deinitOuter(self: *Self) void {
self.alloc.destroy(self.ptr);
}
pub fn toSized(self: Self) SizedBox {
return .{
.ptr = ds.Opaque.fromPtr(*T, self.ptr),
.size = @sizeOf(T),
.alloc = self.alloc,
};
}
};
}
pub const SizedBox = struct {
const Self = @This();
ptr: *ds.Opaque,
alloc: std.mem.Allocator,
size: u32,
pub fn deinit(self: *const Self) void {
const slice = ds.Opaque.toPtr([*]u8, self.ptr)[0..self.size];
self.alloc.free(slice);
}
}; | stdx/ds/box.zig |
const std = @import("std");
const stdx = @import("stdx");
const graphics = @import("../../graphics.zig");
const gpu = graphics.gpu;
const OpenTypeFont = graphics.OpenTypeFont;
const Glyph = gpu.Glyph;
const FontId = graphics.FontId;
const VMetrics = graphics.VMetrics;
const log = std.log.scoped(.font);
// Represents a font rendered at a specific bitmap font size.
pub const RenderFont = struct {
const Self = @This();
font_id: FontId,
// The font size of the underlying bitmap data.
render_font_size: u16,
glyphs: std.AutoHashMap(u21, Glyph),
// Special missing glyph, every font should have this. glyph_id = 0.
missing_glyph: ?Glyph,
// From design units to px. Calculated with render_font_size.
scale_from_ttf: f32,
// max distance above baseline (positive px)
ascent: f32,
// max distance below baseline (negative px)
descent: f32,
// gap between the previous row's decent and current row's ascent.
line_gap: f32,
// should just be ascent + descent amounts.
font_height: f32,
pub fn initOutline(self: *Self, alloc: std.mem.Allocator, font_id: FontId, ot_font: OpenTypeFont, render_font_size: u16) void {
const scale = ot_font.getScaleToUserFontSize(@intToFloat(f32, render_font_size));
const v_metrics = ot_font.getVerticalMetrics();
const s_ascent = scale * @intToFloat(f32, v_metrics.ascender);
const s_descent = scale * @intToFloat(f32, v_metrics.descender);
const s_line_gap = scale * @intToFloat(f32, v_metrics.line_gap);
self.* = .{
.font_id = font_id,
.render_font_size = render_font_size,
.scale_from_ttf = scale,
.ascent = s_ascent,
.descent = s_descent,
.line_gap = s_line_gap,
.font_height = s_ascent - s_descent,
.glyphs = std.AutoHashMap(u21, Glyph).init(alloc),
.missing_glyph = null,
};
// Start with enough memory for ascii codepoints.
self.glyphs.ensureTotalCapacity(256) catch unreachable;
}
pub fn initBitmap(self: *Self, alloc: std.mem.Allocator, font_id: FontId, ot_font: OpenTypeFont, render_font_size: u16) void {
const v_metrics = ot_font.getBitmapVerticalMetrics();
self.* = .{
.font_id = font_id,
.render_font_size = render_font_size,
.scale_from_ttf = 1,
.ascent = @intToFloat(f32, v_metrics.ascender),
.descent = @intToFloat(f32, v_metrics.descender),
.line_gap = @intToFloat(f32, v_metrics.line_gap),
.font_height = @intToFloat(f32, v_metrics.ascender - v_metrics.descender),
.glyphs = std.AutoHashMap(u21, Glyph).init(alloc),
.missing_glyph = null,
};
// Start with enough memory for ascii codepoints.
self.glyphs.ensureTotalCapacity(256) catch unreachable;
}
pub fn deinit(self: *Self) void {
self.glyphs.deinit();
}
pub fn getScaleToUserFontSize(self: *const Self, size: f32) f32 {
return size / @intToFloat(f32, self.render_font_size);
}
pub fn getVerticalMetrics(self: *Self, font_size: f32) VMetrics {
const scale = font_size / @intToFloat(f32, self.render_font_size);
const ascender = self.ascent * scale;
const descender = self.descent * scale;
return .{
.ascender = ascender,
.descender = descender,
.line_gap = self.line_gap * scale,
// subtract descender since it's negative
.height = ascender - descender,
};
}
}; | graphics/src/backend/gpu/render_font.zig |
pub const ENCLAVE_RUNTIME_POLICY_ALLOW_FULL_DEBUG = @as(u32, 1);
pub const ENCLAVE_RUNTIME_POLICY_ALLOW_DYNAMIC_DEBUG = @as(u32, 2);
pub const ENCLAVE_UNSEAL_FLAG_STALE_KEY = @as(u32, 1);
pub const ENCLAVE_FLAG_FULL_DEBUG_ENABLED = @as(u32, 1);
pub const ENCLAVE_FLAG_DYNAMIC_DEBUG_ENABLED = @as(u32, 2);
pub const ENCLAVE_FLAG_DYNAMIC_DEBUG_ACTIVE = @as(u32, 4);
pub const VBS_ENCLAVE_REPORT_PKG_HEADER_VERSION_CURRENT = @as(u32, 1);
pub const VBS_ENCLAVE_REPORT_SIGNATURE_SCHEME_SHA256_RSA_PSS_SHA256 = @as(u32, 1);
pub const VBS_ENCLAVE_REPORT_VERSION_CURRENT = @as(u32, 1);
pub const ENCLAVE_REPORT_DATA_LENGTH = @as(u32, 64);
pub const VBS_ENCLAVE_VARDATA_INVALID = @as(u32, 0);
pub const VBS_ENCLAVE_VARDATA_MODULE = @as(u32, 1);
pub const ENCLAVE_VBS_BASIC_KEY_FLAG_MEASUREMENT = @as(u32, 1);
pub const ENCLAVE_VBS_BASIC_KEY_FLAG_FAMILY_ID = @as(u32, 2);
pub const ENCLAVE_VBS_BASIC_KEY_FLAG_IMAGE_ID = @as(u32, 4);
pub const ENCLAVE_VBS_BASIC_KEY_FLAG_DEBUG_KEY = @as(u32, 8);
//--------------------------------------------------------------------------------
// Section: Types (29)
//--------------------------------------------------------------------------------
pub const ENCLAVE_SEALING_IDENTITY_POLICY = enum(i32) {
INVALID = 0,
EXACT_CODE = 1,
SAME_PRIMARY_CODE = 2,
SAME_IMAGE = 3,
SAME_FAMILY = 4,
SAME_AUTHOR = 5,
};
pub const ENCLAVE_IDENTITY_POLICY_SEAL_INVALID = ENCLAVE_SEALING_IDENTITY_POLICY.INVALID;
pub const ENCLAVE_IDENTITY_POLICY_SEAL_EXACT_CODE = ENCLAVE_SEALING_IDENTITY_POLICY.EXACT_CODE;
pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_PRIMARY_CODE = ENCLAVE_SEALING_IDENTITY_POLICY.SAME_PRIMARY_CODE;
pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_IMAGE = ENCLAVE_SEALING_IDENTITY_POLICY.SAME_IMAGE;
pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_FAMILY = ENCLAVE_SEALING_IDENTITY_POLICY.SAME_FAMILY;
pub const ENCLAVE_IDENTITY_POLICY_SEAL_SAME_AUTHOR = ENCLAVE_SEALING_IDENTITY_POLICY.SAME_AUTHOR;
pub const ENCLAVE_IDENTITY = packed struct {
OwnerId: [32]u8,
UniqueId: [32]u8,
AuthorId: [32]u8,
FamilyId: [16]u8,
ImageId: [16]u8,
EnclaveSvn: u32,
SecureKernelSvn: u32,
PlatformSvn: u32,
Flags: u32,
SigningLevel: u32,
EnclaveType: u32,
};
pub const VBS_ENCLAVE_REPORT_PKG_HEADER = packed struct {
PackageSize: u32,
Version: u32,
SignatureScheme: u32,
SignedStatementSize: u32,
SignatureSize: u32,
Reserved: u32,
};
pub const VBS_ENCLAVE_REPORT = packed struct {
ReportSize: u32,
ReportVersion: u32,
EnclaveData: [64]u8,
EnclaveIdentity: ENCLAVE_IDENTITY,
};
pub const VBS_ENCLAVE_REPORT_VARDATA_HEADER = packed struct {
DataType: u32,
Size: u32,
};
pub const VBS_ENCLAVE_REPORT_MODULE = packed struct {
Header: VBS_ENCLAVE_REPORT_VARDATA_HEADER,
UniqueId: [32]u8,
AuthorId: [32]u8,
FamilyId: [16]u8,
ImageId: [16]u8,
Svn: u32,
ModuleName: [1]u16,
};
pub const ENCLAVE_INFORMATION = extern struct {
EnclaveType: u32,
Reserved: u32,
BaseAddress: ?*anyopaque,
Size: usize,
Identity: ENCLAVE_IDENTITY,
};
pub const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32 = extern struct {
ThreadContext: [4]u32,
EntryPoint: u32,
StackPointer: u32,
ExceptionEntryPoint: u32,
ExceptionStack: u32,
ExceptionActive: u32,
};
pub const VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64 = extern struct {
ThreadContext: [4]u64,
EntryPoint: u64,
StackPointer: u64,
ExceptionEntryPoint: u64,
ExceptionStack: u64,
ExceptionActive: u32,
};
pub const VBS_BASIC_ENCLAVE_EXCEPTION_AMD64 = extern struct {
ExceptionCode: u32,
NumberParameters: u32,
ExceptionInformation: [3]usize,
ExceptionRAX: usize,
ExceptionRCX: usize,
ExceptionRIP: usize,
ExceptionRFLAGS: usize,
ExceptionRSP: usize,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE = fn(
ReturnValue: usize,
) callconv(@import("std").os.windows.WINAPI) void;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES = fn(
EnclaveAddress: ?*anyopaque,
NumberOfBytes: usize,
SourceAddress: ?*anyopaque,
PageProtection: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES = fn(
EnclaveAddress: ?*anyopaque,
NumberOfBytes: usize,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES = fn(
EnclaveAddress: ?*anyopaque,
NumberOfytes: usize,
PageProtection: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION = fn(
EnclaveInfo: ?*ENCLAVE_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const ENCLAVE_VBS_BASIC_KEY_REQUEST = extern struct {
RequestSize: u32,
Flags: u32,
EnclaveSVN: u32,
SystemKeyID: u32,
CurrentSystemKeyID: u32,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY = fn(
KeyRequest: ?*ENCLAVE_VBS_BASIC_KEY_REQUEST,
RequestedKeySize: u32,
ReturnedKey: [*:0]u8,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT = fn(
EnclaveData: ?*const u8,
// TODO: what to do with BytesParamIndex 2?
Report: ?*anyopaque,
BufferSize: u32,
OutputSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT = fn(
// TODO: what to do with BytesParamIndex 1?
Report: ?*const anyopaque,
ReportSize: u32,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA = fn(
// TODO: what to do with BytesParamIndex 1?
Buffer: ?*u8,
NumberOfBytes: u32,
Generation: ?*u64,
) callconv(@import("std").os.windows.WINAPI) i32;
pub const VBS_BASIC_ENCLAVE_SYSCALL_PAGE = extern struct {
ReturnFromEnclave: ?VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE,
ReturnFromException: ?VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION,
TerminateThread: ?VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD,
InterruptThread: ?VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD,
CommitPages: ?VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES,
DecommitPages: ?VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES,
ProtectPages: ?VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES,
CreateThread: ?VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD,
GetEnclaveInformation: ?VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION,
GenerateKey: ?VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY,
GenerateReport: ?VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT,
VerifyReport: ?VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT,
GenerateRandomData: ?VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION = switch(@import("../zig.zig").arch) {
.X64 => fn(
ExceptionRecord: ?*VBS_BASIC_ENCLAVE_EXCEPTION_AMD64,
) callconv(@import("std").os.windows.WINAPI) i32,
.X86, .Arm64 => fn(
ExceptionRecord: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) i32,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64,
) callconv(@import("std").os.windows.WINAPI) i32,
.X86 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32,
) callconv(@import("std").os.windows.WINAPI) i32,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64,
) callconv(@import("std").os.windows.WINAPI) i32,
.X86 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32,
) callconv(@import("std").os.windows.WINAPI) i32,
};
pub const VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD = switch(@import("../zig.zig").arch) {
.X64, .Arm64 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR64,
) callconv(@import("std").os.windows.WINAPI) i32,
.X86 => fn(
ThreadDescriptor: ?*VBS_BASIC_ENCLAVE_THREAD_DESCRIPTOR32,
) callconv(@import("std").os.windows.WINAPI) i32,
};
//--------------------------------------------------------------------------------
// Section: Functions (37)
//--------------------------------------------------------------------------------
pub extern "KERNEL32" fn SetEnvironmentStringsW(
NewEnvironment: ?[*]u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCommandLineA(
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetCommandLineW(
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetEnvironmentStrings(
) callconv(@import("std").os.windows.WINAPI) ?PSTR;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetEnvironmentStringsW(
) callconv(@import("std").os.windows.WINAPI) ?PWSTR;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn FreeEnvironmentStringsA(
penv: ?[*]u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn FreeEnvironmentStringsW(
penv: ?[*]u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetEnvironmentVariableA(
lpName: ?[*:0]const u8,
lpBuffer: ?[*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn GetEnvironmentVariableW(
lpName: ?[*:0]const u16,
lpBuffer: ?[*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetEnvironmentVariableA(
lpName: ?[*:0]const u8,
lpValue: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.1.2600'
pub extern "KERNEL32" fn SetEnvironmentVariableW(
lpName: ?[*:0]const u16,
lpValue: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn ExpandEnvironmentStringsA(
lpSrc: ?[*:0]const u8,
lpDst: ?[*:0]u8,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows5.0'
pub extern "KERNEL32" fn ExpandEnvironmentStringsW(
lpSrc: ?[*:0]const u16,
lpDst: ?[*:0]u16,
nSize: u32,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn SetCurrentDirectoryA(
lpPathName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn SetCurrentDirectoryW(
lpPathName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "KERNEL32" fn GetCurrentDirectoryA(
nBufferLength: u32,
lpBuffer: ?[*:0]u8,
) callconv(@import("std").os.windows.WINAPI) u32;
pub extern "KERNEL32" fn GetCurrentDirectoryW(
nBufferLength: u32,
lpBuffer: ?[*:0]u16,
) callconv(@import("std").os.windows.WINAPI) u32;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn NeedCurrentDirectoryForExePathA(
ExeName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows6.0.6000'
pub extern "KERNEL32" fn NeedCurrentDirectoryForExePathW(
ExeName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USERENV" fn CreateEnvironmentBlock(
lpEnvironment: ?*?*anyopaque,
hToken: ?HANDLE,
bInherit: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USERENV" fn DestroyEnvironmentBlock(
lpEnvironment: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USERENV" fn ExpandEnvironmentStringsForUserA(
hToken: ?HANDLE,
lpSrc: ?[*:0]const u8,
lpDest: [*:0]u8,
dwSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows5.0'
pub extern "USERENV" fn ExpandEnvironmentStringsForUserW(
hToken: ?HANDLE,
lpSrc: ?[*:0]const u16,
lpDest: [*:0]u16,
dwSize: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn IsEnclaveTypeSupported(
flEnclaveType: u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn CreateEnclave(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
dwSize: usize,
dwInitialCommitment: usize,
flEnclaveType: u32,
// TODO: what to do with BytesParamIndex 6?
lpEnclaveInformation: ?*const anyopaque,
dwInfoLength: u32,
lpEnclaveError: ?*u32,
) callconv(@import("std").os.windows.WINAPI) ?*anyopaque;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn LoadEnclaveData(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
// TODO: what to do with BytesParamIndex 3?
lpBuffer: ?*const anyopaque,
nSize: usize,
flProtect: u32,
// TODO: what to do with BytesParamIndex 6?
lpPageInformation: ?*const anyopaque,
dwInfoLength: u32,
lpNumberOfBytesWritten: ?*usize,
lpEnclaveError: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.10240'
pub extern "KERNEL32" fn InitializeEnclave(
hProcess: ?HANDLE,
lpAddress: ?*anyopaque,
// TODO: what to do with BytesParamIndex 3?
lpEnclaveInformation: ?*const anyopaque,
dwInfoLength: u32,
lpEnclaveError: ?*u32,
) callconv(@import("std").os.windows.WINAPI) BOOL;
pub extern "api-ms-win-core-enclave-l1-1-1" fn LoadEnclaveImageA(
lpEnclaveAddress: ?*anyopaque,
lpImageName: ?[*:0]const u8,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "api-ms-win-core-enclave-l1-1-1" fn LoadEnclaveImageW(
lpEnclaveAddress: ?*anyopaque,
lpImageName: ?[*:0]const u16,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn CallEnclave(
lpRoutine: isize,
lpParameter: ?*anyopaque,
fWaitForThread: BOOL,
lpReturnValue: ?*?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn TerminateEnclave(
lpAddress: ?*anyopaque,
fWait: BOOL,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "api-ms-win-core-enclave-l1-1-1" fn DeleteEnclave(
lpAddress: ?*anyopaque,
) callconv(@import("std").os.windows.WINAPI) BOOL;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn EnclaveGetAttestationReport(
EnclaveData: ?*const u8,
// TODO: what to do with BytesParamIndex 2?
Report: ?*anyopaque,
BufferSize: u32,
OutputSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn EnclaveVerifyAttestationReport(
EnclaveType: u32,
// TODO: what to do with BytesParamIndex 2?
Report: ?*const anyopaque,
ReportSize: u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn EnclaveSealData(
// TODO: what to do with BytesParamIndex 1?
DataToEncrypt: ?*const anyopaque,
DataToEncryptSize: u32,
IdentityPolicy: ENCLAVE_SEALING_IDENTITY_POLICY,
RuntimePolicy: u32,
// TODO: what to do with BytesParamIndex 5?
ProtectedBlob: ?*anyopaque,
BufferSize: u32,
ProtectedBlobSize: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn EnclaveUnsealData(
// TODO: what to do with BytesParamIndex 1?
ProtectedBlob: ?*const anyopaque,
ProtectedBlobSize: u32,
// TODO: what to do with BytesParamIndex 3?
DecryptedData: ?*anyopaque,
BufferSize: u32,
DecryptedDataSize: ?*u32,
SealingIdentity: ?*ENCLAVE_IDENTITY,
UnsealingFlags: ?*u32,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
// TODO: this type is limited to platform 'windows10.0.16299'
pub extern "vertdll" fn EnclaveGetEnclaveInformation(
InformationSize: u32,
// TODO: what to do with BytesParamIndex 0?
EnclaveInformation: ?*ENCLAVE_INFORMATION,
) callconv(@import("std").os.windows.WINAPI) HRESULT;
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (10)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../zig.zig").unicode_mode) {
.ansi => struct {
pub const GetCommandLine = thismodule.GetCommandLineA;
pub const FreeEnvironmentStrings = thismodule.FreeEnvironmentStringsA;
pub const GetEnvironmentVariable = thismodule.GetEnvironmentVariableA;
pub const SetEnvironmentVariable = thismodule.SetEnvironmentVariableA;
pub const ExpandEnvironmentStrings = thismodule.ExpandEnvironmentStringsA;
pub const SetCurrentDirectory = thismodule.SetCurrentDirectoryA;
pub const GetCurrentDirectory = thismodule.GetCurrentDirectoryA;
pub const NeedCurrentDirectoryForExePath = thismodule.NeedCurrentDirectoryForExePathA;
pub const ExpandEnvironmentStringsForUser = thismodule.ExpandEnvironmentStringsForUserA;
pub const LoadEnclaveImage = thismodule.LoadEnclaveImageA;
},
.wide => struct {
pub const GetCommandLine = thismodule.GetCommandLineW;
pub const FreeEnvironmentStrings = thismodule.FreeEnvironmentStringsW;
pub const GetEnvironmentVariable = thismodule.GetEnvironmentVariableW;
pub const SetEnvironmentVariable = thismodule.SetEnvironmentVariableW;
pub const ExpandEnvironmentStrings = thismodule.ExpandEnvironmentStringsW;
pub const SetCurrentDirectory = thismodule.SetCurrentDirectoryW;
pub const GetCurrentDirectory = thismodule.GetCurrentDirectoryW;
pub const NeedCurrentDirectoryForExePath = thismodule.NeedCurrentDirectoryForExePathW;
pub const ExpandEnvironmentStringsForUser = thismodule.ExpandEnvironmentStringsForUserW;
pub const LoadEnclaveImage = thismodule.LoadEnclaveImageW;
},
.unspecified => if (@import("builtin").is_test) struct {
pub const GetCommandLine = *opaque{};
pub const FreeEnvironmentStrings = *opaque{};
pub const GetEnvironmentVariable = *opaque{};
pub const SetEnvironmentVariable = *opaque{};
pub const ExpandEnvironmentStrings = *opaque{};
pub const SetCurrentDirectory = *opaque{};
pub const GetCurrentDirectory = *opaque{};
pub const NeedCurrentDirectoryForExePath = *opaque{};
pub const ExpandEnvironmentStringsForUser = *opaque{};
pub const LoadEnclaveImage = *opaque{};
} else struct {
pub const GetCommandLine = @compileError("'GetCommandLine' requires that UNICODE be set to true or false in the root module");
pub const FreeEnvironmentStrings = @compileError("'FreeEnvironmentStrings' requires that UNICODE be set to true or false in the root module");
pub const GetEnvironmentVariable = @compileError("'GetEnvironmentVariable' requires that UNICODE be set to true or false in the root module");
pub const SetEnvironmentVariable = @compileError("'SetEnvironmentVariable' requires that UNICODE be set to true or false in the root module");
pub const ExpandEnvironmentStrings = @compileError("'ExpandEnvironmentStrings' requires that UNICODE be set to true or false in the root module");
pub const SetCurrentDirectory = @compileError("'SetCurrentDirectory' requires that UNICODE be set to true or false in the root module");
pub const GetCurrentDirectory = @compileError("'GetCurrentDirectory' requires that UNICODE be set to true or false in the root module");
pub const NeedCurrentDirectoryForExePath = @compileError("'NeedCurrentDirectoryForExePath' requires that UNICODE be set to true or false in the root module");
pub const ExpandEnvironmentStringsForUser = @compileError("'ExpandEnvironmentStringsForUser' requires that UNICODE be set to true or false in the root module");
pub const LoadEnclaveImage = @compileError("'LoadEnclaveImage' requires that UNICODE be set to true or false in the root module");
},
};
//--------------------------------------------------------------------------------
// Section: Imports (5)
//--------------------------------------------------------------------------------
const BOOL = @import("../foundation.zig").BOOL;
const HANDLE = @import("../foundation.zig").HANDLE;
const HRESULT = @import("../foundation.zig").HRESULT;
const PSTR = @import("../foundation.zig").PSTR;
const PWSTR = @import("../foundation.zig").PWSTR;
test {
// The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_ENCLAVE; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_COMMIT_PAGES; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_DECOMMIT_PAGES; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_PROTECT_PAGES; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_GET_ENCLAVE_INFORMATION; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_KEY; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_REPORT; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_VERIFY_REPORT; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_GENERATE_RANDOM_DATA; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_RETURN_FROM_EXCEPTION; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_TERMINATE_THREAD; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_INTERRUPT_THREAD; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD; }
if (@hasDecl(@This(), "VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD")) { _ = VBS_BASIC_ENCLAVE_BASIC_CALL_CREATE_THREAD; }
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/system/environment.zig |
const std = @import("std");
const game = @import("game.zig");
const assert = std.debug.assert;
const TypeInfo = std.builtin.TypeInfo;
/// a concept-like / trait like metafunction to
/// check at compile time whether a given argument's type satisfies the
/// prng interface necessary for generating a random dice throw
fn assertIsOfPrngType(arg : anytype) void {
const prng_type = comptime switch (@typeInfo(@TypeOf(arg))) {
.Struct => @TypeOf(arg),
.Pointer => |ptr| ptr.child,
else => {@compileError("Type of PRNG must be pointer or struct");}
};
const hasFieldRandom = std.meta.trait.hasField("random");
comptime if (!hasFieldRandom(prng_type)) {
@compileError("PRNG must have member field 'random'");
};
}
/// A variant that contains a valid dice result, either
/// * a raven
/// * a basket
/// * a fruit tree with given index
pub const DiceResult = union(enum) {
raven: Raven,
basket: Basket,
fruit: Fruit,
// create a new raven dice throw
pub fn new_raven() @This() {
return @This(){ .raven = .{} };
}
// create a new basked dice throw
pub fn new_basket() @This() {
return @This(){ .basket = .{} };
}
// create a new fruit result
pub fn new_fruit(index: usize) !@This() {
return @This(){ .fruit = try Fruit.new(index) };
}
/// generate a new random dice result using a prng
/// # Arguments
/// prng: must be a random number generator which has a member
/// random and that member must have a function intRangeAtMost(comptime T:type,lower:T, upper:T)
/// which generates an integer in the range [lower, upper].
/// TODO: I am checking the type at compile time to provide better error messages,
/// but I don't know if I am doing it idiomatically.
pub fn new_random(prng : anytype) @This() {
// this is to check the arg for better error messages
assertIsOfPrngType(prng);
const rand = prng.random.intRangeAtMost(u8, 0, game.TREE_COUNT+1);
switch (rand) {
0...game.TREE_COUNT-1 => |index| return .{.fruit = Fruit.new(index) catch unreachable},
game.TREE_COUNT => return .{.basket = .{}},
game.TREE_COUNT+1 => return .{.raven = .{}},
else => unreachable,
}
}
};
pub const Raven = struct {};
pub const Basket = struct {};
pub const Fruit = struct {
index: usize,
pub fn new(index: usize) !@This() {
if (index < game.TREE_COUNT) {
return Fruit{ .index = index };
} else {
return DiceError.InvalidFruitIndex;
}
}
};
/// An error that indicates that something went wrong when constructing a dice result
const DiceError = error{
/// invalid fruit index was given
InvalidFruitIndex,
};
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;
const expect = std.testing.expect;
test "DiceResult constructors: Raven, Basket" {
try expectEqual(DiceResult.new_basket(), .basket);
try expectEqual(DiceResult.new_raven(), .raven);
}
test "DiceResult constructor: Fruit" {
// TODO: how can I elegantly test that the variant indeed contains the payload I want?
// maybe I have to switch on it...
var idx :u8 = 0;
while (idx < game.TREE_COUNT) : (idx += 1) {
try expectEqual(DiceResult.new_fruit(idx),DiceResult{.fruit=Fruit{.index=idx}});
}
try expectError(DiceError.InvalidFruitIndex,DiceResult.new_fruit(game.TREE_COUNT));
try expectError(DiceError.InvalidFruitIndex,DiceResult.new_fruit(10));
}
test "DiceResult constructor: random" {
var prng = std.rand.Xoroshiro128.init(22131342);
// used this to see what that seed actually produces
// var i : u32 = 0;
// while(i < 10) : (i+=1) {
// std.debug.print("result is {}\n", .{DiceResult.new_random(&prng)});
// }
try expectEqual(DiceResult{.raven = .{}}, DiceResult.new_random(&prng));
try expectEqual(DiceResult{.fruit=.{.index=3}}, DiceResult.new_random(&prng));
try expectEqual(DiceResult{.basket=.{}}, DiceResult.new_random(&prng));
} | src/dice.zig |
const std = @import("std");
const core = @import("core");
const sdl = @import("./sdl.zig");
const Coord = core.geometry.Coord;
const makeCoord = core.geometry.makeCoord;
const Rect = core.geometry.Rect;
pub const Button = enum {
up,
down,
left,
right,
start_attack,
start_kick,
backspace,
enter,
escape,
restart,
beat_level,
};
pub const InputEngine = struct {
pub fn init() InputEngine {
return InputEngine{};
}
pub fn handleEvent(self: *InputEngine, event: sdl.c.SDL_Event) ?Button {
switch (event.@"type") {
sdl.c.SDL_KEYUP => {
return null;
},
sdl.c.SDL_KEYDOWN => {
if (event.key.repeat != 0) return null;
return self.handleKeydown(self.getModifiers(), @enumToInt(event.key.keysym.scancode));
},
else => unreachable,
}
}
fn handleKeydown(self: InputEngine, modifiers: Modifiers, scancode: c_int) ?Button {
switch (scancode) {
sdl.c.SDL_SCANCODE_LEFT => return if (modifiers == 0) Button.left else null,
sdl.c.SDL_SCANCODE_RIGHT => return if (modifiers == 0) Button.right else null,
sdl.c.SDL_SCANCODE_UP => return if (modifiers == 0) Button.up else null,
sdl.c.SDL_SCANCODE_DOWN => return if (modifiers == 0) Button.down else null,
sdl.c.SDL_SCANCODE_F => return if (modifiers == 0) Button.start_attack else null,
sdl.c.SDL_SCANCODE_K => return if (modifiers == 0) Button.start_kick else null,
sdl.c.SDL_SCANCODE_R => return if (modifiers == ctrl) Button.restart else null,
sdl.c.SDL_SCANCODE_BACKSPACE => return if (modifiers == 0) Button.backspace else null,
sdl.c.SDL_SCANCODE_RETURN => return if (modifiers == 0) Button.enter else null,
sdl.c.SDL_SCANCODE_ESCAPE => return if (modifiers == 0) Button.escape else null,
sdl.c.SDL_SCANCODE_RIGHTBRACKET => return if (modifiers == shift) Button.beat_level else null,
else => return null,
}
}
const Modifiers = u4;
const shift = 1;
const ctrl = 2;
const alt = 3;
const meta = 4;
fn getModifiers(self: InputEngine) Modifiers {
const sdl_modifiers = @enumToInt(sdl.c.SDL_GetModState());
var result: Modifiers = 0;
if (sdl_modifiers & (sdl.c.KMOD_LSHIFT | sdl.c.KMOD_RSHIFT) != 0) result |= shift;
if (sdl_modifiers & (sdl.c.KMOD_LCTRL | sdl.c.KMOD_RCTRL) != 0) result |= ctrl;
if (sdl_modifiers & (sdl.c.KMOD_LALT | sdl.c.KMOD_RALT) != 0) result |= alt;
if (sdl_modifiers & (sdl.c.KMOD_LGUI | sdl.c.KMOD_RGUI) != 0) result |= meta;
return result;
}
}; | src/gui/input_engine.zig |
const std = @import("std");
pub const InitFn = fn (std.mem.Allocator) anyerror!void;
pub const DeinitFn = fn (std.mem.Allocator) void;
pub const FrameFn = fn (FrameInput) anyerror!bool;
pub const AudioPlaybackFn = fn (AudioPlaybackStream) anyerror!u32;
/// Defines the structure that is passed to the audio playback fn by the platform layer
pub const AudioPlaybackStream = struct {
/// The sample rate of the output stream
sample_rate: u32,
/// The number of output channels
channels: u32,
/// The buffer to write samples to
sample_buf: []f32,
/// Maximum number of frames to write
max_frames: u32,
};
/// Defines the structure that is passed to the frame fn by the platform layer
pub const FrameInput = struct {
/// Temporary allocator whose memory is valid for the duration of the current frame
frame_arena_allocator: std.mem.Allocator,
/// True if the user tried to close the window, gives us a chance to save state,
/// present a quit dialog, etc.
quit_requested: bool,
/// This is the estimated interval (nanoseconds) until the next frame is displayed.
/// NOTE: This will not necessarily reflect the requested refresh rate and may be
/// adjusted up or down depending on the user's display and whether we are missing
/// or beating the current target refresh rate.
target_frame_dt: u64,
/// This was the interval (nanoseconds) between the previous frame and the one
/// previous to that.
prev_frame_elapsed: u64,
/// All user input events that happened before the current frame
user_input: struct {
key_events: []KeyEvent,
mouse_button_events: []MouseButtonEvent,
mouse_position: struct { x: i32, y: i32 },
},
/// The current window size / framebuffer dimensions
window_size: struct { width: u16, height: u16 },
/// Various debug stats, used for displaying debug information
debug_stats: struct {
/// This is how long was taken doing actual work on the CPU for the previous frame
prev_cpu_frame_elapsed: u64,
},
};
pub const MouseButton = enum(u8) { left = 1, middle = 2, right = 3 };
pub const MouseButtonEvent = struct {
action: enum { press, release },
button: MouseButton,
x: i32,
y: i32,
};
pub const KeyEvent = struct {
action: union(enum) {
press: void,
release: void,
repeat: u32,
},
key: Key,
};
pub const KeyReleaseEvent = Key;
/// Represents a physical key position, using a typical QWERTY layout
pub const Key = enum {
unknown,
space,
apostrophe,
comma,
minus,
period,
slash,
zero,
one,
two,
three,
four,
five,
six,
seven,
eight,
nine,
semicolon,
equal,
a,
b,
c,
d,
e,
f,
g,
h,
i,
j,
k,
l,
m,
n,
o,
p,
q,
r,
s,
t,
u,
v,
w,
x,
y,
z,
bracket_left,
bracket_right,
backslash,
grave_accent,
world1,
world2,
escape,
enter,
tab,
backspace,
insert,
delete,
right,
left,
down,
up,
pageup,
pagedown,
home,
end,
capslock,
scrolllock,
numlock,
printscreen,
pause,
f1,
f2,
f3,
f4,
f5,
f6,
f7,
f8,
f9,
f10,
f11,
f12,
f13,
f14,
f15,
f16,
f17,
f18,
f19,
f20,
f21,
f22,
f23,
f24,
f25,
keypad_0,
keypad_1,
keypad_2,
keypad_3,
keypad_4,
keypad_5,
keypad_6,
keypad_7,
keypad_8,
keypad_9,
keypad_decimal,
keypad_divide,
keypad_multiply,
keypad_subtract,
keypad_add,
keypad_enter,
keypad_equal,
shift_left,
shift_right,
ctrl_left,
ctrl_right,
alt_left,
alt_right,
super_left,
super_right,
menu,
}; | modules/platform/src/common.zig |
const std = @import("std");
const I = @import("instruments.zig");
const Instrument = I.Instrument;
const G = @import("global_config.zig");
const print = std.debug.print;
const InstrumentList = std.ArrayList(*Instrument);
pub fn benchmarkInstruments(instr: InstrumentList, n_frames: u32) f32 {
var begin = std.time.nanoTimestamp();
var i: u32 = 0;
var buf: []const f32 = undefined;
var S: f32 = 0.0;
while (i < 1000) : (i += 1) {
for (instr.items) |instrument| {
var t0: f32 = @intToFloat(f32, i) * (G.sec_per_frame * @intToFloat(f32, n_frames));
buf = instrument.play(t0, n_frames);
for (buf) |b| {
S += b / 10;
}
}
}
var end = std.time.nanoTimestamp();
print("buf:{} {} {} {} {} {}\n", .{ buf[0], buf[1], buf[2], buf[3], buf[4], S });
return @intToFloat(f32, (end - begin)) / 1000000000.0;
}
pub fn main() !u8 {
var alloc = std.testing.allocator;
// fast kick
const n_instr: u32 = 50;
var i: u32 = 0;
var static_instruments = InstrumentList.init(alloc);
defer static_instruments.deinit();
var dynamic_instruments = InstrumentList.init(alloc);
defer dynamic_instruments.deinit();
while (i < n_instr) : (i += 1) {
const fi = @intToFloat(f32, i);
var static_kick = try I.createKick(alloc, 0.3, 0.3, 100 * fi, 0.45 + (fi / 100.0), true);
var dynamic_kick = try I.createKick(alloc, 0.3, 0.3, 100 * fi, 0.45 + (fi / 100.0), false);
// defer static_kick.deinit(alloc);
// defer dynamic_kick.deinit(alloc);
try static_instruments.append(static_kick);
try dynamic_instruments.append(dynamic_kick);
}
var time = benchmarkInstruments(dynamic_instruments, 200);
print("Time dynamic kick: {}\n", .{time});
time = benchmarkInstruments(static_instruments, 200);
print("Time static kick: {}\n", .{time});
for (static_instruments.items) |instrument|
instrument.deinit(alloc);
for (dynamic_instruments.items) |instrument|
instrument.deinit(alloc);
return 0;
} | src/benchmarks.zig |
const std = @import("std");
const parser = @import("parser.zig").Parser;
const Allocator = std.mem.Allocator;
const real = @import("Real.zig");
const Local = enum(u8) { _ };
const Register = enum(u8) {
_,
pub fn id(n: u8) Register {
return @intToEnum(Register, n);
}
};
// Using an union makes each instruction take more memory but avoid loading times.
pub const Instruction = union(enum) {
/// Instruction used to load small (0-255) integers
LoadByte: struct {
target: Register,
value: u8
},
LoadString: struct {
target: Register,
value: []const u8
},
Add: struct {
target: Register,
lhs: Register,
rhs: Register
},
LoadLocal: struct {
target: Register,
local: Local
},
SetLocal: struct {
local: Local,
source: Register
},
LoadGlobal: struct {
target: Register,
global: []const u8
},
CallFunction: struct {
name: []const u8,
args_start: Register,
args_num: u8
},
/// Move the content of one register to another
Move: struct {
source: Register,
target: Register
}
};
const max_register_value = std.math.powi(usize, 2, @bitSizeOf(Register)) catch unreachable;
const RegisterBitSet = std.StaticBitSet(max_register_value);
const IrEncodeState = struct {
instructions: std.ArrayList(Instruction),
locals: std.StringHashMap(Local),
freeRegisters: RegisterBitSet,
allocator: Allocator,
pub fn init(allocator: Allocator) IrEncodeState {
return IrEncodeState {
.instructions = std.ArrayList(Instruction).init(allocator),
.locals = std.StringHashMap(Local).init(allocator),
.freeRegisters = RegisterBitSet.initFull(),
.allocator = allocator
};
}
pub const GetFreeRegisterError = error { OutOfRegisters };
fn getFreeRegister(self: *IrEncodeState) GetFreeRegisterError!Register {
return @intToEnum(Register, @intCast(u8,
self.freeRegisters.toggleFirstSet() orelse return error.OutOfRegisters));
}
fn peekFreeRegister(self: *IrEncodeState) GetFreeRegisterError!Register {
return @intToEnum(Register, @intCast(u8,
self.freeRegisters.findFirstSet() orelse return error.OutOfRegisters));
}
fn freeRegister(self: *IrEncodeState, register: Register) void {
self.freeRegisters.set(@enumToInt(register));
}
pub const TakeRegisterError = error { RegisterUsed };
fn takeRegister(self: *IrEncodeState, register: Register) TakeRegisterError!void {
const idx = @enumToInt(register);
if (self.freeRegisters.isSet(idx)) {
self.freeRegisters.unset(idx);
} else {
return error.RegisterUsed;
}
}
};
pub fn encode(allocator: Allocator, block: parser.Block) ![]const Instruction {
var state = IrEncodeState.init(allocator);
errdefer state.instructions.deinit();
// TODO: use for debug info
defer state.locals.deinit();
for (block) |*statement| {
defer statement.deinit(allocator);
switch (statement.*) {
.SetLocal => |*assign| {
const valueIdx = try encodeExpression(&state, &assign.value);
defer state.freeRegister(valueIdx);
const localIdx = (try state.locals.getOrPutValue(assign.name,
@intToEnum(Local, @intCast(u8, state.locals.count())))).value_ptr.*;
try state.instructions.append(.{ .SetLocal = .{
.local = localIdx,
.source = valueIdx
}});
},
.FunctionCall => |*call| {
var start = Register.id(0);
if (call.args.len > 0) {
for (call.args) |*arg, i| {
const idx = try encodeExpression(&state, arg);
// set start to the location of the first argument
if (i == 0) {
start = idx;
}
// expected register
const expected = @intToEnum(Register, @enumToInt(start) + @intCast(u8, i));
if (idx != expected) {
state.freeRegister(idx);
try state.takeRegister(expected);
try state.instructions.append(.{ .Move = .{
.source = idx,
.target = expected
}});
}
}
}
try state.instructions.append(.{ .CallFunction = .{
.name = call.name,
.args_start = start,
.args_num = @intCast(u8, call.args.len)
}});
if (call.args.len > 0) {
for (call.args) |_, i| {
const reg = @intToEnum(Register, @enumToInt(start) + @intCast(u8, i));
state.freeRegister(reg);
}
}
}
}
}
return state.instructions.toOwnedSlice();
}
const ExpressionEncodeError = error {} || IrEncodeState.GetFreeRegisterError ||
std.fmt.ParseIntError || std.mem.Allocator.Error;
/// Returns the register containing the expression's value
fn encodeExpression(state: *IrEncodeState, expr: *parser.Expression) ExpressionEncodeError!Register {
defer expr.deinit(state.allocator);
switch (expr.*) {
.Number => |number| {
if (number.q.toConst().eq(real.bigOne)) {
const numberIdx = try state.getFreeRegister();
try state.instructions.append(.{ .LoadByte = .{
.target = numberIdx,
.value = number.p.to(u8) catch unreachable
}});
return numberIdx;
} else {
@panic("TODO: rational numbers");
}
},
.StringLiteral => |literal| {
const stringIdx = try state.getFreeRegister();
try state.instructions.append(.{ .LoadString = .{
.target = stringIdx,
.value = literal
}});
return stringIdx;
},
.Add => |addition| {
const lhsIdx = try encodeExpression(state, addition.lhs);
const rhsIdx = try encodeExpression(state, addition.rhs);
defer state.freeRegister(rhsIdx);
try state.instructions.append(.{ .Add = .{
.target = lhsIdx, // addition is performed before target is overwritten, so we can re-use register
.lhs = lhsIdx,
.rhs = rhsIdx
}});
return lhsIdx;
},
.FunctionCall => |call| {
// TODO: handle return values
var start = Register.id(0);
if (call.args.len > 0) {
for (call.args) |*arg, i| {
const idx = try encodeExpression(state, arg);
// set start to the location of the first argument
if (i == 0) {
start = idx;
}
// expected register
const expected = @intToEnum(Register, @enumToInt(start) + @intCast(u8, i));
if (idx != expected) {
try state.instructions.append(.{ .Move = .{
.source = idx,
.target = expected
}});
}
}
}
try state.instructions.append(.{ .CallFunction = .{
.name = call.name,
.args_start = start,
.args_num = @intCast(u8, call.args.len)
}});
return Register.id(0); // no destination register :'(
},
.Local => |local| {
const resultIdx = try state.getFreeRegister();
if (state.locals.get(local)) |localIdx| {
try state.instructions.append(.{ .LoadLocal = .{
.target = resultIdx,
.local = localIdx
}});
} else {
try state.instructions.append(.{ .LoadGlobal = .{
.target = resultIdx,
.global = local
}});
}
return resultIdx;
}
}
} | src/ir.zig |
const note_frequencies = @import("zang-12tet");
const c = @import("common/c.zig");
pub const AudioOut = union(enum) {
mono: usize,
stereo: struct { left: usize, right: usize },
};
pub const KeyBinding = struct {
row: u1,
key: i32,
rel_freq: f32,
};
// note: arpeggiator will cycle in this order, so i've arranged it from lowest
// frequency to highest
pub const key_bindings = [_]KeyBinding{
// bottom two rows is one octave
KeyBinding{ .row = 0, .rel_freq = note_frequencies.b2, .key = c.SDLK_LSHIFT },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.c3, .key = c.SDLK_z },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.cs3, .key = c.SDLK_s },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.d3, .key = c.SDLK_x },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.ds3, .key = c.SDLK_d },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.e3, .key = c.SDLK_c },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.f3, .key = c.SDLK_v },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.fs3, .key = c.SDLK_g },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.g3, .key = c.SDLK_b },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.gs3, .key = c.SDLK_h },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.a3, .key = c.SDLK_n },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.as3, .key = c.SDLK_j },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.b3, .key = c.SDLK_m },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.c4, .key = c.SDLK_COMMA },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.cs4, .key = c.SDLK_l },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.d4, .key = c.SDLK_PERIOD },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.ds4, .key = c.SDLK_SEMICOLON },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.e4, .key = c.SDLK_SLASH },
KeyBinding{ .row = 0, .rel_freq = note_frequencies.f4, .key = c.SDLK_RSHIFT },
// top two rows is one octave up (with fair amount of overlap)
KeyBinding{ .row = 1, .rel_freq = note_frequencies.c4, .key = c.SDLK_q },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.cs4, .key = c.SDLK_2 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.d4, .key = c.SDLK_w },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.ds4, .key = c.SDLK_3 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.e4, .key = c.SDLK_e },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.f4, .key = c.SDLK_r },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.fs4, .key = c.SDLK_5 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.g4, .key = c.SDLK_t },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.gs4, .key = c.SDLK_6 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.a4, .key = c.SDLK_y },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.as4, .key = c.SDLK_7 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.b4, .key = c.SDLK_u },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.c5, .key = c.SDLK_i },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.cs5, .key = c.SDLK_9 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.d5, .key = c.SDLK_o },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.ds5, .key = c.SDLK_0 },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.e5, .key = c.SDLK_p },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.f5, .key = c.SDLK_LEFTBRACKET },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.fs5, .key = c.SDLK_EQUALS },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.g5, .key = c.SDLK_RIGHTBRACKET },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.gs5, .key = c.SDLK_BACKSPACE },
KeyBinding{ .row = 1, .rel_freq = note_frequencies.a5, .key = c.SDLK_BACKSLASH },
};
pub fn getKeyRelFreq(key: i32) ?f32 {
for (key_bindings) |kb| {
if (kb.key == key) {
return kb.rel_freq;
}
}
return null;
}
pub fn getKeyRelFreqFromRow(row: u1, key: i32) ?f32 {
for (key_bindings) |kb| {
if (kb.row == row and kb.key == key) {
return kb.rel_freq;
}
}
return null;
} | examples/common.zig |
const std = @import("std");
const testing = std.testing;
const expect = testing.expect;
const expectEqual = testing.expectEqual;
const expectApproxEqRel = testing.expectApproxEqRel;
pub const Quaternion = packed struct {
x: f32,
y: f32,
z: f32,
w: f32,
pub fn init(x: f32, y: f32, z: f32, w: f32) Quaternion {
return .{ .x = x, .y = y, .z = z, .w = w };
}
pub fn identity() Quaternion {
return .{ .x = 0, .y = 0, .z = 0, .w = 1 };
}
pub fn normalize(q: Quaternion) Quaternion {
const inv_length = 1.0 / length(q);
return .{ .x = q.x * inv_length, .y = q.y * inv_length, .z = q.z * inv_length, .w = q.w * inv_length };
}
pub fn length(q: Quaternion) f32 {
return std.math.sqrt(dot(q, q));
}
pub fn conjugate(q: Quaternion) Quaternion {
return .{ .x = -q.x, .y = -q.y, .z = -q.z, .w = q.w };
}
pub fn dot(a: Quaternion, b: Quaternion) f32 {
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
pub fn multiply(a: Quaternion, b: Quaternion) Quaternion {
return .{
// i * 1 = i 1 * i = i j * k = i k * j = -i
.x = (a.x*b.w) + (a.w*b.x) + (a.y*b.z) - (a.z*b.y),
// j * 1 = j 1 * j = j k * i = j i * k = -j
.y = (a.y*b.w) + (a.w*b.y) + (a.z*b.x) - (a.x*b.z),
// k * 1 = k 1 * k = k i * j = k j * i = -k
.z = (a.z*b.w) + (a.w*b.z) + (a.x*b.y) - (a.y*b.x),
// 1 * 1 = 1 i * i = -1 j * j = -1 k * k = -1
.w = (a.w*b.w) - (a.x*b.x) - (a.y*b.y) - (a.z*b.z),
};
}
pub fn multiplyVector(q: Quaternion, v: Vector3) Vector3 {
const qv = Quaternion.init(v.x, v.y, v.z, 0);
const result = q.multiply(qv).multiply(conjugate(q));
return Vector3.init(result.x, result.y, result.z);
}
};
test "Quaternion" {
var q1 = Quaternion.init(1, 2, 3, 4);
var q2 = Quaternion.init(5, 6, 7, 8);
var v: Quaternion = undefined;
var s: f32 = undefined;
v = Quaternion.init(1, 2, 3, 4);
try expectEqual(@as(f32, 1.0), v.x);
try expectEqual(@as(f32, 2.0), v.y);
try expectEqual(@as(f32, 3.0), v.z);
try expectEqual(@as(f32, 4.0), v.w);
v = Quaternion.identity();
try expectEqual(@as(f32, 0.0), v.x);
try expectEqual(@as(f32, 0.0), v.y);
try expectEqual(@as(f32, 0.0), v.z);
try expectEqual(@as(f32, 1.0), v.w);
s = Quaternion.dot(q1, q2);
try expectApproxEqRel(@as(f32, 70.0), s, 0.0001);
s = Quaternion.length(q1);
try expectApproxEqRel(@as(f32, 5.477), s, 0.0001);
v = Quaternion.normalize(q1);
try expectApproxEqRel(@as(f32, 1.0/5.477), v.x, 0.0001);
try expectApproxEqRel(@as(f32, 2.0/5.477), v.y, 0.0001);
try expectApproxEqRel(@as(f32, 3.0/5.477), v.z, 0.0001);
try expectApproxEqRel(@as(f32, 4.0/5.477), v.w, 0.0001);
} | src/quaternion.zig |
const std = @import("std");
const format = @import("format.zig");
const value = @import("value.zig");
const expect = std.testing.expect;
pub const encodeValue = @import("encode_value.zig").encodeValue;
pub const decodeValue = @import("decode_value.zig").decodeValue;
pub const encode = @import("encode.zig").encode;
pub const decode = @import("decode.zig").decode;
pub const Decoder = @import("decoder.zig").Decoder;
pub const Encoder = @import("encoder.zig").Encoder;
pub const Value = value.Value;
pub fn valid(allocator: *std.mem.Allocator, buf: []const u8) bool {
if (decodeValue(allocator, buf)) |foo| {
return true;
}
return false;
}
test "test encode / decode map" {
var values = std.StringHashMap(value.Value).init(std.testing.allocator);
try values.put("s", value.Value{ .string = "string" });
try values.put("u", value.Value{ .uint = 123456 });
try values.put("b", value.Value{ .bool = true });
try values.put("i", value.Value{ .int = -12343 });
var array = try std.ArrayList(value.Value).initCapacity(std.testing.allocator, 2);
try array.append(.{ .uint = 1 });
try array.append(.{ .string = "hello" });
try values.put("a", value.Value{ .array = array });
var m = std.StringHashMap(value.Value).init(std.testing.allocator);
try m.put("s", value.Value{ .string = "hello world" });
try values.put("m", value.Value{ .map = m });
try values.put("n", .nil);
var val = value.Value{ .map = values };
var encoded = try encodeValue(std.testing.allocator, val);
var decoded = try decodeValue(std.testing.allocator, encoded);
expect(std.mem.eql(u8, values.get("s").?.string, decoded.map.get("s").?.string));
expect(values.get("u").?.uint == decoded.map.get("u").?.uint);
expect(values.get("b").?.bool == decoded.map.get("b").?.bool);
expect(values.get("i").?.int == decoded.map.get("i").?.int);
expect(values.get("a").?.array.items[0].uint == decoded.map.get("a").?.array.items[0].uint);
expect(std.mem.eql(u8, values.get("a").?.array.items[1].string, decoded.map.get("a").?.array.items[1].string));
expect(std.mem.eql(u8, values.get("m").?.map.get("s").?.string, decoded.map.get("m").?.map.get("s").?.string));
expect(values.get("n").?.nil == decoded.map.get("n").?.nil);
decoded.free();
std.testing.allocator.free(encoded);
val.free();
} | src/main.zig |
const std = @import("std");
const Token = @import("token.zig").Token;
const ArrayList = std.ArrayList;
const StringHashMap = std.hash_map.StringHashMap;
const ParseError = @import("parse_error.zig").ParseError;
pub const Node = union(enum) {
Document: Document,
DocumentType: DocumentType,
DocumentFragment: DocumentFragment,
Element: Element,
Text: Text,
ProcessingInstruction: ProcessingInstruction,
Comment: Comment,
};
pub const Document = struct {
const Self = @This();
allocator: *std.mem.Allocator,
title: ?[]const u8 = null,
dir: ?[]const u8 = null,
quirksMode: bool = false,
limitedQuirksMode: bool = false,
doctype: ?DocumentType = null,
body: ?Element = null,
head: ?Element = null,
images: ArrayList(Element),
embeds: ArrayList(Element),
plugins: ArrayList(Element),
links: ArrayList(Element),
forms: ArrayList(Element),
scripts: ArrayList(Element),
parseErrors: ArrayList(ParseError),
currentScript: ?Element = null,
children: ArrayList(Node),
throwOnDynamicMarkupInsertionCounter: usize = 0,
pub fn init(allocator: *std.mem.Allocator) Document {
return Document{
.allocator = allocator,
.images = ArrayList(Element).init(allocator),
.embeds = ArrayList(Element).init(allocator),
.plugins = ArrayList(Element).init(allocator),
.links = ArrayList(Element).init(allocator),
.forms = ArrayList(Element).init(allocator),
.scripts = ArrayList(Element).init(allocator),
.children = ArrayList(Node).init(allocator),
.parseErrors = ArrayList(ParseError).init(allocator),
};
}
pub fn appendNode(self: *Self, node: Node) void {
self.children.append(node) catch unreachable;
}
pub fn nodeCount(self: Self) usize {
return self.children.items.len;
}
pub fn popNode(self: *Self) ?Node {
return self.children.popOrNull();
}
};
pub const DocumentType = struct {
const Self = @This();
name: []const u8,
publicId: []const u8,
systemId: []const u8,
};
pub const DocumentFragment = struct {
const Self = @This();
};
pub const Element = struct {
const Self = @This();
const Namespace = enum {
HTML,
MathML,
SVG,
XLink,
XML,
XMLNS,
pub fn toUri(self: Namespace) []const u8 {
return switch (self) {
.HTML => "http://www.w3.org/1999/xhtml",
.MathML => "http://www.w3.org/1998/Math/MathML",
.SVG => "http://www.w3.org/2000/svg",
.XLink => "http://www.w3.org/1999/xlink",
.XML => "http://www.w3.org/XML/1998/namespace",
.XMLNS => "http://www.w3.org/2000/xmlns/",
};
}
};
namespace: Namespace,
prefix: ?[]const u8,
localName: []const u8,
tagName: []const u8,
id: []const u8,
className: []const u8,
classList: ArrayList([]const u8),
slot: []const u8,
document: Document,
attributes: StringHashMap([]const u8),
pub fn init(local_name: []const u8, document: Document, namespace: Namespace, token: ?Token) Element {
var definition: ?Element = null; // TODO: Look up custom element definition
return Element{
.name = local_name,
.document = document,
.namespace = namespace,
.attributes = attributes,
.prefix = null,
.is = null,
.synchronousCustomElements = false,
};
}
pub fn namespaceUri(self: Self) []const u8 {
return self.namespace.toUri();
}
pub fn hasAttributes(self: Self) bool {
return self.attributes.items().len > 0;
}
pub fn getAttributeNames(self: Self) [][]const u8 {}
pub fn isInNamespace(self: Self, namespace: Namespace) bool {
return self.namespace == namespace;
}
pub fn isHTMLIntegrationPoint(self: Self) bool {
return false;
}
pub fn isMathMLTextIntegrationPoint(self: Self) bool {
return false;
}
};
pub const Text = struct {
const Self = @This();
};
pub const ProcessingInstruction = struct {
const Self = @This();
};
pub const Comment = struct {
const Self = @This();
data: []const u8
}; | src/node.zig |
const std = @import("std");
pub const audio_graph = @import("audio_graph.zig");
pub const system = @import("system.zig");
pub const module = @import("module.zig");
pub const modules = module.modules;
pub const sample_buffer = @import("sample_buffer.zig");
const Utility = modules.Utility;
const SamplePlayer = modules.SamplePlayer;
const SampleBuffer = sample_buffer.SampleBuffer;
pub fn main() anyerror!void {}
test "" {
_ = audio_graph;
_ = system;
_ = module;
_ = modules;
_ = sample_buffer;
}
test "main" {
var sys: system.System = undefined;
try sys.init(.{
.allocator = std.testing.allocator,
.suggested_latency = 0.15,
.device_number = 5,
});
defer sys.deinit();
var graph_ctl = &sys.controller;
// var play_ctl: module.Controlled(SamplePlayer) = undefined;
// try play_ctl.init(std.testing.allocator, 10, modules.SamplePlayer.init());
// var play_ctlr = play_ctl.makeController();
//
// var play_idx = try graph_ctl.addModule(module.Module.init(&play_ctl));
// graph_ctl.setOutput(play_idx);
//
// try graph_ctl.pushChanges(std.testing.allocator, sys.tm.now());
//
// const file = @embedFile("../content/amen_brother.wav");
// var smp = try SampleBuffer.initWav(std.testing.allocator, file);
// defer smp.deinit();
//
// try play_ctlr.send(sys.tm.now(), .{ .setSample = &smp });
// try play_ctlr.send(sys.tm.now(), .{ .setPlayRate = 1. });
// try play_ctlr.send(sys.tm.now(), .{ .setPlayPosition = 1000 });
// try play_ctlr.send(sys.tm.now(), .{ .setAntiClick = true });
// try play_ctlr.send(sys.tm.now(), .play);
// try play_ctlr.send(sys.tm.now() + 700000000, .pause);
// try play_ctlr.send(sys.tm.now() + 970000000, .play);
// try play_ctlr.send(sys.tm.now(), .{ .setLoop = true });
var sine = modules.Sine.init(440.);
var sine_ctl: module.Controlled(modules.Sine) = undefined;
try sine_ctl.init(std.testing.allocator, 10, &sine);
defer sine_ctl.deinit();
var sine_ctlr = sine_ctl.makeController();
var util = modules.Utility.init();
var util_ctl: module.Controlled(modules.Utility) = undefined;
try util_ctl.init(std.testing.allocator, 10, &util);
defer util_ctl.deinit();
var util_ctlr = util_ctl.makeController();
const sine_idx = try graph_ctl.addModule(sine_ctl.module());
const util_idx = try graph_ctl.addModule(util_ctl.module());
_ = try graph_ctl.addEdge(sine_idx, util_idx, 0);
graph_ctl.setOutput(util_idx);
try graph_ctl.pushChanges(std.testing.allocator, sys.tm.now());
var in = std.io.getStdIn();
var buf = [_]u8{ 0, 0, 0 };
while (buf[0] != 'q') {
// std.time.sleep(1000000000);
_ = try in.read(&buf);
try sine_ctlr.send(0, .{ .setFreq = 660 });
try util_ctlr.send(sys.tm.now(), .{ .setVolume = 0.15 });
// util.volume = 0.5;
// try util_ctlr.send(0, vol0);
// graph_ctl.frame();
//
// _ = try in.read(&buf);
// try util_ctlr.send(0, vol1);
// graph_ctl.frame();
}
} | src/main.zig |
const std = @import("std");
const objects = @import("didot-objects");
const models = @import("didot-models");
const zlm = @import("zlm");
const Allocator = std.mem.Allocator;
fn to_f32(value: std.json.Value) f32 {
return switch (value) {
.Float => |float| @floatCast(f32, float),
.Integer => |int| @intToFloat(f32, int),
else => unreachable
};
}
fn to_vec3(array: []std.json.Value) zlm.Vec3 {
return zlm.vec3(to_f32(array[0]), to_f32(array[1]), to_f32(array[2]));
}
pub fn loadFrom(allocator: *Allocator, text: []const u8) !*objects.Scene {
var scene = try objects.Scene.create(allocator, null);
var p = std.json.Parser.init(allocator, false);
defer p.deinit();
var tree = try p.parse(text);
defer tree.deinit();
var root = tree.root;
var objectsJs = root.Object.get("objects").?.Array;
var assetsJs = root.Object.get("assets").?.Object;
var assetsIterator = assetsJs.iterator();
while (assetsIterator.next()) |entry| {
const assetJs = entry.value;
if (assetJs.Object.contains("mesh")) {
const mesh = assetJs.Object.get("mesh").?.Object;
const path = mesh.get("path").?.String;
const format = mesh.get("format").?.String;
try scene.assetManager.put(entry.key, .{
.loader = models.meshAssetLoader,
.loaderData = try models.MeshAssetLoaderData.init(allocator, path, format),
.objectType = .Mesh,
});
}
}
for (objectsJs.items) |obj, i| {
const objectType = obj.Object.get("type").?.String;
var go: objects.GameObject = undefined;
if (std.mem.eql(u8, objectType, "camera")) {
var shader = try @import("didot-graphics").ShaderProgram.create(@embedFile("../assets/shaders/vert.glsl"), @embedFile("../assets/shaders/frag.glsl"));
var camera = try objects.Camera.create(allocator, shader);
go = camera.gameObject;
} else if (std.mem.eql(u8, objectType, "point_light")) {
var pointLight = try objects.PointLight.create(allocator);
go = pointLight.gameObject;
} else {
go = objects.GameObject.createEmpty(allocator);
}
go.name = obj.Object.get("name").?.String;
if (obj.Object.get("mesh")) |mesh| {
go.meshPath = mesh.String;
}
go.position = to_vec3(obj.Object.get("position").?.Array.items);
go.rotation = to_vec3(obj.Object.get("rotation").?.Array.items).toRadians();
go.scale = to_vec3(obj.Object.get("scale").?.Array.items);
try scene.add(go);
}
return scene;
} | src/scene.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList(usize);
const parseUnsigned = std.fmt.parseUnsigned;
fn chainAdapters(adapters: []usize, dist: []usize, diff: *ArrayList) !void {
var prev: usize = 0;
var dx: usize = undefined;
for (adapters) |adapter| {
dx = adapter - prev;
dist[dx - 1] += 1;
try diff.append(dx);
prev = adapter;
}
}
fn permute(n: usize) usize {
return switch (n) {
1 => 1,
2 => 2,
3 => 4,
4 => 7,
else => |x| x,
};
}
fn combinations(allocator: *Allocator, diffs: []usize) !usize {
var permutable = ArrayList.init(allocator);
var n: usize = 0;
for (diffs) |diff| {
if (diff == 3 and n > 0) {
try permutable.append(permute(n));
n = 0;
} else if (diff == 1) {
n += 1;
}
}
if (n > 0) { // catch any trailing 1s
try permutable.append(permute(n));
}
n = 1;
for (permutable.items) |perm| {
n *= perm;
}
return n;
}
pub fn main() anyerror!void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
var adapters = ArrayList.init(allocator);
var stdin = std.io.getStdIn().reader();
var in = std.io.bufferedReader(stdin).reader();
var buf: [256]u8 = undefined;
while (try in.readUntilDelimiterOrEof(&buf, '\n')) |line| {
try adapters.append(try parseUnsigned(usize, line, 10));
}
std.sort.sort(usize, adapters.items, {}, comptime std.sort.asc(usize));
var diff = ArrayList.init(allocator);
// Part A
var dist = [3]usize{ 0, 0, 1 };
try chainAdapters(adapters.items, &dist, &diff);
std.debug.print("A) {d} * {d} = {d}\n", .{ dist[0], dist[2], dist[0] * dist[2] });
// Part B
const nb = try combinations(allocator, diff.items);
std.debug.print("B) {d} combinations\n", .{nb});
} | 2020/zig/src/10.zig |
const std = @import("std");
/// Node in filesystem tree
pub fn FSNode(comptime T: type, max_name_length: usize) type {
return struct {
/// Hashmap key & value type
pub const HashMapKeyVal = *[]const u8;
/// Hashmap context type
const HashmapContext = struct {
pub fn hash(self: @This(), k: HashMapKeyVal) u64 {
return std.hash_map.hashString(k.*);
}
pub fn eql(self: @This(), k1: HashMapKeyVal, k2: HashMapKeyVal) bool {
return std.mem.eql(u8, k1.*, k2.*);
}
};
/// Node data
ref: T = .{},
/// Name buffer
name_buf: [max_name_length]u8 = undefined,
/// Node name. Always points to name_buf
name: []const u8 = undefined,
/// Node children
children: std.HashMapUnmanaged(HashMapKeyVal, HashMapKeyVal, HashmapContext, 80) = .{},
/// Node parent
parent: ?*@This() = null,
/// Mount pointer. Points to root dentry of mounted fs if not null
mount: ?*@This() = null,
/// Mount link. Points to the directory entry on which fs was mounted if this directory
/// entry is root of the filesystem
origin: ?*@This() = null,
/// Next node in cache
next_in_cache: ?*@This() = null,
/// Previous node in cache
prev_in_cache: ?*@This() = null,
/// Node reference count
ref_count: usize = 1,
/// True if reachable from fs root
reachable_from_root: bool = true,
/// Get hashmap key
pub fn key(self: *@This()) HashMapKeyVal {
return &self.name;
}
/// Get node from key
pub fn fromKey(k: HashMapKeyVal) *@This() {
return @fieldParentPtr(@This(), "name", k);
}
/// Recursively enter mounts
/// NOTE: Does not modify reference counts
pub fn traceMounts(self: *@This()) *@This() {
var current = self;
while (current.mount) |mount| : (current = mount) {}
return current;
}
/// Recursively exit from mounted filesystems
/// NOTE: Does not modify reference counts
pub fn backtraceMounts(self: *@This()) *@This() {
var current = self;
while (current.origin) |origin| : (current = origin) {}
return current;
}
/// Update node's name
/// NOTE: node should not be inserted in child hashmap
pub fn updateName(self: *@This(), name: []const u8) void {
std.debug.assert(name.len <= max_name_length);
self.name = self.name_buf[0..name.len];
std.mem.copy(u8, self.name_buf[0..name.len], name);
}
/// Looks up node child and traces mounts as needed
/// NOTE: Does not modify reference counts
pub fn getChild(self: *@This(), name: []const u8) ?*@This() {
var slice_buf = name;
return fromKey(self.children.get(&slice_buf) orelse return null).traceMounts();
}
/// Add child node
/// NOTE: Does not modify reference counts
pub fn addChild(self: *@This(), child: *@This(), allocator: *std.mem.Allocator) !void {
child.parent = self;
try self.children.put(allocator, child.key(), child.key());
}
/// Remove child
/// NOTE: Does not modify reference counts
pub fn removeChild(self: *@This(), child: *@This()) void {
if (std.debug.runtime_safety) {
child.parent = null;
}
std.debug.assert(self.children.remove(child.key()));
child.reachable_from_root = false;
}
/// Add mount. This node should not have mount beforehand
/// NOTE: Does not modify reference counts
pub fn addMount(self: *@This(), mount: *@This()) void {
std.debug.assert(self.mount == null);
self.mount = mount;
mount.origin = self;
}
/// Remove mount. Mount pointer should be non-null and there should be
/// no mounts on top. Pointer to the unmounted node is returned. If no mount is present,
/// null is returned
pub fn removeMount(self: *@This()) ?*@This() {
if (self.mount) |mount| {
std.debug.assert(mount.mount == null);
self.mount = null;
return mount;
}
return null;
}
/// Get node's backtraced parent. Exits mounts. Used to implement .. lookup
/// NOTE: Does not modify reference counts
pub fn getParent(self: *@This()) ?*@This() {
return self.backtraceMounts().parent;
}
/// Create node
pub fn create(allocator: *std.mem.Allocator, name: []const u8) !*@This() {
std.debug.assert(name.len <= max_name_length);
const result = try allocator.create(@This());
result.* = .{};
result.updateName(name);
return result;
}
/// Dispose node
pub fn destroy(self: *@This(), allocator: *std.mem.Allocator) void {
self.children.deinit(allocator);
allocator.destroy(self);
}
};
}
test "Basic FSNode operations" {
const MyDEntry = FSNode(struct { ino: usize = 0 }, 255);
const makeDEntry = struct {
fn makeDEntry(name: []const u8, id: usize) !*MyDEntry {
const result = try MyDEntry.create(std.testing.allocator, name);
result.ref.ino = id;
return result;
}
}.makeDEntry;
// /
// - home/
// - anon/
// - dev/ -> devroot/
// - block/
const root = try makeDEntry("", 1);
const home = try makeDEntry("home", 2);
const anon = try makeDEntry("anon", 3);
const dev = try makeDEntry("dev", 4);
const devRoot = try makeDEntry("", 5);
const block = try makeDEntry("block", 6);
try root.addChild(home, std.testing.allocator);
try root.addChild(dev, std.testing.allocator);
try home.addChild(anon, std.testing.allocator);
try devRoot.addChild(block, std.testing.allocator);
dev.addMount(devRoot);
try std.testing.expectEqual(root.getChild("dev").?.getChild("block").?.ref.ino, 6);
try std.testing.expectEqual(root.getChild("usr"), null);
try std.testing.expectEqual(root.getChild("home").?.getChild("anon").?.ref.ino, 3);
try std.testing.expectEqual(block.getParent().?.getParent().?.ref.ino, 1);
// Mount fs on top of home
const tmpHomeRoot = try makeDEntry("", 8);
const anon2 = try makeDEntry("anon", 9);
try tmpHomeRoot.addChild(anon2, std.testing.allocator);
home.addMount(tmpHomeRoot);
try std.testing.expectEqual(root.getChild("home").?.getChild("anon").?.ref.ino, 9);
try std.testing.expectEqual(home.removeMount(), tmpHomeRoot);
try std.testing.expectEqual(root.getChild("home").?.getChild("anon").?.ref.ino, 3);
root.removeChild(home);
try std.testing.expectEqual(root.getChild("usr"), null);
root.destroy(std.testing.allocator);
home.destroy(std.testing.allocator);
anon.destroy(std.testing.allocator);
dev.destroy(std.testing.allocator);
devRoot.destroy(std.testing.allocator);
block.destroy(std.testing.allocator);
tmpHomeRoot.destroy(std.testing.allocator);
anon2.destroy(std.testing.allocator);
} | fsnode.zig |
const std = @import("std");
const bld = std.build;
const main = @import("src/main.zig");
const Mode = main.Mode;
const Testdata = struct {
mode: Mode,
foldername: []const u8,
exp_exit_code: u8,
};
// 0123, 3 only with file output, 01 only with check
const Testcases = [_]Testdata{
// TODO utf8 control sequences, deprecated characters
// => question: how to write the test cases?
// TODO pipe stdout
Testdata{ .mode = Mode.CheckOnly, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x02", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x03", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x04", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x05", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x06", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x07", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x08", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x09", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x1c", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x1d", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x1e", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x1f", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/f_\x20", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnly, .foldername = "test_folders/control_sequences/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 1 },
Testdata{ .mode = Mode.CheckOnlyAscii, .foldername = "test_folders/control_sequences/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 2 },
Testdata{ .mode = Mode.ShellOutput, .foldername = "test_folders/control_sequences/", .exp_exit_code = 2 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 2 },
Testdata{ .mode = Mode.ShellOutputAscii, .foldername = "test_folders/control_sequences/", .exp_exit_code = 2 },
Testdata{ .mode = Mode.FileOutput, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/ctrl_seq_nonewline/", .exp_exit_code = 2 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 2 },
Testdata{ .mode = Mode.FileOutput, .foldername = "test_folders/control_sequences/", .exp_exit_code = 3 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "zig-out/", .exp_exit_code = 0 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/-fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/--fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/~fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/ fname", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/fname ", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/fname1 -fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/bad_patterns/fname1 ~fname2", .exp_exit_code = 1 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/ctrl_seq_nonewline/", .exp_exit_code = 2 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/control_sequences/f_\x01", .exp_exit_code = 2 },
Testdata{ .mode = Mode.FileOutputAscii, .foldername = "test_folders/control_sequences/", .exp_exit_code = 3 },
};
fn createTests(b: *bld.Builder, exe: *bld.LibExeObjStep, dep_step: *bld.Step) [Testcases.len]*bld.RunStep {
var tcases = Testcases;
_ = tcases;
// idea: parallel test execution?
//var prev_test_case: ?*std.build.RunStep = null;
var test_cases: [Testcases.len]*std.build.RunStep = undefined;
for (tcases) |_, i| {
test_cases[i] = exe.run(); // *RunStep
test_cases[i].expected_exit_code = tcases[i].exp_exit_code;
test_cases[i].step.dependOn(dep_step);
// if (prev_test_case != null)
// test_cases[i].step.dependOn(&(prev_test_case.?.step));
//
const inttest_arg = b.pathJoin(&.{ b.build_root, tcases[i].foldername });
test_cases[i].addArgs(&.{inttest_arg});
switch (tcases[i].mode) {
Mode.CheckOnly => test_cases[i].addArgs(&.{"-c"}),
Mode.CheckOnlyAscii => test_cases[i].addArgs(&.{ "-a", "-c" }),
Mode.FileOutput => {
// multiple executables write same file
const tmpfile_path = b.pathJoin(&.{ b.build_root, "zig-cache/tmp/inttest.txt" });
test_cases[i].addArgs(&.{ "-outfile", tmpfile_path });
},
Mode.FileOutputAscii => {
// multiple executables write same file
const tmpfile_path = b.pathJoin(&.{ b.build_root, "zig-cache/tmp/inttest.txt" });
test_cases[i].addArgs(&.{ "-a", "-outfile", tmpfile_path });
},
Mode.ShellOutput => {},
Mode.ShellOutputAscii => test_cases[i].addArgs(&.{"-a"}),
}
//prev_test_case = test_cases[i];
}
return test_cases;
}
pub fn build(b: *bld.Builder) void {
const target = b.standardTargetOptions(.{});
const mode = b.standardReleaseOptions();
// install
const exe = b.addExecutable("chepa", "src/main.zig");
exe.setTarget(target);
exe.setBuildMode(mode);
exe.install();
// run
const run_cmd = exe.run();
run_cmd.step.dependOn(b.getInstallStep());
if (b.args) |args|
run_cmd.addArgs(args);
const run_cmd_step = b.step("run", "Run the app");
run_cmd_step.dependOn(&run_cmd.step);
// unit tests
const exe_tests = b.addTest("src/main.zig");
exe_tests.setTarget(target);
exe_tests.setBuildMode(mode);
const test_step = b.step("test", "Run unit tests");
test_step.dependOn(&exe_tests.step);
// build and run binary to create test folders
// stage1: panic from build system, if executable is non-existing
//const tfgen = b.addExecutable("tfgen", "src/testfolder_gen.zig");
const tfgen = b.addExecutable("tfgen", "src/testfolder_gen.zig");
tfgen.setTarget(target);
tfgen.setBuildMode(mode);
tfgen.install();
const run_tfgen = tfgen.run(); // integration test generation
run_tfgen.step.dependOn(b.getInstallStep());
const tfgen_arg = b.pathJoin(&.{ b.build_root, "test_folders" });
run_tfgen.addArgs(&.{tfgen_arg});
const run_tfgen_step = b.step("tfgen", "Test folders generation");
run_tfgen_step.dependOn(&run_tfgen.step); // integration test generation
const run_inttest_step = b.step("inttest", "Run integration tests");
const testdata = createTests(b, exe, run_tfgen_step);
// idea: how to enumerate test sequences?
for (testdata) |single_test| {
run_inttest_step.dependOn(&single_test.step);
}
// TODO expand build.zig: StdIoAction limits *make*, which executes *RunStep
// => requires comptime-selection of string compare function,
const perfgen = b.addExecutable("perfgen", "src/perffolder_gen.zig");
perfgen.setTarget(target);
perfgen.setBuildMode(mode);
perfgen.install();
const run_perfgen = perfgen.run(); // perf bench data generation
run_perfgen.step.dependOn(b.getInstallStep());
const perfgen_arg = b.pathJoin(&.{ b.build_root, "perf_folders" });
run_perfgen.addArgs(&.{perfgen_arg});
const run_perfgen_step = b.step("perfgen", "Perf benchmark folders generation (requires ~440MB memory)");
run_perfgen_step.dependOn(&run_perfgen.step); // perf bench data generation
//idea: check, if hyperfine is installed or build+use a proper c/c++ equivalent
//hyperfine './zig-out/bin/chepa perf_folders/ -c' 'fd -j1 "blabla" perf_folders/'
//hyperfine './zig-out/bin/chepa perf_folders/' 'fd -j1 "blabla" perf_folders/'
//'./zig-out/bin/chepa perf_folders/ -c' ran
// 2.23 ± 0.07 times faster than 'fd -j1 "blabla" perf_folders/'
//'./zig-out/bin/chepa perf_folders/' ran
// 2.30 ± 0.04 times faster than 'fd -j1 "blabla" perf_folders/'
//const run_perfbench = exe.run(); // run perf benchmarks
//run_perfbench.step.dependOn(run_perfgen_step);
//const perfbench_arg = b.pathJoin(&.{ b.build_root, "perf_folders" });
//run_perfbench.addArgs(&.{perfbench_arg});
//const run_perfbench_step = b.step("inttest", "Run integration tests");
//run_perfbench_step.dependOn(&run_perfbench.step); // run perf benchmarks
} | build.zig |
const std = @import("std");
const builtin = @import("builtin");
const IsWasm = builtin.target.isWasm();
const stdx = @import("stdx");
const platform = @import("platform");
const Window = platform.Window;
const graphics = @import("graphics");
const Color = graphics.Color;
const ui = @import("ui");
const TextEditor = ui.widgets.TextEditor;
const TextButton = ui.widgets.TextButton;
const Column = ui.widgets.Column;
const Row = ui.widgets.Row;
const Text = ui.widgets.Text;
const Slider = ui.widgets.Slider;
const Flex = ui.widgets.Flex;
const Button = ui.widgets.Button;
const Padding = ui.widgets.Padding;
const Stretch = ui.widgets.Stretch;
const ColorPicker = ui.widgets.ColorPicker;
const SwitchOption = ui.widgets.SwitchOption;
const FileDialog = ui.widgets.FileDialog;
const Root = ui.widgets.Root;
const helper = @import("helper.zig");
const log = stdx.log.scoped(.main);
/// Note: This embedded color emoji font only contains two emojis for the demo. Download the full emoji set on the web.
const NotoColorEmoji = @embedFile("../../examples/assets/NotoColorEmoji.ttf");
const tamzen9_otb = @embedFile("../../assets/tamzen5x9r.otb");
pub const App = struct {
alloc: std.mem.Allocator,
text_editor: ui.WidgetRef(TextEditor),
size_slider: ui.WidgetRef(Slider),
text_color: Color,
bg_color: Color,
text_wrap: bool,
root: *Root,
file_m: u32,
cwd: []const u8,
ctx: *ui.CommonContext,
font_family: graphics.FontFamily,
const Self = @This();
pub fn init(self: *Self, c: *ui.InitContext) void {
self.* = .{
.alloc = c.alloc,
.root = c.getRoot(),
.text_editor = .{},
.size_slider = .{},
.text_color = Color.Black,
.bg_color = Color.White,
.text_wrap = false,
.cwd = undefined,
.file_m = undefined,
.font_family = graphics.FontFamily.Default,
.ctx = c.common,
};
var buf: [std.os.PATH_MAX]u8 = undefined;
const cwd = std.os.getcwd(&buf) catch @panic("error");
self.cwd = c.alloc.dupe(u8, cwd) catch @panic("error");
}
pub fn deinit(node: *ui.Node, alloc: std.mem.Allocator) void {
const self = node.getWidget(Self);
alloc.free(self.cwd);
}
pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId {
const S = struct {
fn onSliderChange(self_: *Self, value: i32) void {
self_.text_editor.getWidget().setFontSize(@intToFloat(f32, value));
}
fn onFgPreviewChange(self_: *Self, color: Color) void {
self_.text_color = color;
}
fn onFgResult(self_: *Self, color: Color, save: bool) void {
_ = save;
self_.text_color = color;
}
fn onBgPreviewChange(self_: *Self, color: Color) void {
self_.bg_color = color;
}
fn onBgResult(self_: *Self, color: Color, save: bool) void {
_ = save;
self_.bg_color = color;
}
fn onTextWrapChange(self_: *Self, is_set: bool) void {
self_.text_wrap = is_set;
}
fn onOpenFont(self_: *Self, path: []const u8) void {
const font_data = std.fs.cwd().readFileAlloc(self_.alloc, path, 1e8) catch @panic("error");
defer self_.alloc.free(font_data);
const g = self_.ctx.getGraphics();
const font_id = g.addFontTTF(font_data);
self_.font_family = graphics.FontFamily{ .Font = font_id };
}
fn buildFileDialog(ptr: ?*anyopaque, c_: *ui.BuildContext) ui.FrameId {
const self_ = stdx.mem.ptrCastAlign(*Self, ptr);
return c_.decl(FileDialog, .{
.init_cwd = self_.cwd,
.onResult = c_.funcExt(self_, onOpenFont),
});
}
fn onLoadFontClick(self_: *Self, _: platform.MouseUpEvent) void {
self_.file_m = self_.root.showModal(self_, buildFileDialog, .{});
}
};
const size = if (self.size_slider.binded) self.size_slider.getWidget().value else 0;
return c.decl(Row, .{
.children = c.list(.{
c.decl(Flex, .{
.flex = 3,
.child = c.decl(Column, .{
.children = c.list(.{
c.decl(Stretch, .{
.child = c.decl(Padding, .{
.padding = 10,
.child = c.decl(TextEditor, .{
.bind = &self.text_editor,
// .font_family = "Tamzen",
.font_family = self.font_family,
.init_val = "The quick brown fox 🦊 jumps over the lazy dog 🐶.\n\nThe graphics and UI are built from scratch with no dependencies.",
.text_color = self.text_color,
.bg_color = self.bg_color,
}),
}),
}),
}),
}),
}),
c.decl(Flex, .{
.flex = 1,
.child = c.decl(Column, .{
.spacing = 10,
.children = c.list(.{
c.decl(Text, .{
.text = c.fmt("Size ({})", .{size}),
.color = Color.White,
}),
c.decl(Stretch, .{
.method = .Width,
.child = c.decl(Slider, .{
.bind = &self.size_slider,
.init_val = 20,
.min_val = 1,
.max_val = 200,
.onChange = c.funcExt(self, S.onSliderChange),
}),
}),
c.decl(ColorPicker, .{
.label = "Text Color",
.init_val = self.text_color,
.onPreviewChange = c.funcExt(self, S.onFgPreviewChange),
.onResult = c.funcExt(self, S.onFgResult),
}),
c.decl(ColorPicker, .{
.label = "Bg Color",
.init_val = self.bg_color,
.onPreviewChange = c.funcExt(self, S.onBgPreviewChange),
.onResult = c.funcExt(self, S.onBgResult),
}),
c.decl(SwitchOption, .{
.label = "Text Wrap (TODO)",
.init_val = false,
.onChange = c.funcExt(self, S.onTextWrapChange),
}),
c.decl(TextButton, .{
.text = "Load Font",
.onClick = c.funcExt(self, S.onLoadFontClick),
}),
}),
}),
}),
}),
});
}
};
var app: helper.App = undefined;
pub fn main() !void {
// This is the app loop for desktop. For web/wasm see wasm exports below.
app.init("Text Demo");
defer app.deinit();
_ = app.gctx.addFontOTB(&.{
.{ .data = tamzen9_otb, .size = 9 },
});
const emoji_font = app.gctx.addFontTTF(NotoColorEmoji);
app.gctx.addFallbackFont(emoji_font);
app.runEventLoop(update);
}
fn update(delta_ms: f32) void {
const S = struct {
fn buildRoot(_: void, c: *ui.BuildContext) ui.FrameId {
return c.decl(App, .{});
}
};
const ui_width = @intToFloat(f32, app.win.getWidth());
const ui_height = @intToFloat(f32, app.win.getHeight());
app.ui_mod.updateAndRender(delta_ms, {}, S.buildRoot, ui_width, ui_height) catch unreachable;
}
pub usingnamespace if (IsWasm) struct {
export fn wasmInit() *const u8 {
return helper.wasmInit(&app, "Text Demo");
}
export fn wasmUpdate(cur_time_ms: f64, input_buffer_len: u32) *const u8 {
return helper.wasmUpdate(cur_time_ms, input_buffer_len, &app, update);
}
/// Not that useful since it's a long lived process in the browser.
export fn wasmDeinit() void {
app.deinit();
stdx.wasm.deinit();
}
} else struct {}; | ui/examples/text_demo.zig |
const std = @import("std");
const builtin = @import("builtin");
const liu = @import("./lib.zig");
const Vec2 = liu.Vec2;
var frame_id: u64 = 0;
var time: f64 = undefined;
var key_data: [256]KeyInfo = [_]KeyInfo{.{}} ** 256;
var dims: @Vector(2, u32) = @Vector(2, u32){ 0, 0 };
var mouse: MouseData = .{};
comptime {
@export(setDims, .{ .name = "setDims", .linkage = .Strong });
@export(onScroll, .{ .name = "onScroll", .linkage = .Strong });
@export(onMove, .{ .name = "onMove", .linkage = .Strong });
@export(onClick, .{ .name = "onClick", .linkage = .Strong });
@export(onRightClick, .{ .name = "onRightClick", .linkage = .Strong });
@export(onKey, .{ .name = "onKey", .linkage = .Strong });
}
pub fn init(timestamp: f64) void {
time = timestamp;
}
pub fn frameStart(timestamp: f64) FrameInput {
const value = FrameInput{
.frame_id = frame_id,
.delta = @floatCast(f32, timestamp - time),
.screen_dims = dims,
.mouse = mouse,
};
time = timestamp;
frame_id += 1;
return value;
}
pub fn frameCleanup() void {
for (key_data) |*k| {
k.pressed = false;
}
mouse.scroll_dist = Vec2{ 0, 0 };
mouse.scroll_tick = @Vector(2, i32){ 0, 0 };
mouse.left_clicked = false;
mouse.right_clicked = false;
}
fn setDims(posX: u32, posY: u32) callconv(.C) void {
dims = @Vector(2, u32){ posX, posY };
}
fn onScroll(deltaX: f32, deltaY_: f32) callconv(.C) void {
// Y axis grows downwards on the web
const deltaY = -deltaY_;
mouse.scroll_dist += Vec2{ deltaX, deltaY };
const one: f32 = 1;
if (deltaX != 0) {
mouse.scroll_tick[0] += @floatToInt(i32, std.math.copysign(one, deltaX));
}
if (deltaY != 0) {
mouse.scroll_tick[1] += @floatToInt(i32, std.math.copysign(one, deltaY));
}
}
fn onMove(posX: f32, posY: f32) callconv(.C) void {
mouse.pos = Vec2{ posX, posY };
}
fn onClick(posX: f32, posY: f32) callconv(.C) void {
onMove(posX, posY);
mouse.left_clicked = true;
}
fn onRightClick(posX: f32, posY: f32) callconv(.C) void {
onMove(posX, posY);
mouse.right_clicked = true;
}
fn onKey(down: bool, code: u8) callconv(.C) void {
const key = &key_data[code];
key.pressed = down;
key.down = down;
}
pub const Timer = struct {
previous: f64,
pub fn init() @This() {
return .{ .previous = time };
}
pub fn elapsed(self: @This()) f32 {
return @floatCast(f32, time - self.previous);
}
pub fn lap(self: @This()) f32 {
const delta = self.elapsed();
self.previous = time;
return delta;
}
};
pub const KeyRow = struct {
keys: []const KeyCode,
leftX: i32,
};
const KeyInfo = struct {
pressed: bool = false,
down: bool = false,
};
pub const FrameInput = struct {
frame_id: u64,
delta: f32,
screen_dims: @Vector(2, u32),
mouse: MouseData,
pub fn key(self: *const @This(), code: KeyCode) KeyInfo {
_ = self;
return key_data[code.code()];
}
};
pub const MouseData = struct {
pos: Vec2 = Vec2{ 0, 0 },
scroll_dist: Vec2 = Vec2{ 0, 0 },
scroll_tick: @Vector(2, i32) = @Vector(2, i32){ 0, 0 },
left_clicked: bool = false,
right_clicked: bool = false,
};
pub const KeyCode = enum(u8) {
space = ' ',
comma = ',',
period = '.',
slash = '/',
digit0 = '0',
digit1,
digit2,
digit3,
digit4,
digit5,
digit6,
digit7,
digit8,
digit9,
semicolon = ';',
key_a = 'A',
key_b,
key_c,
key_d,
key_e,
key_f,
key_g,
key_h,
key_i,
key_j,
key_k,
key_l,
key_m,
key_n,
key_o,
key_p,
key_q,
key_r,
key_s,
key_t,
key_u,
key_v,
key_w,
key_x,
key_y,
key_z,
arrow_up = 128,
arrow_down,
arrow_left,
arrow_right,
pub fn code(self: @This()) u8 {
return @enumToInt(self);
}
}; | src/liu/gamescreen.zig |
const std = @import("../std.zig");
const builtin = std.builtin;
const fs = std.fs;
const File = std.fs.File;
test "openSelfExe" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
const self_exe_file = try std.fs.openSelfExe();
self_exe_file.close();
}
const FILE_LOCK_TEST_SLEEP_TIME = 5 * std.time.ns_per_ms;
test "open file with exclusive nonblocking lock twice" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
const dir = fs.cwd();
const filename = "file_nonblocking_lock_test.txt";
const file1 = try dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
defer file1.close();
const file2 = dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
std.debug.assert(std.meta.eql(file2, error.WouldBlock));
dir.deleteFile(filename) catch |err| switch (err) {
error.FileNotFound => {},
else => return err,
};
}
test "open file with lock twice, make sure it wasn't open at the same time" {
if (builtin.single_threaded) return error.SkipZigTest;
if (std.io.is_async) {
// This test starts its own threads and is not compatible with async I/O.
return error.SkipZigTest;
}
const filename = "file_lock_test.txt";
var contexts = [_]FileLockTestContext{
.{ .filename = filename, .create = true, .lock = .Exclusive },
.{ .filename = filename, .create = true, .lock = .Exclusive },
};
try run_lock_file_test(&contexts);
// Check for an error
var was_error = false;
for (contexts) |context, idx| {
if (context.err) |err| {
was_error = true;
std.debug.warn("\nError in context {}: {}\n", .{ idx, err });
}
}
if (was_error) builtin.panic("There was an error in contexts", null);
std.debug.assert(!contexts[0].overlaps(&contexts[1]));
fs.cwd().deleteFile(filename) catch |err| switch (err) {
error.FileNotFound => {},
else => return err,
};
}
test "create file, lock and read from multiple process at once" {
if (builtin.single_threaded) return error.SkipZigTest;
if (std.io.is_async) {
// This test starts its own threads and is not compatible with async I/O.
return error.SkipZigTest;
}
if (true) {
// https://github.com/ziglang/zig/issues/5006
return error.SkipZigTest;
}
const filename = "file_read_lock_test.txt";
const filedata = "Hello, world!\n";
try fs.cwd().writeFile(filename, filedata);
var contexts = [_]FileLockTestContext{
.{ .filename = filename, .create = false, .lock = .Shared },
.{ .filename = filename, .create = false, .lock = .Shared },
.{ .filename = filename, .create = false, .lock = .Exclusive },
};
try run_lock_file_test(&contexts);
var was_error = false;
for (contexts) |context, idx| {
if (context.err) |err| {
was_error = true;
std.debug.warn("\nError in context {}: {}\n", .{ idx, err });
}
}
if (was_error) builtin.panic("There was an error in contexts", null);
std.debug.assert(contexts[0].overlaps(&contexts[1]));
std.debug.assert(!contexts[2].overlaps(&contexts[0]));
std.debug.assert(!contexts[2].overlaps(&contexts[1]));
if (contexts[0].bytes_read.? != filedata.len) {
std.debug.warn("\n bytes_read: {}, expected: {} \n", .{ contexts[0].bytes_read, filedata.len });
}
std.debug.assert(contexts[0].bytes_read.? == filedata.len);
std.debug.assert(contexts[1].bytes_read.? == filedata.len);
fs.cwd().deleteFile(filename) catch |err| switch (err) {
error.FileNotFound => {},
else => return err,
};
}
test "open file with exclusive nonblocking lock twice (absolute paths)" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
const allocator = std.testing.allocator;
const file_paths: [1][]const u8 = .{"zig-test-absolute-paths.txt"};
const filename = try fs.path.resolve(allocator, &file_paths);
defer allocator.free(filename);
const file1 = try fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
const file2 = fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
file1.close();
std.testing.expectError(error.WouldBlock, file2);
try fs.deleteFileAbsolute(filename);
}
const FileLockTestContext = struct {
filename: []const u8,
pid: if (builtin.os.tag == .windows) ?void else ?std.os.pid_t = null,
// use file.createFile
create: bool,
// the type of lock to use
lock: File.Lock,
// Output variables
err: ?(File.OpenError || std.os.ReadError) = null,
start_time: i64 = 0,
end_time: i64 = 0,
bytes_read: ?usize = null,
fn overlaps(self: *const @This(), other: *const @This()) bool {
return (self.start_time < other.end_time) and (self.end_time > other.start_time);
}
fn run(ctx: *@This()) void {
var file: File = undefined;
if (ctx.create) {
file = fs.cwd().createFile(ctx.filename, .{ .lock = ctx.lock }) catch |err| {
ctx.err = err;
return;
};
} else {
file = fs.cwd().openFile(ctx.filename, .{ .lock = ctx.lock }) catch |err| {
ctx.err = err;
return;
};
}
defer file.close();
ctx.start_time = std.time.milliTimestamp();
if (!ctx.create) {
var buffer: [100]u8 = undefined;
ctx.bytes_read = 0;
while (true) {
const amt = file.read(buffer[0..]) catch |err| {
ctx.err = err;
return;
};
if (amt == 0) break;
ctx.bytes_read.? += amt;
}
}
std.time.sleep(FILE_LOCK_TEST_SLEEP_TIME);
ctx.end_time = std.time.milliTimestamp();
}
};
fn run_lock_file_test(contexts: []FileLockTestContext) !void {
var threads = std.ArrayList(*std.Thread).init(std.testing.allocator);
defer {
for (threads.items) |thread| {
thread.wait();
}
threads.deinit();
}
for (contexts) |*ctx, idx| {
try threads.append(try std.Thread.spawn(ctx, FileLockTestContext.run));
}
} | lib/std/fs/test.zig |
const std = @import("std");
const testing = std.testing;
const zupnp = @import("zupnp");
const SUT = struct {
const one = "one";
const two = "two";
const three = "three";
const contents = one ++ two ++ three;
const content_type = "test/whatever";
const dest = "/endpoint";
const Endpoint = struct {
pub fn get(_: *const zupnp.web.ServerGetRequest) zupnp.web.ServerResponse {
return zupnp.web.ServerResponse.contents(.{ .contents = contents, .content_type = content_type });
}
};
lib: zupnp.ZUPnP = undefined,
url: [:0]const u8 = undefined,
fn init(self: *SUT) !void {
self.lib = try zupnp.ZUPnP.init(testing.allocator, .{});
_ = try self.lib.server.createEndpoint(Endpoint, {}, dest);
try self.lib.server.start();
self.url = try std.fmt.allocPrintZ(testing.allocator, "{s}{s}", .{self.lib.server.base_url, dest});
}
fn deinit(self: *SUT) void {
testing.allocator.free(self.url);
self.lib.deinit();
}
};
test "GET request returns code 200 with contents" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var response = try zupnp.web.request(.GET, sut.url, .{});
try testing.expectEqual(@as(c_int, 200), response.http_status);
try testing.expectEqualStrings(SUT.content_type, response.content_type.?);
const contents = try response.readAll(testing.allocator);
defer testing.allocator.free(contents);
try testing.expectEqualStrings(SUT.contents, contents);
}
test "HEAD request returns code 200 with no contents" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var response = try zupnp.web.request(.HEAD, sut.url, .{});
try testing.expectEqual(@as(c_int, 200), response.http_status);
try testing.expectEqualStrings(SUT.content_type, response.content_type.?);
const contents = try response.readAll(testing.allocator);
defer testing.allocator.free(contents);
try testing.expectEqualStrings("", contents);
}
test "unhandled requests return server error codes" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
inline for (.{
.{.POST, 500},
.{.PUT, 501},
.{.DELETE, 500}
}) |requestAndCode| {
var response = try zupnp.web.request(requestAndCode.@"0", sut.url, .{});
try testing.expectEqual(@as(c_int, requestAndCode.@"1"), response.http_status);
}
}
test "GET request with chunks gets individual parts of contents" {
var sut = SUT {};
try sut.init();
defer sut.deinit();
var request = try zupnp.web.request(.GET, sut.url, .{});
try testing.expectEqual(@as(c_int, 200), request.http_status);
try testing.expectEqualStrings(SUT.content_type, request.content_type.?);
try testing.expectEqual(@as(u32, SUT.contents.len), request.content_length.?);
var buf: [8]u8 = undefined;
inline for (.{SUT.one, SUT.two, SUT.three}) |part| {
try testing.expectEqualStrings(part, (try request.readChunk(buf[0..part.len])).?);
}
try testing.expectEqual(@as(?[]const u8, null), try request.readChunk(&buf));
} | test/web/test_get_requests.zig |
const AllImageFormats = @import("formats/all.zig");
const Allocator = std.mem.Allocator;
const Color = color.Color;
const ColorStorage = color.ColorStorage;
const FormatInterface = @import("format_interface.zig").FormatInterface;
const PixelFormat = @import("pixel_format.zig").PixelFormat;
const color = @import("color.zig");
const errors = @import("errors.zig");
const io = std.io;
const std = @import("std");
pub const ImageFormat = enum {
Bmp,
Pbm,
Pcx,
Pgm,
Png,
Ppm,
Raw,
Tga,
};
pub const ImageReader = io.StreamSource.Reader;
pub const ImageSeekStream = io.StreamSource.SeekableStream;
pub const ImageWriterStream = io.StreamSource.Writer;
pub const ImageEncoderOptions = AllImageFormats.ImageEncoderOptions;
pub const ImageSaveInfo = struct {
width: usize,
height: usize,
encoder_options: ImageEncoderOptions,
};
pub const ImageInfo = struct {
width: usize = 0,
height: usize = 0,
pixel_format: PixelFormat = undefined,
};
/// Format-independant image
pub const Image = struct {
allocator: *Allocator = undefined,
width: usize = 0,
height: usize = 0,
pixels: ?ColorStorage = null,
pixel_format: PixelFormat = undefined,
image_format: ImageFormat = undefined,
const Self = @This();
const FormatInteraceFnType = fn () FormatInterface;
const allInterfaceFuncs = comptime blk: {
const allFormatDecls = std.meta.declarations(AllImageFormats);
var result: [allFormatDecls.len]FormatInteraceFnType = undefined;
var index: usize = 0;
for (allFormatDecls) |decl| {
switch (decl.data) {
.Type => |entryType| {
const entryTypeInfo = @typeInfo(entryType);
if (entryTypeInfo == .Struct) {
for (entryTypeInfo.Struct.decls) |structEntry| {
if (std.mem.eql(u8, structEntry.name, "formatInterface")) {
result[index] = @field(entryType, structEntry.name);
index += 1;
break;
}
}
}
},
else => {},
}
}
break :blk result[0..index];
};
pub fn init(allocator: *Allocator) Self {
return Self{
.allocator = allocator,
};
}
pub fn deinit(self: Self) void {
if (self.pixels) |pixels| {
pixels.deinit(self.allocator);
}
}
pub fn fromFilePath(allocator: *Allocator, file_path: []const u8) !Self {
const cwd = std.fs.cwd();
var resolvedPath = try std.fs.path.resolve(allocator, &[_][]const u8{file_path});
defer allocator.free(resolvedPath);
var file = try cwd.openFile(resolvedPath, .{});
defer file.close();
return fromFile(allocator, &file);
}
pub fn fromFile(allocator: *Allocator, file: *std.fs.File) !Self {
var result = init(allocator);
var stream_source = io.StreamSource{ .file = file.* };
try result.internalRead(allocator, stream_source.reader(), stream_source.seekableStream());
return result;
}
pub fn fromMemory(allocator: *Allocator, buffer: []const u8) !Image {
var result = init(allocator);
var stream_source = io.StreamSource{ .const_buffer = io.fixedBufferStream(buffer) };
try result.internalRead(allocator, stream_source.reader(), stream_source.seekableStream());
return result;
}
pub fn create(allocator: *Allocator, width: usize, height: usize, pixel_format: PixelFormat, image_format: ImageFormat) !Self {
var result = Self{
.allocator = allocator,
.width = width,
.height = height,
.pixel_format = pixel_format,
.image_format = image_format,
.pixels = try ColorStorage.init(allocator, pixel_format, width * height),
};
return result;
}
pub fn writeToFilePath(self: Self, file_path: []const u8, image_format: ImageFormat, encoder_options: ImageEncoderOptions) !void {
if (self.pixels == null) {
return error.NoPixelData;
}
const cwd = std.fs.cwd();
var resolved_path = try std.fs.path.resolve(self.allocator, &[_][]const u8{file_path});
defer self.allocator.free(resolved_path);
var file = try cwd.createFile(resolved_path, .{});
defer file.close();
try self.writeToFile(&file, image_format, encoder_options);
}
pub fn writeToFile(self: Self, file: *std.fs.File, image_format: ImageFormat, encoder_options: ImageEncoderOptions) !void {
if (self.pixels == null) {
return error.NoPixelData;
}
var image_save_info = ImageSaveInfo{
.width = self.width,
.height = self.height,
.encoder_options = encoder_options,
};
var format_interface = try findImageInterfaceFromImageFormat(image_format);
var stream_source = io.StreamSource{ .file = file.* };
if (self.pixels) |pixels| {
try format_interface.writeForImage(self.allocator, stream_source.writer(), stream_source.seekableStream(), pixels, image_save_info);
}
}
pub fn writeToMemory(self: Self, write_buffer: []u8, image_format: ImageFormat, encoder_options: ImageEncoderOptions) ![]u8 {
if (self.pixels == null) {
return error.NoPixelData;
}
var image_save_info = ImageSaveInfo{
.width = self.width,
.height = self.height,
.encoder_options = encoder_options,
};
var format_interface = try findImageInterfaceFromImageFormat(image_format);
var stream_source = io.StreamSource{ .buffer = std.io.fixedBufferStream(write_buffer) };
if (self.pixels) |pixels| {
try format_interface.writeForImage(self.allocator, stream_source.writer(), stream_source.seekableStream(), pixels, image_save_info);
}
return stream_source.buffer.getWritten();
}
pub fn iterator(self: Self) color.ColorStorageIterator {
if (self.pixels) |*pixels| {
return color.ColorStorageIterator.init(pixels);
}
return color.ColorStorageIterator.initNull();
}
fn internalRead(self: *Self, allocator: *Allocator, reader: ImageReader, seekStream: ImageSeekStream) !void {
var formatInterface = try findImageInterfaceFromStream(reader, seekStream);
self.image_format = formatInterface.format();
try seekStream.seekTo(0);
const imageInfo = try formatInterface.readForImage(allocator, reader, seekStream, &self.pixels);
self.width = imageInfo.width;
self.height = imageInfo.height;
self.pixel_format = imageInfo.pixel_format;
}
fn findImageInterfaceFromStream(reader: ImageReader, seekStream: ImageSeekStream) !FormatInterface {
for (allInterfaceFuncs) |intefaceFn| {
const formatInterface = intefaceFn();
try seekStream.seekTo(0);
const found = try formatInterface.formatDetect(reader, seekStream);
if (found) {
return formatInterface;
}
}
return errors.ImageFormatInvalid;
}
fn findImageInterfaceFromImageFormat(image_format: ImageFormat) !FormatInterface {
for (allInterfaceFuncs) |intefaceFn| {
const formatInterface = intefaceFn();
if (formatInterface.format() == image_format) {
return formatInterface;
}
}
return errors.ImageFormatInvalid;
}
}; | src/image.zig |
const std = @import("std");
const version = @import("version");
const tar = @import("tar");
const glob = @import("glob");
const zzz = @import("zzz");
const Dependency = @import("Dependency.zig");
usingnamespace @import("common.zig");
const Self = @This();
const Allocator = std.mem.Allocator;
arena: std.heap.ArenaAllocator,
name: []const u8,
version: version.Semver,
root: ?[]const u8,
files: std.ArrayList([]const u8),
deps: []Dependency,
build_deps: []Dependency,
// meta info
author: ?[]const u8,
description: ?[]const u8,
license: ?[]const u8,
homepage_url: ?[]const u8,
source_url: ?[]const u8,
tags: std.ArrayList([]const u8),
pub fn init(
allocator: *Allocator,
name: []const u8,
ver: version.Semver,
deps: []Dependency,
build_deps: []Dependency,
) Self {
return Self{
.arena = std.heap.ArenaAllocator.init(allocator),
.name = name,
.version = ver,
.deps = deps,
.build_deps = build_deps,
.files = std.ArrayList([]const u8).init(allocator),
.tags = std.ArrayList([]const u8).init(allocator),
.root = null,
.author = null,
.description = null,
.license = null,
.homepage_url = null,
.source_url = null,
};
}
pub fn deinit(self: *Self) void {
self.tags.deinit();
self.files.deinit();
self.arena.deinit();
}
pub fn fillFromZNode(
self: *Self,
node: *zzz.ZNode,
) !void {
if (zFindChild(node, "files")) |files| {
var it = ZChildIterator.init(files);
while (it.next()) |path| try self.files.append(try zGetString(path));
}
if (zFindChild(node, "tags")) |tags| {
var it = ZChildIterator.init(tags);
while (it.next()) |tag| try self.tags.append(try zGetString(tag));
}
inline for (std.meta.fields(Self)) |field| {
if (@TypeOf(@field(self, field.name)) == ?[]const u8) {
@field(self, field.name) = try zFindString(node, field.name);
}
}
}
fn createManifest(self: *Self, tree: *zzz.ZTree(1, 1000), ver_str: []const u8) !void {
var root = try tree.addNode(null, .Null);
try zPutKeyString(tree, root, "name", self.name);
try zPutKeyString(tree, root, "version", ver_str);
inline for (std.meta.fields(Self)) |field| {
if (@TypeOf(@field(self, field.name)) == ?[]const u8) {
if (@field(self, field.name)) |value| {
try zPutKeyString(tree, root, field.name, value);
} else if (std.mem.eql(u8, field.name, "root")) {
try zPutKeyString(tree, root, field.name, "src/main.zig");
}
}
}
if (self.tags.items.len > 0) {
var tags = try tree.addNode(root, .{ .String = "tags" });
for (self.tags.items) |tag| _ = try tree.addNode(tags, .{ .String = tag });
}
if (self.deps.len > 0) {
var deps = try tree.addNode(root, .{ .String = "deps" });
for (self.deps) |dep| try dep.addToZNode(&self.arena, tree, deps, true);
}
if (self.build_deps.len > 0) {
var build_deps = try tree.addNode(root, .{ .String = "build_deps" });
for (self.build_deps) |dep| try dep.addToZNode(&self.arena, tree, build_deps, true);
}
}
pub fn bundle(self: *Self, root: std.fs.Dir, output_dir: std.fs.Dir) !void {
var ver_buf: [1024]u8 = undefined;
var ver_str = std.io.fixedBufferStream(&ver_buf);
try ver_str.writer().print("{}", .{self.version});
var buf: [std.mem.page_size]u8 = undefined;
var stream = std.io.fixedBufferStream(&buf);
try stream.writer().print("{s}-{s}.tar", .{
self.name,
ver_str.getWritten(),
});
const file = try output_dir.createFile(stream.getWritten(), .{
.truncate = true,
.read = true,
});
errdefer output_dir.deleteFile(stream.getWritten()) catch {};
defer file.close();
var tarball = tar.builder(self.arena.child_allocator, file.writer());
defer {
tarball.finish() catch {};
tarball.deinit();
}
var fifo = std.fifo.LinearFifo(u8, .Dynamic).init(self.arena.child_allocator);
defer fifo.deinit();
var manifest = zzz.ZTree(1, 1000){};
try self.createManifest(&manifest, ver_str.getWritten());
try manifest.rootSlice()[0].stringify(fifo.writer());
try fifo.writer().writeByte('\n');
try tarball.addSlice(fifo.readableSlice(0), "manifest.zzz");
if (self.root) |root_file| {
tarball.addFile(root, "pkg", root_file) catch |err| {
if (err == error.FileNotFound) {
std.log.err("{s}'s root is declared as {s}, but it does not exist", .{
self.name,
root_file,
});
return error.Explained;
} else return err;
};
} else {
tarball.addFile(root, "pkg", "src/main.zig") catch |err| {
if (err == error.FileNotFound) {
std.log.err("there's no src/main.zig, did you forget to declare a {s}'s root file in gyro.zzz?", .{
self.name,
});
return error.Explained;
} else return err;
};
}
for (self.files.items) |pattern| {
var dir = try root.openDir(".", .{ .iterate = true, .access_sub_paths = true });
defer dir.close();
var it = try glob.Iterator.init(self.arena.child_allocator, dir, pattern);
defer it.deinit();
while (try it.next()) |subpath| {
tarball.addFile(dir, "pkg", subpath) catch |err| {
return if (err == error.FileNotFound) blk: {
std.log.err("file pattern '{s}' wants path '{s}', but it doesn't exist", .{
pattern,
subpath,
});
break :blk error.Explained;
} else err;
};
}
}
} | src/Package.zig |
const std = @import("std");
const mach = @import("mach");
const gpu = @import("gpu");
const App = mach.App(*FrameParams, .{});
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var allocator = gpa.allocator();
const ctx = try allocator.create(FrameParams);
var app = try App.init(allocator, ctx, .{});
const vs_module = app.device.createShaderModule(&.{
.label = "my vertex shader",
.code = .{ .wgsl = @embedFile("vert.wgsl") },
});
const fs_module = app.device.createShaderModule(&.{
.label = "my fragment shader",
.code = .{ .wgsl = @embedFile("frag.wgsl") },
});
// Fragment state
const blend = gpu.BlendState{
.color = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .one,
},
.alpha = .{
.operation = .add,
.src_factor = .one,
.dst_factor = .one,
},
};
const color_target = gpu.ColorTargetState{
.format = app.swap_chain_format,
.blend = &blend,
.write_mask = gpu.ColorWriteMask.all,
};
const fragment = gpu.FragmentState{
.module = fs_module,
.entry_point = "main",
.targets = &.{color_target},
.constants = null,
};
const pipeline_descriptor = gpu.RenderPipeline.Descriptor{
.fragment = &fragment,
.layout = null,
.depth_stencil = null,
.vertex = .{
.module = vs_module,
.entry_point = "main",
.buffers = null,
},
.multisample = .{
.count = 1,
.mask = 0xFFFFFFFF,
.alpha_to_coverage_enabled = false,
},
.primitive = .{
.front_face = .ccw,
.cull_mode = .none,
.topology = .triangle_list,
.strip_index_format = .none,
},
};
ctx.* = FrameParams{
.pipeline = app.device.createRenderPipeline(&pipeline_descriptor),
.queue = app.device.getQueue(),
};
vs_module.release();
fs_module.release();
try app.run(.{ .frame = frame });
}
const FrameParams = struct {
pipeline: gpu.RenderPipeline,
queue: gpu.Queue,
};
fn frame(app: *App, params: *FrameParams) !void {
const back_buffer_view = app.swap_chain.?.getCurrentTextureView();
const color_attachment = gpu.RenderPassColorAttachment{
.view = back_buffer_view,
.resolve_target = null,
.clear_value = std.mem.zeroes(gpu.Color),
.load_op = .clear,
.store_op = .store,
};
const encoder = app.device.createCommandEncoder(null);
const render_pass_info = gpu.RenderPassEncoder.Descriptor{
.color_attachments = &.{color_attachment},
.depth_stencil_attachment = null,
};
const pass = encoder.beginRenderPass(&render_pass_info);
pass.setPipeline(params.pipeline);
pass.draw(3, 1, 0, 0);
pass.end();
pass.release();
var command = encoder.finish(null);
encoder.release();
params.queue.submit(&.{command});
command.release();
app.swap_chain.?.present();
back_buffer_view.release();
} | examples/main.zig |
usingnamespace @import("../utils/bitboard.zig");
const console = @import("../utils/console.zig");
const masks = @import("masks.zig");
const Color = @import("../types/enums.zig").Color;
const Square = @import("../types/enums.zig").Square;
const File = @import("../types/enums.zig").File;
const Piece = @import("../types/Piece.zig");
pub const north_bb = comptime northBB();
pub const south_bb = comptime southBB();
pub const east_bb = comptime eastBB();
pub const west_bb = comptime westBB();
pub const north_west_bb = comptime northWestBB();
pub const south_west_bb = comptime southWestBB();
pub const north_east_bb = comptime northEastBB();
pub const south_east_bb = comptime southEastBB();
const pawn_attacks_bb = comptime pawnAttacksBB();
const knight_attacks_bb = comptime knightAttacksBB();
const bishop_pseudo_attacks_bb = comptime bishopPseudoAttacksBB();
const rook_pseudo_attacks_bb = comptime rookPseudoAttacksBB();
const queen_pseudo_attacks_bb = comptime queenPseudoAttacksBB();
const king_attacks_bb = comptime kingAttacksBB();
pub fn pawnAttacks(square: Square, color: Color) u64 {
return pawn_attacks_bb[@enumToInt(color)][@enumToInt(square)];
}
pub fn nonPawnAttacks(piece_type: Piece.Type, square: Square, occupancy_bb: u64) u64 {
return switch (piece_type) {
.Knight => return knightAttacks(square),
.Bishop => return bishopAttacks(square, occupancy_bb),
.Rook => return rookAttacks(square, occupancy_bb),
.Queen => return queenAttacks(square, occupancy_bb),
.King => return kingAttacks(square),
else => unreachable,
};
}
pub fn knightAttacks(square: Square) u64 {
return knight_attacks_bb[@enumToInt(square)];
}
pub fn bishopAttacks(square: Square, occupancy_bb: u64) u64 {
const square_v = @enumToInt(square);
const nw_blockers = (north_west_bb[square_v] & occupancy_bb) | Square.A8.toBitboard();
const ne_blockers = (north_east_bb[square_v] & occupancy_bb) | Square.H8.toBitboard();
const sw_blockers = (south_west_bb[square_v] & occupancy_bb) | Square.A1.toBitboard();
const se_blockers = (south_east_bb[square_v] & occupancy_bb) | Square.H1.toBitboard();
return bishop_pseudo_attacks_bb[square_v] ^
north_west_bb[bitscanForward(nw_blockers)] ^
north_east_bb[bitscanForward(ne_blockers)] ^
south_west_bb[bitscanReverse(sw_blockers)] ^
south_east_bb[bitscanReverse(se_blockers)];
}
pub fn rookAttacks(square: Square, occupancy_bb: u64) u64 {
const square_v = @enumToInt(square);
const n_blockers = (north_bb[square_v] & occupancy_bb) | Square.H8.toBitboard();
const s_blockers = (south_bb[square_v] & occupancy_bb) | Square.A1.toBitboard();
const w_blockers = (west_bb[square_v] & occupancy_bb) | Square.A1.toBitboard();
const e_blockers = (east_bb[square_v] & occupancy_bb) | Square.H8.toBitboard();
return rook_pseudo_attacks_bb[square_v] ^
north_bb[bitscanForward(n_blockers)] ^
south_bb[bitscanReverse(s_blockers)] ^
west_bb[bitscanReverse(w_blockers)] ^
east_bb[bitscanForward(e_blockers)];
}
pub fn queenAttacks(square: Square, occupancy_bb: u64) u64 {
return rookAttacks(square, occupancy_bb) | bishopAttacks(square, occupancy_bb);
}
pub fn kingAttacks(square: Square) u64 {
return king_attacks_bb[@enumToInt(square)];
}
fn northBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A1);
while (square <= @enumToInt(Square.H7)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square + 8;
while (attack_sq <= @enumToInt(Square.H8)) : (attack_sq += 8) {
bb |= toBitboard(@intCast(u6, attack_sq));
}
attacks[square] = bb;
}
return attacks;
}
fn southBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A2);
while (square <= @enumToInt(Square.H8)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square - 8;
while (attack_sq >= @enumToInt(Square.A1)) : (attack_sq -= 8) {
bb |= toBitboard(@intCast(u6, attack_sq));
}
attacks[square] = bb;
}
return attacks;
}
fn eastBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A1);
while (square <= @enumToInt(Square.G8)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square + 1;
while (attack_sq <= @enumToInt(Square.H8)) : (attack_sq += 1) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.A)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn westBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.B1);
while (square <= @enumToInt(Square.H8)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square - 1;
while (attack_sq >= @enumToInt(Square.A1)) : (attack_sq -= 1) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.H)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn northWestBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A1);
while (square <= @enumToInt(Square.H7)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square + 7;
while (attack_sq <= @enumToInt(Square.H8)) : (attack_sq += 7) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.H)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn southWestBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.B2);
while (square <= @enumToInt(Square.H8)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square - 9;
while (attack_sq >= @enumToInt(Square.A1)) : (attack_sq -= 9) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.H)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn northEastBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A1);
while (square <= @enumToInt(Square.G7)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square + 9;
while (attack_sq <= @enumToInt(Square.H8)) : (attack_sq += 9) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.A)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn southEastBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
var square = @enumToInt(Square.A2);
while (square <= @enumToInt(Square.H8)) : (square += 1) {
var bb: u64 = 0;
var attack_sq: i32 = square - 7;
while (attack_sq >= @enumToInt(Square.A1)) : (attack_sq -= 7) {
const bb_tmp = toBitboard(@intCast(u6, attack_sq));
if ((bb_tmp & masks.file_masks[@enumToInt(File.A)]) != 0) {
break;
}
bb |= bb_tmp;
}
attacks[square] = bb;
}
return attacks;
}
fn pawnAttacksBB() [2][64]u64 {
var attacks: [2][64]u64 = [2][64]u64{
[_]u64{0} ** 64,
[_]u64{0} ** 64,
};
for (Square.all) |square| {
const square_v = @enumToInt(square);
if (square_v <= @enumToInt(Square.H7)) {
attacks[@enumToInt(Color.White)][square_v] |= toBitboard(@intCast(u6, square_v + 7)) & ~masks.file_masks[@enumToInt(File.H)];
}
if (square_v <= @enumToInt(Square.G7)) {
attacks[@enumToInt(Color.White)][square_v] |= toBitboard(@intCast(u6, square_v + 9)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v >= @enumToInt(Square.A2)) {
attacks[@enumToInt(Color.Black)][square_v] |= toBitboard(@intCast(u6, square_v - 7)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v >= @enumToInt(Square.B2)) {
attacks[@enumToInt(Color.Black)][square_v] |= toBitboard(@intCast(u6, square_v - 9)) & ~masks.file_masks[@enumToInt(File.H)];
}
}
return attacks;
}
fn knightAttacksBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
for (Square.all) |square| {
const square_v = @enumToInt(square);
if (square_v <= @enumToInt(Square.G6)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 17)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v <= @enumToInt(Square.H6)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 15)) & ~masks.file_masks[@enumToInt(File.H)];
}
if (square_v >= @enumToInt(Square.B3)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 17)) & ~masks.file_masks[@enumToInt(File.H)];
}
if (square_v >= @enumToInt(Square.A3)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 15)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v <= @enumToInt(Square.F7)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 10)) & ~(masks.file_masks[@enumToInt(File.A)] | masks.file_masks[@enumToInt(File.B)]);
}
if (square_v <= @enumToInt(Square.H7)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 6)) & ~(masks.file_masks[@enumToInt(File.H)] | masks.file_masks[@enumToInt(File.G)]);
}
if (square_v >= @enumToInt(Square.C2)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 10)) & ~(masks.file_masks[@enumToInt(File.H)] | masks.file_masks[@enumToInt(File.G)]);
}
if (square_v >= @enumToInt(Square.A2)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 6)) & ~(masks.file_masks[@enumToInt(File.A)] | masks.file_masks[@enumToInt(File.B)]);
}
}
return attacks;
}
fn kingAttacksBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
for (Square.all) |square| {
const square_v = @enumToInt(square);
if (square_v <= @enumToInt(Square.G7)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 9)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v <= @enumToInt(Square.H7)) {
attacks[square_v] |= @intCast(u64, 1) << @intCast(u6, square_v + 8);
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 7)) & ~masks.file_masks[@enumToInt(File.H)];
}
if (square_v <= @enumToInt(Square.G8)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v + 1)) & ~masks.file_masks[@enumToInt(File.A)];
}
if (square_v >= @enumToInt(Square.B1)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 1)) & ~masks.file_masks[@enumToInt(File.H)];
}
if (square_v >= @enumToInt(Square.A2)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 7)) & ~masks.file_masks[@enumToInt(File.A)];
attacks[square_v] |= @intCast(u64, 1) << @intCast(u6, square_v - 8);
}
if (square_v >= @enumToInt(Square.B2)) {
attacks[square_v] |= toBitboard(@intCast(u6, square_v - 9)) & ~masks.file_masks[@enumToInt(File.H)];
}
}
return attacks;
}
fn bishopPseudoAttacksBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
for (Square.all) |square| {
const square_v = @enumToInt(square);
attacks[square_v] =
north_east_bb[square_v] |
north_west_bb[square_v] |
south_east_bb[square_v] |
south_west_bb[square_v];
}
return attacks;
}
fn rookPseudoAttacksBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
for (Square.all) |square| {
const square_v = @enumToInt(square);
attacks[square_v] =
north_bb[square_v] |
south_bb[square_v] |
east_bb[square_v] |
west_bb[square_v];
}
return attacks;
}
fn queenPseudoAttacksBB() [64]u64 {
var attacks: [64]u64 = [_]u64{0} ** 64;
for (Square.all) |square| {
const square_v = @enumToInt(square);
attacks[square_v] =
north_bb[square_v] |
south_bb[square_v] |
east_bb[square_v] |
west_bb[square_v] |
north_east_bb[square_v] |
north_west_bb[square_v] |
south_east_bb[square_v] |
south_west_bb[square_v];
}
return attacks;
} | src/bitboards/attacks.zig |
const std = @import("std");
const string = []const u8;
const List = std.ArrayList(string);
const extras = @import("extras");
const range = @import("range").range;
var singles: std.StringArrayHashMap(string) = undefined;
var multis: std.StringArrayHashMap(List) = undefined;
pub fn init(alloc: std.mem.Allocator) void {
singles = std.StringArrayHashMap(string).init(alloc);
multis = std.StringArrayHashMap(List).init(alloc);
}
pub fn deinit() void {
singles.deinit();
multis.deinit();
}
pub fn addSingle(name: string) !void {
try singles.putNoClobber(name, "");
}
pub fn addMulti(name: string) !void {
try multis.putNoClobber(name, List.init(multis.allocator));
}
pub const FlagDashKind = enum {
single,
double,
pub fn hypen(self: FlagDashKind) string {
return switch (self) {
.single => "-",
.double => "--",
};
}
};
pub fn parse(k: FlagDashKind) !std.process.ArgIterator {
const dash = k.hypen();
var argiter = std.process.args();
defer argiter.deinit();
var argi: usize = 0;
blk: while (argiter.next()) |item| : (argi += 1) {
const data = item;
if (argi == 0) continue;
const name = extras.trimPrefix(data, dash);
if (data.len == name.len) return error.BadFlag;
for (singles.keys()) |jtem| {
if (std.mem.eql(u8, name, jtem)) {
const value = argiter.next().?;
try singles.put(name, value);
continue :blk;
}
}
for (multis.keys()) |jtem| {
if (std.mem.eql(u8, name, jtem)) {
const value = argiter.next().?;
try multis.getEntry(name).?.value_ptr.append(value);
continue :blk;
}
}
std.log.err("Unrecognized argument: {s}{s}", .{ dash, name });
std.os.exit(1);
}
return argiter;
}
pub fn parseEnv() !void {
const alloc = singles.allocator;
for (singles.keys()) |jtem| {
const u = try fixNameForEnv(alloc, jtem);
defer alloc.free(u);
if (std.os.getenv(u)) |value| {
try singles.put(jtem, value);
}
}
for (multis.keys()) |jtem| {
const e = multis.getEntry(jtem).?;
var n: usize = 1;
while (true) : (n += 1) {
const u = try fixNameForEnv(alloc, e.key_ptr.*);
defer alloc.free(u);
const k = try std.fmt.allocPrint(alloc, "{s}_{d}", .{ u, n });
defer alloc.free(k);
if (std.os.getenv(k)) |value| {
try e.value_ptr.append(value);
continue;
}
break;
}
}
}
fn fixNameForEnv(alloc: std.mem.Allocator, input: string) !string {
var ret = try extras.asciiUpper(alloc, input);
for (range(ret.len)) |_, i| {
if (ret[i] == '-') {
ret[i] = '_';
}
}
return ret;
}
pub fn getSingle(name: string) ?string {
const x = singles.get(name).?;
return if (x.len > 0) x else null;
}
pub fn getMulti(name: string) ?[]const string {
const x = multis.get(name).?.toOwnedSlice();
return if (x.len > 0) x else null;
} | src/lib.zig |
pub usingnamespace @import("wrapper.zig");
pub const struct___sbuf = extern struct {
_base: [*c]u8,
_size: c_int,
};
pub const FILE = extern struct {
_p: [*c]u8,
_r: c_int,
_w: c_int,
_flags: c_short,
_file: c_short,
_bf: struct___sbuf,
_lbfsize: c_int,
_cookie: ?*c_void,
_close: ?fn (?*c_void) callconv(.C) c_int,
_read: ?fn (?*c_void, [*c]u8, c_int) callconv(.C) c_int,
// _seek: ?fn (?*c_void, fpos_t, c_int) callconv(.C) fpos_t,
_write: ?fn (?*c_void, [*c]const u8, c_int) callconv(.C) c_int,
_ub: struct___sbuf,
_extra: ?*@Type(.Opaque),
_ur: c_int,
_ubuf: [3]u8,
_nbuf: [1]u8,
_lb: struct___sbuf,
_blksize: c_int,
// _offset: fpos_t,
};
pub const struct___va_list_tag = extern struct {
gp_offset: c_uint,
fp_offset: c_uint,
overflow_arg_area: ?*c_void,
reg_save_area: ?*c_void,
};
pub const struct_ImGuiStoragePair = extern struct {
key: ImGuiID,
unnamed_0: extern union {
val_i: c_int,
val_f: f32,
val_p: ?*c_void,
},
};
pub const ImGuiStoragePair = struct_ImGuiStoragePair;
pub const struct_ImGuiTextRange = extern struct {
b: [*c]const u8,
e: [*c]const u8,
};
pub const ImGuiTextRange = struct_ImGuiTextRange;
pub const struct_ImGuiViewportP = extern struct {
_ImGuiViewport: ImGuiViewport,
Idx: c_int,
LastFrameActive: c_int,
LastFrameDrawLists: [2]c_int,
LastFrontMostStampCount: c_int,
LastNameHash: ImGuiID,
LastPos: ImVec2,
Alpha: f32,
LastAlpha: f32,
PlatformMonitor: c_short,
PlatformWindowCreated: bool,
Window: ?*ImGuiWindow,
DrawLists: [2][*c]ImDrawList,
DrawDataP: ImDrawData,
DrawDataBuilder: ImDrawDataBuilder,
LastPlatformPos: ImVec2,
LastPlatformSize: ImVec2,
LastRendererSize: ImVec2,
CurrWorkOffsetMin: ImVec2,
CurrWorkOffsetMax: ImVec2,
};
pub const ImGuiViewportP = struct_ImGuiViewportP;
pub const struct_ImGuiPtrOrIndex = extern struct {
Ptr: ?*c_void,
Index: c_int,
};
pub const ImGuiPtrOrIndex = struct_ImGuiPtrOrIndex;
pub const struct_ImGuiShrinkWidthItem = extern struct {
Index: c_int,
Width: f32,
};
pub const ImGuiShrinkWidthItem = struct_ImGuiShrinkWidthItem;
pub const struct_ImGuiDataTypeTempStorage = extern struct {
Data: [8]ImU8,
};
pub const ImGuiDataTypeTempStorage = struct_ImGuiDataTypeTempStorage;
pub const struct_ImVec2ih = extern struct {
x: c_short,
y: c_short,
};
pub const ImVec2ih = struct_ImVec2ih;
pub const struct_ImVec1 = extern struct {
x: f32,
};
pub const ImVec1 = struct_ImVec1;
pub const struct_ImFontAtlasCustomRect = extern struct {
Width: c_ushort,
Height: c_ushort,
X: c_ushort,
Y: c_ushort,
GlyphID: c_uint,
GlyphAdvanceX: f32,
GlyphOffset: ImVec2,
Font: [*c]ImFont,
};
pub const ImFontAtlasCustomRect = struct_ImFontAtlasCustomRect;
pub const struct_ImVec4 = extern struct {
x: f32 = 0,
y: f32 = 0,
z: f32 = 0,
w: f32 = 0,
};
pub const ImVec4 = struct_ImVec4;
pub const ImVec2 = extern struct {
x: f32 = 0,
y: f32 = 0,
pub fn init(x: f32, y: f32) ImVec2 {
return .{ .x = x, .y = y };
}
pub fn add(self: ImVec2, other: ImVec2) ImVec2 {
return .{ .x = self.x + other.x, .y = self.y + other.y };
}
pub fn subtract(self: ImVec2, other: ImVec2) ImVec2 {
return .{ .x = self.x - other.x, .y = self.y - other.y };
}
pub fn scale(self: ImVec2, s: f32) ImVec2 {
return .{ .x = self.x * s, .y = self.y * s };
}
};
pub const struct_ImGuiWindowSettings = extern struct {
ID: ImGuiID,
Pos: ImVec2ih,
Size: ImVec2ih,
ViewportPos: ImVec2ih,
ViewportId: ImGuiID,
DockId: ImGuiID,
ClassId: ImGuiID,
DockOrder: c_short,
Collapsed: bool,
WantApply: bool,
};
pub const ImGuiWindowSettings = struct_ImGuiWindowSettings;
pub const struct_ImGuiWindowTempData = extern struct {
CursorPos: ImVec2,
CursorPosPrevLine: ImVec2,
CursorStartPos: ImVec2,
CursorMaxPos: ImVec2,
CurrLineSize: ImVec2,
PrevLineSize: ImVec2,
CurrLineTextBaseOffset: f32,
PrevLineTextBaseOffset: f32,
Indent: ImVec1,
ColumnsOffset: ImVec1,
GroupOffset: ImVec1,
LastItemId: ImGuiID,
LastItemStatusFlags: ImGuiItemStatusFlags,
LastItemRect: ImRect,
LastItemDisplayRect: ImRect,
NavLayerCurrent: ImGuiNavLayer,
NavLayerCurrentMask: c_int,
NavLayerActiveMask: c_int,
NavLayerActiveMaskNext: c_int,
NavFocusScopeIdCurrent: ImGuiID,
NavHideHighlightOneFrame: bool,
NavHasScroll: bool,
MenuBarAppending: bool,
MenuBarOffset: ImVec2,
MenuColumns: ImGuiMenuColumns,
TreeDepth: c_int,
TreeJumpToParentOnPopMask: ImU32,
ChildWindows: ImVector_ImGuiWindowPtr,
StateStorage: [*c]ImGuiStorage,
CurrentColumns: [*c]ImGuiColumns,
LayoutType: ImGuiLayoutType,
ParentLayoutType: ImGuiLayoutType,
FocusCounterRegular: c_int,
FocusCounterTabStop: c_int,
ItemFlags: ImGuiItemFlags,
ItemWidth: f32,
TextWrapPos: f32,
ItemFlagsStack: ImVector_ImGuiItemFlags,
ItemWidthStack: ImVector_float,
TextWrapPosStack: ImVector_float,
GroupStack: ImVector_ImGuiGroupData,
StackSizesBackup: [6]c_short,
};
pub const ImGuiWindowTempData = struct_ImGuiWindowTempData;
pub const struct_ImGuiWindow = @Type(.Opaque); // /Users/mikedesaro/Zig-Aya/deps/imgui/cimgui/cimgui.h:1954:10: warning: struct demoted to opaque type - has bitfield
pub const ImGuiWindow = struct_ImGuiWindow;
pub const struct_ImGuiTabItem = extern struct {
ID: ImGuiID,
Flags: ImGuiTabItemFlags,
Window: ?*ImGuiWindow,
LastFrameVisible: c_int,
LastFrameSelected: c_int,
NameOffset: c_int,
Offset: f32,
Width: f32,
ContentWidth: f32,
};
pub const ImGuiTabItem = struct_ImGuiTabItem;
pub const struct_ImGuiTabBar = extern struct {
Tabs: ImVector_ImGuiTabItem,
ID: ImGuiID,
SelectedTabId: ImGuiID,
NextSelectedTabId: ImGuiID,
VisibleTabId: ImGuiID,
CurrFrameVisible: c_int,
PrevFrameVisible: c_int,
BarRect: ImRect,
LastTabContentHeight: f32,
OffsetMax: f32,
OffsetMaxIdeal: f32,
OffsetNextTab: f32,
ScrollingAnim: f32,
ScrollingTarget: f32,
ScrollingTargetDistToVisibility: f32,
ScrollingSpeed: f32,
Flags: ImGuiTabBarFlags,
ReorderRequestTabId: ImGuiID,
ReorderRequestDir: ImS8,
WantLayout: bool,
VisibleTabWasSubmitted: bool,
LastTabItemIdx: c_short,
FramePadding: ImVec2,
TabsNames: ImGuiTextBuffer,
};
pub const ImGuiTabBar = struct_ImGuiTabBar;
const union_unnamed_3 = extern union {
BackupInt: [2]c_int,
BackupFloat: [2]f32,
};
pub const struct_ImGuiStyleMod = extern struct {
VarIdx: ImGuiStyleVar,
unnamed_0: union_unnamed_3,
};
pub const ImGuiStyleMod = struct_ImGuiStyleMod;
pub const struct_ImGuiSettingsHandler = extern struct {
TypeName: [*c]const u8,
TypeHash: ImGuiID,
ClearAllFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler) callconv(.C) void,
ReadInitFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler) callconv(.C) void,
ReadOpenFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler, [*c]const u8) callconv(.C) ?*c_void,
ReadLineFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler, ?*c_void, [*c]const u8) callconv(.C) void,
ApplyAllFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler) callconv(.C) void,
WriteAllFn: ?fn ([*c]ImGuiContext, [*c]ImGuiSettingsHandler, [*c]ImGuiTextBuffer) callconv(.C) void,
UserData: ?*c_void,
};
pub const ImGuiSettingsHandler = struct_ImGuiSettingsHandler;
pub const struct_ImGuiPopupData = extern struct {
PopupId: ImGuiID,
Window: ?*ImGuiWindow,
SourceWindow: ?*ImGuiWindow,
OpenFrameCount: c_int,
OpenParentId: ImGuiID,
OpenPopupPos: ImVec2,
OpenMousePos: ImVec2,
};
pub const ImGuiPopupData = struct_ImGuiPopupData;
pub const struct_ImGuiNextItemData = extern struct {
Flags: ImGuiNextItemDataFlags,
Width: f32,
FocusScopeId: ImGuiID,
OpenCond: ImGuiCond,
OpenVal: bool,
};
pub const ImGuiNextItemData = struct_ImGuiNextItemData;
pub const struct_ImGuiNextWindowData = extern struct {
Flags: ImGuiNextWindowDataFlags,
PosCond: ImGuiCond,
SizeCond: ImGuiCond,
CollapsedCond: ImGuiCond,
DockCond: ImGuiCond,
PosVal: ImVec2,
PosPivotVal: ImVec2,
SizeVal: ImVec2,
ContentSizeVal: ImVec2,
ScrollVal: ImVec2,
PosUndock: bool,
CollapsedVal: bool,
SizeConstraintRect: ImRect,
SizeCallback: ImGuiSizeCallback,
SizeCallbackUserData: ?*c_void,
BgAlphaVal: f32,
ViewportId: ImGuiID,
DockId: ImGuiID,
WindowClass: ImGuiWindowClass,
MenuBarOffsetMinVal: ImVec2,
};
pub const ImGuiNextWindowData = struct_ImGuiNextWindowData;
pub const struct_ImGuiNavMoveResult = extern struct {
Window: ?*ImGuiWindow,
ID: ImGuiID,
FocusScopeId: ImGuiID,
DistBox: f32,
DistCenter: f32,
DistAxial: f32,
RectRel: ImRect,
};
pub const ImGuiNavMoveResult = struct_ImGuiNavMoveResult;
pub const struct_ImGuiMenuColumns = extern struct {
Spacing: f32,
Width: f32,
NextWidth: f32,
Pos: [3]f32,
NextWidths: [3]f32,
};
pub const ImGuiMenuColumns = struct_ImGuiMenuColumns;
pub const struct_ImGuiItemHoveredDataBackup = extern struct {
LastItemId: ImGuiID,
LastItemStatusFlags: ImGuiItemStatusFlags,
LastItemRect: ImRect,
LastItemDisplayRect: ImRect,
};
pub const ImGuiItemHoveredDataBackup = struct_ImGuiItemHoveredDataBackup;
pub const struct_ImGuiInputTextState = extern struct {
ID: ImGuiID,
CurLenW: c_int,
CurLenA: c_int,
TextW: ImVector_ImWchar,
TextA: ImVector_char,
InitialTextA: ImVector_char,
TextAIsValid: bool,
BufCapacityA: c_int,
ScrollX: f32,
Stb: STB_TexteditState,
CursorAnim: f32,
CursorFollow: bool,
SelectedAllMouseLock: bool,
UserFlags: ImGuiInputTextFlags,
UserCallback: ImGuiInputTextCallback,
UserCallbackData: ?*c_void,
};
pub const ImGuiInputTextState = struct_ImGuiInputTextState;
pub const struct_ImGuiGroupData = extern struct {
BackupCursorPos: ImVec2,
BackupCursorMaxPos: ImVec2,
BackupIndent: ImVec1,
BackupGroupOffset: ImVec1,
BackupCurrLineSize: ImVec2,
BackupCurrLineTextBaseOffset: f32,
BackupActiveIdIsAlive: ImGuiID,
BackupActiveIdPreviousFrameIsAlive: bool,
EmitItem: bool,
};
pub const ImGuiGroupData = struct_ImGuiGroupData;
pub const struct_ImGuiDockNodeSettings = @Type(.Opaque);
pub const ImGuiDockNodeSettings = struct_ImGuiDockNodeSettings;
pub const struct_ImGuiDockNode = @Type(.Opaque); // /Users/mikedesaro/Zig-Aya/deps/imgui/cimgui/cimgui.h:1551:24: warning: struct demoted to opaque type - has bitfield
pub const ImGuiDockNode = struct_ImGuiDockNode;
pub const struct_ImGuiDockRequest = @Type(.Opaque);
pub const ImGuiDockRequest = struct_ImGuiDockRequest;
pub const struct_ImGuiDockContext = extern struct {
Nodes: ImGuiStorage,
Requests: ImVector_ImGuiDockRequest,
NodesSettings: ImVector_ImGuiDockNodeSettings,
WantFullRebuild: bool,
};
pub const ImGuiDockContext = struct_ImGuiDockContext;
pub const struct_ImGuiDataTypeInfo = extern struct {
Size: usize,
PrintFmt: [*c]const u8,
ScanFmt: [*c]const u8,
};
pub const ImGuiDataTypeInfo = struct_ImGuiDataTypeInfo;
pub const struct_ImGuiColumns = extern struct {
ID: ImGuiID,
Flags: ImGuiColumnsFlags,
IsFirstFrame: bool,
IsBeingResized: bool,
Current: c_int,
Count: c_int,
OffMinX: f32,
OffMaxX: f32,
LineMinY: f32,
LineMaxY: f32,
HostCursorPosY: f32,
HostCursorMaxPosX: f32,
HostClipRect: ImRect,
HostWorkRect: ImRect,
Columns: ImVector_ImGuiColumnData,
Splitter: ImDrawListSplitter,
};
pub const ImGuiColumns = struct_ImGuiColumns;
pub const struct_ImGuiColumnData = extern struct {
OffsetNorm: f32,
OffsetNormBeforeResize: f32,
Flags: ImGuiColumnsFlags,
ClipRect: ImRect,
};
pub const ImGuiColumnData = struct_ImGuiColumnData;
pub const struct_ImGuiColorMod = extern struct {
Col: ImGuiCol,
BackupValue: ImVec4,
};
pub const ImGuiColorMod = struct_ImGuiColorMod;
pub const struct_ImDrawDataBuilder = extern struct {
Layers: [2]ImVector_ImDrawListPtr,
};
pub const ImDrawDataBuilder = struct_ImDrawDataBuilder;
pub const struct_ImRect = extern struct {
Min: ImVec2,
Max: ImVec2,
};
pub const ImRect = struct_ImRect;
pub const struct_ImBitVector = extern struct {
Storage: ImVector_ImU32,
};
pub const ImBitVector = struct_ImBitVector;
pub const struct_ImGuiWindowClass = extern struct {
ClassId: ImGuiID,
ParentViewportId: ImGuiID,
ViewportFlagsOverrideSet: ImGuiViewportFlags,
ViewportFlagsOverrideClear: ImGuiViewportFlags,
DockNodeFlagsOverrideSet: ImGuiDockNodeFlags,
DockNodeFlagsOverrideClear: ImGuiDockNodeFlags,
DockingAlwaysTabBar: bool,
DockingAllowUnclassed: bool,
};
pub const ImGuiWindowClass = struct_ImGuiWindowClass;
pub const struct_ImGuiViewport = extern struct {
ID: ImGuiID,
Flags: ImGuiViewportFlags,
Pos: ImVec2,
Size: ImVec2,
WorkOffsetMin: ImVec2,
WorkOffsetMax: ImVec2,
DpiScale: f32,
DrawData: [*c]ImDrawData,
ParentViewportId: ImGuiID,
RendererUserData: ?*c_void,
PlatformUserData: ?*c_void,
PlatformHandle: ?*c_void,
PlatformHandleRaw: ?*c_void,
PlatformRequestMove: bool,
PlatformRequestResize: bool,
PlatformRequestClose: bool,
};
pub const ImGuiViewport = struct_ImGuiViewport;
pub const struct_ImGuiTextFilter = extern struct {
InputBuf: [256]u8,
Filters: ImVector_ImGuiTextRange,
CountGrep: c_int,
};
pub const ImGuiTextFilter = struct_ImGuiTextFilter;
pub const struct_ImGuiTextBuffer = extern struct {
Buf: ImVector_char,
};
pub const ImGuiTextBuffer = struct_ImGuiTextBuffer;
pub const struct_ImGuiStyle = extern struct {
Alpha: f32,
WindowPadding: ImVec2,
WindowRounding: f32,
WindowBorderSize: f32,
WindowMinSize: ImVec2,
WindowTitleAlign: ImVec2,
WindowMenuButtonPosition: ImGuiDir,
ChildRounding: f32,
ChildBorderSize: f32,
PopupRounding: f32,
PopupBorderSize: f32,
FramePadding: ImVec2,
FrameRounding: f32,
FrameBorderSize: f32,
ItemSpacing: ImVec2,
ItemInnerSpacing: ImVec2,
TouchExtraPadding: ImVec2,
IndentSpacing: f32,
ColumnsMinSpacing: f32,
ScrollbarSize: f32,
ScrollbarRounding: f32,
GrabMinSize: f32,
GrabRounding: f32,
TabRounding: f32,
TabBorderSize: f32,
TabMinWidthForUnselectedCloseButton: f32,
ColorButtonPosition: ImGuiDir,
ButtonTextAlign: ImVec2,
SelectableTextAlign: ImVec2,
DisplayWindowPadding: ImVec2,
DisplaySafeAreaPadding: ImVec2,
MouseCursorScale: f32,
AntiAliasedLines: bool,
AntiAliasedFill: bool,
CurveTessellationTol: f32,
CircleSegmentMaxError: f32,
Colors: [50]ImVec4,
};
pub const ImGuiStyle = struct_ImGuiStyle;
pub const struct_ImGuiStorage = extern struct {
Data: ImVector_ImGuiStoragePair,
};
pub const ImGuiStorage = struct_ImGuiStorage;
pub const struct_ImGuiSizeCallbackData = extern struct {
UserData: ?*c_void,
Pos: ImVec2,
CurrentSize: ImVec2,
DesiredSize: ImVec2,
};
pub const ImGuiSizeCallbackData = struct_ImGuiSizeCallbackData;
pub const struct_ImGuiPlatformMonitor = extern struct {
MainPos: ImVec2,
MainSize: ImVec2,
WorkPos: ImVec2,
WorkSize: ImVec2,
DpiScale: f32,
};
pub const ImGuiPlatformMonitor = struct_ImGuiPlatformMonitor;
pub const struct_ImGuiPlatformIO = extern struct {
Platform_CreateWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_DestroyWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_ShowWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_SetWindowPos: ?fn ([*c]ImGuiViewport, ImVec2) callconv(.C) void,
Platform_GetWindowPos: ?fn ([*c]ImGuiViewport) callconv(.C) ImVec2,
Platform_SetWindowSize: ?fn ([*c]ImGuiViewport, ImVec2) callconv(.C) void,
Platform_GetWindowSize: ?fn ([*c]ImGuiViewport) callconv(.C) ImVec2,
Platform_SetWindowFocus: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_GetWindowFocus: ?fn ([*c]ImGuiViewport) callconv(.C) bool,
Platform_GetWindowMinimized: ?fn ([*c]ImGuiViewport) callconv(.C) bool,
Platform_SetWindowTitle: ?fn ([*c]ImGuiViewport, [*c]const u8) callconv(.C) void,
Platform_SetWindowAlpha: ?fn ([*c]ImGuiViewport, f32) callconv(.C) void,
Platform_UpdateWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_RenderWindow: ?fn ([*c]ImGuiViewport, ?*c_void) callconv(.C) void,
Platform_SwapBuffers: ?fn ([*c]ImGuiViewport, ?*c_void) callconv(.C) void,
Platform_GetWindowDpiScale: ?fn ([*c]ImGuiViewport) callconv(.C) f32,
Platform_OnChangedViewport: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Platform_SetImeInputPos: ?fn ([*c]ImGuiViewport, ImVec2) callconv(.C) void,
Platform_CreateVkSurface: ?fn ([*c]ImGuiViewport, ImU64, ?*const c_void, [*c]ImU64) callconv(.C) c_int,
Renderer_CreateWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Renderer_DestroyWindow: ?fn ([*c]ImGuiViewport) callconv(.C) void,
Renderer_SetWindowSize: ?fn ([*c]ImGuiViewport, ImVec2) callconv(.C) void,
Renderer_RenderWindow: ?fn ([*c]ImGuiViewport, ?*c_void) callconv(.C) void,
Renderer_SwapBuffers: ?fn ([*c]ImGuiViewport, ?*c_void) callconv(.C) void,
Monitors: ImVector_ImGuiPlatformMonitor,
MainViewport: [*c]ImGuiViewport,
Viewports: ImVector_ImGuiViewportPtr,
};
pub const ImGuiPlatformIO = struct_ImGuiPlatformIO;
pub const struct_ImGuiPayload = extern struct {
Data: ?*c_void,
DataSize: c_int,
SourceId: ImGuiID,
SourceParentId: ImGuiID,
DataFrameCount: c_int,
DataType: [33]u8,
Preview: bool,
Delivery: bool,
};
pub const ImGuiPayload = struct_ImGuiPayload;
pub const struct_ImGuiOnceUponAFrame = extern struct {
RefFrame: c_int,
};
pub const ImGuiOnceUponAFrame = struct_ImGuiOnceUponAFrame;
pub const struct_ImGuiListClipper = extern struct {
DisplayStart: c_int,
DisplayEnd: c_int,
ItemsCount: c_int,
StepNo: c_int,
ItemsHeight: f32,
StartPosY: f32,
};
pub const ImGuiListClipper = struct_ImGuiListClipper;
pub const struct_ImGuiInputTextCallbackData = extern struct {
EventFlag: ImGuiInputTextFlags,
Flags: ImGuiInputTextFlags,
UserData: ?*c_void,
EventChar: ImWchar,
EventKey: ImGuiKey,
Buf: [*c]u8,
BufTextLen: c_int,
BufSize: c_int,
BufDirty: bool,
CursorPos: c_int,
SelectionStart: c_int,
SelectionEnd: c_int,
};
pub const ImGuiInputTextCallbackData = struct_ImGuiInputTextCallbackData;
pub const struct_ImGuiIO = extern struct {
ConfigFlags: ImGuiConfigFlags,
BackendFlags: ImGuiBackendFlags,
DisplaySize: ImVec2,
DeltaTime: f32,
IniSavingRate: f32,
IniFilename: [*c]const u8,
LogFilename: [*c]const u8,
MouseDoubleClickTime: f32,
MouseDoubleClickMaxDist: f32,
MouseDragThreshold: f32,
KeyMap: [22]c_int,
KeyRepeatDelay: f32,
KeyRepeatRate: f32,
UserData: ?*c_void,
Fonts: [*c]ImFontAtlas,
FontGlobalScale: f32,
FontAllowUserScaling: bool,
FontDefault: [*c]ImFont,
DisplayFramebufferScale: ImVec2,
ConfigDockingNoSplit: bool,
ConfigDockingWithShift: bool,
ConfigDockingAlwaysTabBar: bool,
ConfigDockingTransparentPayload: bool,
ConfigViewportsNoAutoMerge: bool,
ConfigViewportsNoTaskBarIcon: bool,
ConfigViewportsNoDecoration: bool,
ConfigViewportsNoDefaultParent: bool,
MouseDrawCursor: bool,
ConfigMacOSXBehaviors: bool,
ConfigInputTextCursorBlink: bool,
ConfigWindowsResizeFromEdges: bool,
ConfigWindowsMoveFromTitleBarOnly: bool,
ConfigWindowsMemoryCompactTimer: f32,
BackendPlatformName: [*c]const u8,
BackendRendererName: [*c]const u8,
BackendPlatformUserData: ?*c_void,
BackendRendererUserData: ?*c_void,
BackendLanguageUserData: ?*c_void,
GetClipboardTextFn: ?fn (?*c_void) callconv(.C) [*c]const u8,
SetClipboardTextFn: ?fn (?*c_void, [*c]const u8) callconv(.C) void,
ClipboardUserData: ?*c_void,
RenderDrawListsFnUnused: ?*c_void,
MousePos: ImVec2,
MouseDown: [5]bool,
MouseWheel: f32,
MouseWheelH: f32,
MouseHoveredViewport: ImGuiID,
KeyCtrl: bool,
KeyShift: bool,
KeyAlt: bool,
KeySuper: bool,
KeysDown: [512]bool,
NavInputs: [21]f32,
WantCaptureMouse: bool,
WantCaptureKeyboard: bool,
WantTextInput: bool,
WantSetMousePos: bool,
WantSaveIniSettings: bool,
NavActive: bool,
NavVisible: bool,
Framerate: f32,
MetricsRenderVertices: c_int,
MetricsRenderIndices: c_int,
MetricsRenderWindows: c_int,
MetricsActiveWindows: c_int,
MetricsActiveAllocations: c_int,
MouseDelta: ImVec2,
KeyMods: ImGuiKeyModFlags,
MousePosPrev: ImVec2,
MouseClickedPos: [5]ImVec2,
MouseClickedTime: [5]f64,
MouseClicked: [5]bool,
MouseDoubleClicked: [5]bool,
MouseReleased: [5]bool,
MouseDownOwned: [5]bool,
MouseDownWasDoubleClick: [5]bool,
MouseDownDuration: [5]f32,
MouseDownDurationPrev: [5]f32,
MouseDragMaxDistanceAbs: [5]ImVec2,
MouseDragMaxDistanceSqr: [5]f32,
KeysDownDuration: [512]f32,
KeysDownDurationPrev: [512]f32,
NavInputsDownDuration: [21]f32,
NavInputsDownDurationPrev: [21]f32,
InputQueueSurrogate: ImWchar16,
InputQueueCharacters: ImVector_ImWchar,
};
pub const ImGuiIO = struct_ImGuiIO;
pub const struct_ImGuiContext = extern struct {
Initialized: bool,
FontAtlasOwnedByContext: bool,
IO: ImGuiIO,
PlatformIO: ImGuiPlatformIO,
Style: ImGuiStyle,
ConfigFlagsCurrFrame: ImGuiConfigFlags,
ConfigFlagsLastFrame: ImGuiConfigFlags,
Font: [*c]ImFont,
FontSize: f32,
FontBaseSize: f32,
DrawListSharedData: ImDrawListSharedData,
Time: f64,
FrameCount: c_int,
FrameCountEnded: c_int,
FrameCountPlatformEnded: c_int,
FrameCountRendered: c_int,
WithinFrameScope: bool,
WithinFrameScopeWithImplicitWindow: bool,
WithinEndChild: bool,
TestEngineHookItems: bool,
TestEngineHookIdInfo: ImGuiID,
TestEngine: ?*c_void,
Windows: ImVector_ImGuiWindowPtr,
WindowsFocusOrder: ImVector_ImGuiWindowPtr,
WindowsTempSortBuffer: ImVector_ImGuiWindowPtr,
CurrentWindowStack: ImVector_ImGuiWindowPtr,
WindowsById: ImGuiStorage,
WindowsActiveCount: c_int,
CurrentWindow: ?*ImGuiWindow,
HoveredWindow: ?*ImGuiWindow,
HoveredRootWindow: ?*ImGuiWindow,
HoveredWindowUnderMovingWindow: ?*ImGuiWindow,
MovingWindow: ?*ImGuiWindow,
WheelingWindow: ?*ImGuiWindow,
WheelingWindowRefMousePos: ImVec2,
WheelingWindowTimer: f32,
HoveredId: ImGuiID,
HoveredIdAllowOverlap: bool,
HoveredIdPreviousFrame: ImGuiID,
HoveredIdTimer: f32,
HoveredIdNotActiveTimer: f32,
ActiveId: ImGuiID,
ActiveIdIsAlive: ImGuiID,
ActiveIdTimer: f32,
ActiveIdIsJustActivated: bool,
ActiveIdAllowOverlap: bool,
ActiveIdHasBeenPressedBefore: bool,
ActiveIdHasBeenEditedBefore: bool,
ActiveIdHasBeenEditedThisFrame: bool,
ActiveIdUsingNavDirMask: ImU32,
ActiveIdUsingNavInputMask: ImU32,
ActiveIdUsingKeyInputMask: ImU64,
ActiveIdClickOffset: ImVec2,
ActiveIdWindow: ?*ImGuiWindow,
ActiveIdSource: ImGuiInputSource,
ActiveIdMouseButton: c_int,
ActiveIdPreviousFrame: ImGuiID,
ActiveIdPreviousFrameIsAlive: bool,
ActiveIdPreviousFrameHasBeenEditedBefore: bool,
ActiveIdPreviousFrameWindow: ?*ImGuiWindow,
LastActiveId: ImGuiID,
LastActiveIdTimer: f32,
NextWindowData: ImGuiNextWindowData,
NextItemData: ImGuiNextItemData,
ColorModifiers: ImVector_ImGuiColorMod,
StyleModifiers: ImVector_ImGuiStyleMod,
FontStack: ImVector_ImFontPtr,
OpenPopupStack: ImVector_ImGuiPopupData,
BeginPopupStack: ImVector_ImGuiPopupData,
Viewports: ImVector_ImGuiViewportPPtr,
CurrentDpiScale: f32,
CurrentViewport: [*c]ImGuiViewportP,
MouseViewport: [*c]ImGuiViewportP,
MouseLastHoveredViewport: [*c]ImGuiViewportP,
PlatformLastFocusedViewport: ImGuiID,
ViewportFrontMostStampCount: c_int,
NavWindow: ?*ImGuiWindow,
NavId: ImGuiID,
NavFocusScopeId: ImGuiID,
NavActivateId: ImGuiID,
NavActivateDownId: ImGuiID,
NavActivatePressedId: ImGuiID,
NavInputId: ImGuiID,
NavJustTabbedId: ImGuiID,
NavJustMovedToId: ImGuiID,
NavJustMovedToFocusScopeId: ImGuiID,
NavJustMovedToKeyMods: ImGuiKeyModFlags,
NavNextActivateId: ImGuiID,
NavInputSource: ImGuiInputSource,
NavScoringRect: ImRect,
NavScoringCount: c_int,
NavLayer: ImGuiNavLayer,
NavIdTabCounter: c_int,
NavIdIsAlive: bool,
NavMousePosDirty: bool,
NavDisableHighlight: bool,
NavDisableMouseHover: bool,
NavAnyRequest: bool,
NavInitRequest: bool,
NavInitRequestFromMove: bool,
NavInitResultId: ImGuiID,
NavInitResultRectRel: ImRect,
NavMoveFromClampedRefRect: bool,
NavMoveRequest: bool,
NavMoveRequestFlags: ImGuiNavMoveFlags,
NavMoveRequestForward: ImGuiNavForward,
NavMoveRequestKeyMods: ImGuiKeyModFlags,
NavMoveDir: ImGuiDir,
NavMoveDirLast: ImGuiDir,
NavMoveClipDir: ImGuiDir,
NavMoveResultLocal: ImGuiNavMoveResult,
NavMoveResultLocalVisibleSet: ImGuiNavMoveResult,
NavMoveResultOther: ImGuiNavMoveResult,
NavWrapRequestWindow: ?*ImGuiWindow,
NavWrapRequestFlags: ImGuiNavMoveFlags,
NavWindowingTarget: ?*ImGuiWindow,
NavWindowingTargetAnim: ?*ImGuiWindow,
NavWindowingListWindow: ?*ImGuiWindow,
NavWindowingTimer: f32,
NavWindowingHighlightAlpha: f32,
NavWindowingToggleLayer: bool,
FocusRequestCurrWindow: ?*ImGuiWindow,
FocusRequestNextWindow: ?*ImGuiWindow,
FocusRequestCurrCounterRegular: c_int,
FocusRequestCurrCounterTabStop: c_int,
FocusRequestNextCounterRegular: c_int,
FocusRequestNextCounterTabStop: c_int,
FocusTabPressed: bool,
DimBgRatio: f32,
MouseCursor: ImGuiMouseCursor,
DragDropActive: bool,
DragDropWithinSource: bool,
DragDropWithinTarget: bool,
DragDropSourceFlags: ImGuiDragDropFlags,
DragDropSourceFrameCount: c_int,
DragDropMouseButton: c_int,
DragDropPayload: ImGuiPayload,
DragDropTargetRect: ImRect,
DragDropTargetId: ImGuiID,
DragDropAcceptFlags: ImGuiDragDropFlags,
DragDropAcceptIdCurrRectSurface: f32,
DragDropAcceptIdCurr: ImGuiID,
DragDropAcceptIdPrev: ImGuiID,
DragDropAcceptFrameCount: c_int,
DragDropHoldJustPressedId: ImGuiID,
DragDropPayloadBufHeap: ImVector_unsigned_char,
DragDropPayloadBufLocal: [16]u8,
CurrentTabBar: [*c]ImGuiTabBar,
TabBars: ImPool_ImGuiTabBar,
CurrentTabBarStack: ImVector_ImGuiPtrOrIndex,
ShrinkWidthBuffer: ImVector_ImGuiShrinkWidthItem,
LastValidMousePos: ImVec2,
InputTextState: ImGuiInputTextState,
InputTextPasswordFont: ImFont,
TempInputId: ImGuiID,
ColorEditOptions: ImGuiColorEditFlags,
ColorEditLastHue: f32,
ColorEditLastSat: f32,
ColorEditLastColor: [3]f32,
ColorPickerRef: ImVec4,
DragCurrentAccumDirty: bool,
DragCurrentAccum: f32,
DragSpeedDefaultRatio: f32,
ScrollbarClickDeltaToGrabCenter: f32,
TooltipOverrideCount: c_int,
ClipboardHandlerData: ImVector_char,
MenusIdSubmittedThisFrame: ImVector_ImGuiID,
PlatformImePos: ImVec2,
PlatformImeLastPos: ImVec2,
PlatformImePosViewport: [*c]ImGuiViewportP,
DockContext: ImGuiDockContext,
SettingsLoaded: bool,
SettingsDirtyTimer: f32,
SettingsIniData: ImGuiTextBuffer,
SettingsHandlers: ImVector_ImGuiSettingsHandler,
SettingsWindows: ImChunkStream_ImGuiWindowSettings,
LogEnabled: bool,
LogType: ImGuiLogType,
LogFile: ImFileHandle,
LogBuffer: ImGuiTextBuffer,
LogLinePosY: f32,
LogLineFirstItem: bool,
LogDepthRef: c_int,
LogDepthToExpand: c_int,
LogDepthToExpandDefault: c_int,
DebugItemPickerActive: bool,
DebugItemPickerBreakId: ImGuiID,
FramerateSecPerFrame: [120]f32,
FramerateSecPerFrameIdx: c_int,
FramerateSecPerFrameAccum: f32,
WantCaptureMouseNextFrame: c_int,
WantCaptureKeyboardNextFrame: c_int,
WantTextInputNextFrame: c_int,
TempBuffer: [3073]u8,
};
pub const ImGuiContext = struct_ImGuiContext;
pub const struct_ImColor = extern struct {
Value: ImVec4,
};
pub const ImColor = struct_ImColor;
pub const struct_ImFontGlyphRangesBuilder = extern struct {
UsedChars: ImVector_ImU32,
};
pub const ImFontGlyphRangesBuilder = struct_ImFontGlyphRangesBuilder;
pub const struct_ImFontGlyph = @Type(.Opaque); // /Users/mikedesaro/Zig-Aya/deps/imgui/cimgui/cimgui.h:1012:18: warning: struct demoted to opaque type - has bitfield
pub const ImFontGlyph = struct_ImFontGlyph;
pub const struct_ImFontConfig = extern struct {
FontData: ?*c_void,
FontDataSize: c_int,
FontDataOwnedByAtlas: bool,
FontNo: c_int,
SizePixels: f32,
OversampleH: c_int,
OversampleV: c_int,
PixelSnapH: bool,
GlyphExtraSpacing: ImVec2,
GlyphOffset: ImVec2,
GlyphRanges: [*c]const ImWchar,
GlyphMinAdvanceX: f32,
GlyphMaxAdvanceX: f32,
MergeMode: bool,
RasterizerFlags: c_uint,
RasterizerMultiply: f32,
EllipsisChar: ImWchar,
Name: [40]u8,
DstFont: [*c]ImFont,
};
pub const ImFontConfig = struct_ImFontConfig;
pub const struct_ImFontAtlas = extern struct {
Locked: bool,
Flags: ImFontAtlasFlags,
TexID: ImTextureID,
TexDesiredWidth: c_int,
TexGlyphPadding: c_int,
TexPixelsAlpha8: [*c]u8,
TexPixelsRGBA32: [*c]c_uint,
TexWidth: c_int,
TexHeight: c_int,
TexUvScale: ImVec2,
TexUvWhitePixel: ImVec2,
Fonts: ImVector_ImFontPtr,
CustomRects: ImVector_ImFontAtlasCustomRect,
ConfigData: ImVector_ImFontConfig,
CustomRectIds: [1]c_int,
};
pub const ImFontAtlas = struct_ImFontAtlas;
pub const struct_ImFont = extern struct {
IndexAdvanceX: ImVector_float,
FallbackAdvanceX: f32,
FontSize: f32,
IndexLookup: ImVector_ImWchar,
Glyphs: ImVector_ImFontGlyph,
FallbackGlyph: ?*const ImFontGlyph,
DisplayOffset: ImVec2,
ContainerAtlas: [*c]ImFontAtlas,
ConfigData: [*c]const ImFontConfig,
ConfigDataCount: c_short,
FallbackChar: ImWchar,
EllipsisChar: ImWchar,
DirtyLookupTables: bool,
Scale: f32,
Ascent: f32,
Descent: f32,
MetricsTotalSurface: c_int,
Used4kPagesMap: [2]ImU8,
};
pub const ImFont = struct_ImFont;
pub const struct_ImDrawVert = extern struct {
pos: ImVec2,
uv: ImVec2,
col: ImU32,
};
pub const ImDrawVert = struct_ImDrawVert;
pub const struct_ImDrawListSplitter = extern struct {
_Current: c_int,
_Count: c_int,
_Channels: ImVector_ImDrawChannel,
};
pub const ImDrawListSplitter = struct_ImDrawListSplitter;
pub const struct_ImDrawListSharedData = extern struct {
TexUvWhitePixel: ImVec2,
Font: [*c]ImFont,
FontSize: f32,
CurveTessellationTol: f32,
CircleSegmentMaxError: f32,
ClipRectFullscreen: ImVec4,
InitialFlags: ImDrawListFlags,
ArcFastVtx: [12]ImVec2,
CircleSegmentCounts: [64]ImU8,
};
pub const ImDrawListSharedData = struct_ImDrawListSharedData;
pub const struct_ImDrawList = extern struct {
CmdBuffer: ImVector_ImDrawCmd,
IdxBuffer: ImVector_ImDrawIdx,
VtxBuffer: ImVector_ImDrawVert,
Flags: ImDrawListFlags,
_Data: [*c]const ImDrawListSharedData,
_OwnerName: [*c]const u8,
_VtxCurrentOffset: c_uint,
_VtxCurrentIdx: c_uint,
_VtxWritePtr: [*c]ImDrawVert,
_IdxWritePtr: [*c]ImDrawIdx,
_ClipRectStack: ImVector_ImVec4,
_TextureIdStack: ImVector_ImTextureID,
_Path: ImVector_ImVec2,
_Splitter: ImDrawListSplitter,
};
pub const ImDrawList = struct_ImDrawList;
pub const struct_ImDrawData = extern struct {
Valid: bool,
CmdLists: [*c]*ImDrawList,
CmdListsCount: c_int,
TotalIdxCount: c_int,
TotalVtxCount: c_int,
DisplayPos: ImVec2,
DisplaySize: ImVec2,
FramebufferScale: ImVec2,
OwnerViewport: [*c]ImGuiViewport,
};
pub const ImDrawData = struct_ImDrawData;
pub const struct_ImDrawCmd = extern struct {
ElemCount: c_uint,
ClipRect: ImVec4,
TextureId: ImTextureID,
VtxOffset: c_uint,
IdxOffset: c_uint,
UserCallback: ImDrawCallback,
UserCallbackData: ?*c_void,
};
pub const ImDrawCmd = struct_ImDrawCmd;
pub const struct_ImDrawChannel = extern struct {
_CmdBuffer: ImVector_ImDrawCmd,
_IdxBuffer: ImVector_ImDrawIdx,
};
pub const ImDrawChannel = struct_ImDrawChannel;
pub const ImGuiCol = c_int;
pub const ImGuiCond = c_int;
pub const ImGuiDataType = c_int;
pub const ImGuiDir = c_int;
pub const ImGuiKey = c_int;
pub const ImGuiNavInput = c_int;
pub const ImGuiMouseButton = c_int;
pub const ImGuiMouseCursor = c_int;
pub const ImGuiStyleVar = c_int;
pub const ImDrawCornerFlags = c_int;
pub const ImDrawListFlags = c_int;
pub const ImFontAtlasFlags = c_int;
pub const ImGuiBackendFlags = c_int;
pub const ImGuiColorEditFlags = c_int;
pub const ImGuiConfigFlags = c_int;
pub const ImGuiComboFlags = c_int;
pub const ImGuiDockNodeFlags = c_int;
pub const ImGuiDragDropFlags = c_int;
pub const ImGuiFocusedFlags = c_int;
pub const ImGuiHoveredFlags = c_int;
pub const ImGuiInputTextFlags = c_int;
pub const ImGuiKeyModFlags = c_int;
pub const ImGuiSelectableFlags = c_int;
pub const ImGuiTabBarFlags = c_int;
pub const ImGuiTabItemFlags = c_int;
pub const ImGuiTreeNodeFlags = c_int;
pub const ImGuiViewportFlags = c_int;
pub const ImGuiWindowFlags = c_int;
pub const ImTextureID = ?*c_void;
pub const ImGuiID = c_uint;
pub const ImGuiInputTextCallback = ?fn ([*c]ImGuiInputTextCallbackData) callconv(.C) c_int;
pub const ImGuiSizeCallback = ?fn ([*c]ImGuiSizeCallbackData) callconv(.C) void;
pub const ImWchar16 = c_ushort;
pub const ImWchar32 = c_uint;
pub const ImWchar = ImWchar16;
pub const ImS8 = i8;
pub const ImU8 = u8;
pub const ImS16 = c_short;
pub const ImU16 = c_ushort;
pub const ImS32 = c_int;
pub const ImU32 = c_uint;
pub const ImS64 = i64;
pub const ImU64 = u64;
pub const ImDrawCallback = ?fn ([*c]const ImDrawList, [*c]const ImDrawCmd) callconv(.C) void;
pub const ImDrawIdx = c_ushort;
pub const ImGuiDataAuthority = c_int;
pub const ImGuiLayoutType = c_int;
pub const ImGuiButtonFlags = c_int;
pub const ImGuiColumnsFlags = c_int;
pub const ImGuiDragFlags = c_int;
pub const ImGuiItemFlags = c_int;
pub const ImGuiItemStatusFlags = c_int;
pub const ImGuiNavHighlightFlags = c_int;
pub const ImGuiNavDirSourceFlags = c_int;
pub const ImGuiNavMoveFlags = c_int;
pub const ImGuiNextItemDataFlags = c_int;
pub const ImGuiNextWindowDataFlags = c_int;
pub const ImGuiSeparatorFlags = c_int;
pub const ImGuiSliderFlags = c_int;
pub const ImGuiTextFlags = c_int;
pub const ImGuiTooltipFlags = c_int;
pub extern var GImGui: [*c]ImGuiContext;
pub const ImFileHandle = [*c]FILE;
pub const ImPoolIdx = c_int;
pub const struct_ImVector = extern struct {
Size: c_int,
Capacity: c_int,
Data: ?*c_void,
};
pub const ImVector = struct_ImVector;
pub const struct_ImVector_float = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]f32,
};
pub const ImVector_float = struct_ImVector_float;
pub const struct_ImVector_ImWchar = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImWchar,
};
pub const ImVector_ImWchar = struct_ImVector_ImWchar;
pub const struct_ImVector_ImDrawVert = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImDrawVert,
};
pub const ImVector_ImDrawVert = struct_ImVector_ImDrawVert;
pub const struct_ImVector_ImGuiSettingsHandler = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiSettingsHandler,
};
pub const ImVector_ImGuiSettingsHandler = struct_ImVector_ImGuiSettingsHandler;
pub const struct_ImVector_ImGuiPlatformMonitor = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiPlatformMonitor,
};
pub const ImVector_ImGuiPlatformMonitor = struct_ImVector_ImGuiPlatformMonitor;
pub const struct_ImVector_ImVec4 = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImVec4,
};
pub const ImVector_ImVec4 = struct_ImVector_ImVec4;
pub const struct_ImVector_ImGuiPopupData = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiPopupData,
};
pub const ImVector_ImGuiPopupData = struct_ImVector_ImGuiPopupData;
pub const struct_ImVector_const_charPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c][*c]const u8,
};
pub const ImVector_const_charPtr = struct_ImVector_const_charPtr;
pub const struct_ImVector_ImGuiID = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiID,
};
pub const ImVector_ImGuiID = struct_ImVector_ImGuiID;
pub const struct_ImVector_ImGuiWindowPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]?*ImGuiWindow,
};
pub const ImVector_ImGuiWindowPtr = struct_ImVector_ImGuiWindowPtr;
pub const struct_ImVector_ImGuiColumnData = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiColumnData,
};
pub const ImVector_ImGuiColumnData = struct_ImVector_ImGuiColumnData;
pub const struct_ImVector_ImGuiViewportPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c][*c]ImGuiViewport,
};
pub const ImVector_ImGuiViewportPtr = struct_ImVector_ImGuiViewportPtr;
pub const struct_ImVector_ImGuiColorMod = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiColorMod,
};
pub const ImVector_ImGuiColorMod = struct_ImVector_ImGuiColorMod;
pub const struct_ImVector_ImGuiDockRequest = extern struct {
Size: c_int,
Capacity: c_int,
Data: ?*ImGuiDockRequest,
};
pub const ImVector_ImGuiDockRequest = struct_ImVector_ImGuiDockRequest;
pub const struct_ImVector_ImFontGlyph = extern struct {
Size: c_int,
Capacity: c_int,
Data: ?*ImFontGlyph,
};
pub const ImVector_ImFontGlyph = struct_ImVector_ImFontGlyph;
pub const struct_ImVector_unsigned_char = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]u8,
};
pub const ImVector_unsigned_char = struct_ImVector_unsigned_char;
pub const struct_ImVector_ImGuiStoragePair = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiStoragePair,
};
pub const ImVector_ImGuiStoragePair = struct_ImVector_ImGuiStoragePair;
pub const struct_ImVector_ImGuiStyleMod = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiStyleMod,
};
pub const ImVector_ImGuiStyleMod = struct_ImVector_ImGuiStyleMod;
pub const struct_ImVector_ImGuiViewportPPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c][*c]ImGuiViewportP,
};
pub const ImVector_ImGuiViewportPPtr = struct_ImVector_ImGuiViewportPPtr;
pub const struct_ImVector_ImDrawChannel = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImDrawChannel,
};
pub const ImVector_ImDrawChannel = struct_ImVector_ImDrawChannel;
pub const struct_ImVector_ImDrawListPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c][*c]ImDrawList,
};
pub const ImVector_ImDrawListPtr = struct_ImVector_ImDrawListPtr;
pub const struct_ImVector_ImGuiTabItem = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiTabItem,
};
pub const ImVector_ImGuiTabItem = struct_ImVector_ImGuiTabItem;
pub const struct_ImVector_ImU32 = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImU32,
};
pub const ImVector_ImU32 = struct_ImVector_ImU32;
pub const struct_ImVector_ImGuiItemFlags = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiItemFlags,
};
pub const ImVector_ImGuiItemFlags = struct_ImVector_ImGuiItemFlags;
pub const struct_ImVector_ImGuiColumns = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiColumns,
};
pub const ImVector_ImGuiColumns = struct_ImVector_ImGuiColumns;
pub const struct_ImVector_ImFontAtlasCustomRect = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImFontAtlasCustomRect,
};
pub const ImVector_ImFontAtlasCustomRect = struct_ImVector_ImFontAtlasCustomRect;
pub const struct_ImVector_ImGuiDockNodeSettings = extern struct {
Size: c_int,
Capacity: c_int,
Data: ?*ImGuiDockNodeSettings,
};
pub const ImVector_ImGuiDockNodeSettings = struct_ImVector_ImGuiDockNodeSettings;
pub const struct_ImVector_ImGuiGroupData = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiGroupData,
};
pub const ImVector_ImGuiGroupData = struct_ImVector_ImGuiGroupData;
pub const struct_ImVector_ImTextureID = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImTextureID,
};
pub const ImVector_ImTextureID = struct_ImVector_ImTextureID;
pub const struct_ImVector_ImGuiShrinkWidthItem = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiShrinkWidthItem,
};
pub const ImVector_ImGuiShrinkWidthItem = struct_ImVector_ImGuiShrinkWidthItem;
pub const struct_ImVector_ImFontConfig = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImFontConfig,
};
pub const ImVector_ImFontConfig = struct_ImVector_ImFontConfig;
pub const struct_ImVector_ImVec2 = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImVec2,
};
pub const ImVector_ImVec2 = struct_ImVector_ImVec2;
pub const struct_ImVector_char = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]u8,
};
pub const ImVector_char = struct_ImVector_char;
pub const struct_ImVector_ImDrawCmd = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImDrawCmd,
};
pub const ImVector_ImDrawCmd = struct_ImVector_ImDrawCmd;
pub const struct_ImVector_ImFontPtr = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c][*c]ImFont,
};
pub const ImVector_ImFontPtr = struct_ImVector_ImFontPtr;
pub const struct_ImVector_ImGuiPtrOrIndex = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiPtrOrIndex,
};
pub const ImVector_ImGuiPtrOrIndex = struct_ImVector_ImGuiPtrOrIndex;
pub const struct_ImVector_ImDrawIdx = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImDrawIdx,
};
pub const ImVector_ImDrawIdx = struct_ImVector_ImDrawIdx;
pub const struct_ImVector_ImGuiTextRange = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiTextRange,
};
pub const ImVector_ImGuiTextRange = struct_ImVector_ImGuiTextRange;
pub const struct_ImVector_ImGuiWindowSettings = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiWindowSettings,
};
pub const ImVector_ImGuiWindowSettings = struct_ImVector_ImGuiWindowSettings;
pub const struct_ImChunkStream_ImGuiWindowSettings = extern struct {
Buf: ImVector_ImGuiWindowSettings,
};
pub const ImChunkStream_ImGuiWindowSettings = struct_ImChunkStream_ImGuiWindowSettings;
const struct_unnamed_4 = extern struct {
where: c_int,
insert_length: c_int,
delete_length: c_int,
char_storage: c_int,
};
pub const StbUndoRecord = struct_unnamed_4;
const struct_unnamed_5 = extern struct {
undo_rec: [99]StbUndoRecord,
undo_char: [999]ImWchar,
undo_point: c_short,
redo_point: c_short,
undo_char_point: c_int,
redo_char_point: c_int,
};
pub const StbUndoState = struct_unnamed_5;
const struct_unnamed_6 = extern struct {
cursor: c_int,
select_start: c_int,
select_end: c_int,
insert_mode: u8,
cursor_at_end_of_line: u8,
initialized: u8,
has_preferred_x: u8,
single_line: u8,
padding1: u8,
padding2: u8,
padding3: u8,
preferred_x: f32,
undostate: StbUndoState,
};
pub const STB_TexteditState = struct_unnamed_6;
const struct_unnamed_7 = extern struct {
x0: f32,
x1: f32,
baseline_y_delta: f32,
ymin: f32,
ymax: f32,
num_chars: c_int,
};
pub const StbTexteditRow = struct_unnamed_7;
pub const ImGuiWindowFlags_None = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_None);
pub const ImGuiWindowFlags_NoTitleBar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoTitleBar);
pub const ImGuiWindowFlags_NoResize = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoResize);
pub const ImGuiWindowFlags_NoMove = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoMove);
pub const ImGuiWindowFlags_NoScrollbar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoScrollbar);
pub const ImGuiWindowFlags_NoScrollWithMouse = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoScrollWithMouse);
pub const ImGuiWindowFlags_NoCollapse = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoCollapse);
pub const ImGuiWindowFlags_AlwaysAutoResize = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_AlwaysAutoResize);
pub const ImGuiWindowFlags_NoBackground = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoBackground);
pub const ImGuiWindowFlags_NoSavedSettings = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoSavedSettings);
pub const ImGuiWindowFlags_NoMouseInputs = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoMouseInputs);
pub const ImGuiWindowFlags_MenuBar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_MenuBar);
pub const ImGuiWindowFlags_HorizontalScrollbar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_HorizontalScrollbar);
pub const ImGuiWindowFlags_NoFocusOnAppearing = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoFocusOnAppearing);
pub const ImGuiWindowFlags_NoBringToFrontOnFocus = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoBringToFrontOnFocus);
pub const ImGuiWindowFlags_AlwaysVerticalScrollbar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_AlwaysVerticalScrollbar);
pub const ImGuiWindowFlags_AlwaysHorizontalScrollbar = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_AlwaysHorizontalScrollbar);
pub const ImGuiWindowFlags_AlwaysUseWindowPadding = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_AlwaysUseWindowPadding);
pub const ImGuiWindowFlags_NoNavInputs = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoNavInputs);
pub const ImGuiWindowFlags_NoNavFocus = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoNavFocus);
pub const ImGuiWindowFlags_UnsavedDocument = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_UnsavedDocument);
pub const ImGuiWindowFlags_NoDocking = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoDocking);
pub const ImGuiWindowFlags_NoNav = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoNav);
pub const ImGuiWindowFlags_NoDecoration = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoDecoration);
pub const ImGuiWindowFlags_NoInputs = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NoInputs);
pub const ImGuiWindowFlags_NavFlattened = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_NavFlattened);
pub const ImGuiWindowFlags_ChildWindow = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_ChildWindow);
pub const ImGuiWindowFlags_Tooltip = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_Tooltip);
pub const ImGuiWindowFlags_Popup = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_Popup);
pub const ImGuiWindowFlags_Modal = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_Modal);
pub const ImGuiWindowFlags_ChildMenu = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_ChildMenu);
pub const ImGuiWindowFlags_DockNodeHost = @enumToInt(enum_unnamed_8.ImGuiWindowFlags_DockNodeHost);
const enum_unnamed_8 = extern enum(c_int) {
ImGuiWindowFlags_None = 0,
ImGuiWindowFlags_NoTitleBar = 1,
ImGuiWindowFlags_NoResize = 2,
ImGuiWindowFlags_NoMove = 4,
ImGuiWindowFlags_NoScrollbar = 8,
ImGuiWindowFlags_NoScrollWithMouse = 16,
ImGuiWindowFlags_NoCollapse = 32,
ImGuiWindowFlags_AlwaysAutoResize = 64,
ImGuiWindowFlags_NoBackground = 128,
ImGuiWindowFlags_NoSavedSettings = 256,
ImGuiWindowFlags_NoMouseInputs = 512,
ImGuiWindowFlags_MenuBar = 1024,
ImGuiWindowFlags_HorizontalScrollbar = 2048,
ImGuiWindowFlags_NoFocusOnAppearing = 4096,
ImGuiWindowFlags_NoBringToFrontOnFocus = 8192,
ImGuiWindowFlags_AlwaysVerticalScrollbar = 16384,
ImGuiWindowFlags_AlwaysHorizontalScrollbar = 32768,
ImGuiWindowFlags_AlwaysUseWindowPadding = 65536,
ImGuiWindowFlags_NoNavInputs = 262144,
ImGuiWindowFlags_NoNavFocus = 524288,
ImGuiWindowFlags_UnsavedDocument = 1048576,
ImGuiWindowFlags_NoDocking = 2097152,
ImGuiWindowFlags_NoNav = 786432,
ImGuiWindowFlags_NoDecoration = 43,
ImGuiWindowFlags_NoInputs = 786944,
ImGuiWindowFlags_NavFlattened = 8388608,
ImGuiWindowFlags_ChildWindow = 16777216,
ImGuiWindowFlags_Tooltip = 33554432,
ImGuiWindowFlags_Popup = 67108864,
ImGuiWindowFlags_Modal = 134217728,
ImGuiWindowFlags_ChildMenu = 268435456,
ImGuiWindowFlags_DockNodeHost = 536870912,
_,
};
pub const ImGuiWindowFlags_ = enum_unnamed_8;
pub const ImGuiInputTextFlags_None = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_None);
pub const ImGuiInputTextFlags_CharsDecimal = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CharsDecimal);
pub const ImGuiInputTextFlags_CharsHexadecimal = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CharsHexadecimal);
pub const ImGuiInputTextFlags_CharsUppercase = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CharsUppercase);
pub const ImGuiInputTextFlags_CharsNoBlank = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CharsNoBlank);
pub const ImGuiInputTextFlags_AutoSelectAll = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_AutoSelectAll);
pub const ImGuiInputTextFlags_EnterReturnsTrue = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_EnterReturnsTrue);
pub const ImGuiInputTextFlags_CallbackCompletion = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CallbackCompletion);
pub const ImGuiInputTextFlags_CallbackHistory = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CallbackHistory);
pub const ImGuiInputTextFlags_CallbackAlways = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CallbackAlways);
pub const ImGuiInputTextFlags_CallbackCharFilter = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CallbackCharFilter);
pub const ImGuiInputTextFlags_AllowTabInput = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_AllowTabInput);
pub const ImGuiInputTextFlags_CtrlEnterForNewLine = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CtrlEnterForNewLine);
pub const ImGuiInputTextFlags_NoHorizontalScroll = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_NoHorizontalScroll);
pub const ImGuiInputTextFlags_AlwaysInsertMode = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_AlwaysInsertMode);
pub const ImGuiInputTextFlags_ReadOnly = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_ReadOnly);
pub const ImGuiInputTextFlags_Password = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_Password);
pub const ImGuiInputTextFlags_NoUndoRedo = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_NoUndoRedo);
pub const ImGuiInputTextFlags_CharsScientific = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CharsScientific);
pub const ImGuiInputTextFlags_CallbackResize = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_CallbackResize);
pub const ImGuiInputTextFlags_Multiline = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_Multiline);
pub const ImGuiInputTextFlags_NoMarkEdited = @enumToInt(enum_unnamed_9.ImGuiInputTextFlags_NoMarkEdited);
const enum_unnamed_9 = extern enum(c_int) {
ImGuiInputTextFlags_None = 0,
ImGuiInputTextFlags_CharsDecimal = 1,
ImGuiInputTextFlags_CharsHexadecimal = 2,
ImGuiInputTextFlags_CharsUppercase = 4,
ImGuiInputTextFlags_CharsNoBlank = 8,
ImGuiInputTextFlags_AutoSelectAll = 16,
ImGuiInputTextFlags_EnterReturnsTrue = 32,
ImGuiInputTextFlags_CallbackCompletion = 64,
ImGuiInputTextFlags_CallbackHistory = 128,
ImGuiInputTextFlags_CallbackAlways = 256,
ImGuiInputTextFlags_CallbackCharFilter = 512,
ImGuiInputTextFlags_AllowTabInput = 1024,
ImGuiInputTextFlags_CtrlEnterForNewLine = 2048,
ImGuiInputTextFlags_NoHorizontalScroll = 4096,
ImGuiInputTextFlags_AlwaysInsertMode = 8192,
ImGuiInputTextFlags_ReadOnly = 16384,
ImGuiInputTextFlags_Password = <PASSWORD>,
ImGuiInputTextFlags_NoUndoRedo = 65536,
ImGuiInputTextFlags_CharsScientific = 131072,
ImGuiInputTextFlags_CallbackResize = 262144,
ImGuiInputTextFlags_Multiline = 1048576,
ImGuiInputTextFlags_NoMarkEdited = 2097152,
_,
};
pub const ImGuiInputTextFlags_ = enum_unnamed_9;
pub const ImGuiTreeNodeFlags_None = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_None);
pub const ImGuiTreeNodeFlags_Selected = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_Selected);
pub const ImGuiTreeNodeFlags_Framed = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_Framed);
pub const ImGuiTreeNodeFlags_AllowItemOverlap = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_AllowItemOverlap);
pub const ImGuiTreeNodeFlags_NoTreePushOnOpen = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_NoTreePushOnOpen);
pub const ImGuiTreeNodeFlags_NoAutoOpenOnLog = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_NoAutoOpenOnLog);
pub const ImGuiTreeNodeFlags_DefaultOpen = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_DefaultOpen);
pub const ImGuiTreeNodeFlags_OpenOnDoubleClick = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_OpenOnDoubleClick);
pub const ImGuiTreeNodeFlags_OpenOnArrow = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_OpenOnArrow);
pub const ImGuiTreeNodeFlags_Leaf = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_Leaf);
pub const ImGuiTreeNodeFlags_Bullet = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_Bullet);
pub const ImGuiTreeNodeFlags_FramePadding = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_FramePadding);
pub const ImGuiTreeNodeFlags_SpanAvailWidth = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_SpanAvailWidth);
pub const ImGuiTreeNodeFlags_SpanFullWidth = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_SpanFullWidth);
pub const ImGuiTreeNodeFlags_NavLeftJumpsBackHere = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_NavLeftJumpsBackHere);
pub const ImGuiTreeNodeFlags_CollapsingHeader = @enumToInt(enum_unnamed_10.ImGuiTreeNodeFlags_CollapsingHeader);
const enum_unnamed_10 = extern enum(c_int) {
ImGuiTreeNodeFlags_None = 0,
ImGuiTreeNodeFlags_Selected = 1,
ImGuiTreeNodeFlags_Framed = 2,
ImGuiTreeNodeFlags_AllowItemOverlap = 4,
ImGuiTreeNodeFlags_NoTreePushOnOpen = 8,
ImGuiTreeNodeFlags_NoAutoOpenOnLog = 16,
ImGuiTreeNodeFlags_DefaultOpen = 32,
ImGuiTreeNodeFlags_OpenOnDoubleClick = 64,
ImGuiTreeNodeFlags_OpenOnArrow = 128,
ImGuiTreeNodeFlags_Leaf = 256,
ImGuiTreeNodeFlags_Bullet = 512,
ImGuiTreeNodeFlags_FramePadding = 1024,
ImGuiTreeNodeFlags_SpanAvailWidth = 2048,
ImGuiTreeNodeFlags_SpanFullWidth = 4096,
ImGuiTreeNodeFlags_NavLeftJumpsBackHere = 8192,
ImGuiTreeNodeFlags_CollapsingHeader = 26,
_,
};
pub const ImGuiTreeNodeFlags_ = enum_unnamed_10;
pub const ImGuiSelectableFlags_None = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_None);
pub const ImGuiSelectableFlags_DontClosePopups = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_DontClosePopups);
pub const ImGuiSelectableFlags_SpanAllColumns = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_SpanAllColumns);
pub const ImGuiSelectableFlags_AllowDoubleClick = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_AllowDoubleClick);
pub const ImGuiSelectableFlags_Disabled = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_Disabled);
pub const ImGuiSelectableFlags_AllowItemOverlap = @enumToInt(enum_unnamed_11.ImGuiSelectableFlags_AllowItemOverlap);
const enum_unnamed_11 = extern enum(c_int) {
ImGuiSelectableFlags_None = 0,
ImGuiSelectableFlags_DontClosePopups = 1,
ImGuiSelectableFlags_SpanAllColumns = 2,
ImGuiSelectableFlags_AllowDoubleClick = 4,
ImGuiSelectableFlags_Disabled = 8,
ImGuiSelectableFlags_AllowItemOverlap = 16,
_,
};
pub const ImGuiSelectableFlags_ = enum_unnamed_11;
pub const ImGuiComboFlags_None = @enumToInt(enum_unnamed_12.ImGuiComboFlags_None);
pub const ImGuiComboFlags_PopupAlignLeft = @enumToInt(enum_unnamed_12.ImGuiComboFlags_PopupAlignLeft);
pub const ImGuiComboFlags_HeightSmall = @enumToInt(enum_unnamed_12.ImGuiComboFlags_HeightSmall);
pub const ImGuiComboFlags_HeightRegular = @enumToInt(enum_unnamed_12.ImGuiComboFlags_HeightRegular);
pub const ImGuiComboFlags_HeightLarge = @enumToInt(enum_unnamed_12.ImGuiComboFlags_HeightLarge);
pub const ImGuiComboFlags_HeightLargest = @enumToInt(enum_unnamed_12.ImGuiComboFlags_HeightLargest);
pub const ImGuiComboFlags_NoArrowButton = @enumToInt(enum_unnamed_12.ImGuiComboFlags_NoArrowButton);
pub const ImGuiComboFlags_NoPreview = @enumToInt(enum_unnamed_12.ImGuiComboFlags_NoPreview);
pub const ImGuiComboFlags_HeightMask_ = @enumToInt(enum_unnamed_12.ImGuiComboFlags_HeightMask_);
const enum_unnamed_12 = extern enum(c_int) {
ImGuiComboFlags_None = 0,
ImGuiComboFlags_PopupAlignLeft = 1,
ImGuiComboFlags_HeightSmall = 2,
ImGuiComboFlags_HeightRegular = 4,
ImGuiComboFlags_HeightLarge = 8,
ImGuiComboFlags_HeightLargest = 16,
ImGuiComboFlags_NoArrowButton = 32,
ImGuiComboFlags_NoPreview = 64,
ImGuiComboFlags_HeightMask_ = 30,
_,
};
pub const ImGuiComboFlags_ = enum_unnamed_12;
pub const ImGuiTabBarFlags_None = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_None);
pub const ImGuiTabBarFlags_Reorderable = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_Reorderable);
pub const ImGuiTabBarFlags_AutoSelectNewTabs = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_AutoSelectNewTabs);
pub const ImGuiTabBarFlags_TabListPopupButton = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_TabListPopupButton);
pub const ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_NoCloseWithMiddleMouseButton);
pub const ImGuiTabBarFlags_NoTabListScrollingButtons = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_NoTabListScrollingButtons);
pub const ImGuiTabBarFlags_NoTooltip = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_NoTooltip);
pub const ImGuiTabBarFlags_FittingPolicyResizeDown = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_FittingPolicyResizeDown);
pub const ImGuiTabBarFlags_FittingPolicyScroll = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_FittingPolicyScroll);
pub const ImGuiTabBarFlags_FittingPolicyMask_ = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_FittingPolicyMask_);
pub const ImGuiTabBarFlags_FittingPolicyDefault_ = @enumToInt(enum_unnamed_13.ImGuiTabBarFlags_FittingPolicyDefault_);
const enum_unnamed_13 = extern enum(c_int) {
ImGuiTabBarFlags_None = 0,
ImGuiTabBarFlags_Reorderable = 1,
ImGuiTabBarFlags_AutoSelectNewTabs = 2,
ImGuiTabBarFlags_TabListPopupButton = 4,
ImGuiTabBarFlags_NoCloseWithMiddleMouseButton = 8,
ImGuiTabBarFlags_NoTabListScrollingButtons = 16,
ImGuiTabBarFlags_NoTooltip = 32,
ImGuiTabBarFlags_FittingPolicyResizeDown = 64,
ImGuiTabBarFlags_FittingPolicyScroll = 128,
ImGuiTabBarFlags_FittingPolicyMask_ = 192,
ImGuiTabBarFlags_FittingPolicyDefault_ = 64,
_,
};
pub const ImGuiTabBarFlags_ = enum_unnamed_13;
pub const ImGuiTabItemFlags_None = @enumToInt(enum_unnamed_14.ImGuiTabItemFlags_None);
pub const ImGuiTabItemFlags_UnsavedDocument = @enumToInt(enum_unnamed_14.ImGuiTabItemFlags_UnsavedDocument);
pub const ImGuiTabItemFlags_SetSelected = @enumToInt(enum_unnamed_14.ImGuiTabItemFlags_SetSelected);
pub const ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = @enumToInt(enum_unnamed_14.ImGuiTabItemFlags_NoCloseWithMiddleMouseButton);
pub const ImGuiTabItemFlags_NoPushId = @enumToInt(enum_unnamed_14.ImGuiTabItemFlags_NoPushId);
const enum_unnamed_14 = extern enum(c_int) {
ImGuiTabItemFlags_None = 0,
ImGuiTabItemFlags_UnsavedDocument = 1,
ImGuiTabItemFlags_SetSelected = 2,
ImGuiTabItemFlags_NoCloseWithMiddleMouseButton = 4,
ImGuiTabItemFlags_NoPushId = 8,
_,
};
pub const ImGuiTabItemFlags_ = enum_unnamed_14;
pub const ImGuiFocusedFlags_None = @enumToInt(enum_unnamed_15.ImGuiFocusedFlags_None);
pub const ImGuiFocusedFlags_ChildWindows = @enumToInt(enum_unnamed_15.ImGuiFocusedFlags_ChildWindows);
pub const ImGuiFocusedFlags_RootWindow = @enumToInt(enum_unnamed_15.ImGuiFocusedFlags_RootWindow);
pub const ImGuiFocusedFlags_AnyWindow = @enumToInt(enum_unnamed_15.ImGuiFocusedFlags_AnyWindow);
pub const ImGuiFocusedFlags_RootAndChildWindows = @enumToInt(enum_unnamed_15.ImGuiFocusedFlags_RootAndChildWindows);
const enum_unnamed_15 = extern enum(c_int) {
ImGuiFocusedFlags_None = 0,
ImGuiFocusedFlags_ChildWindows = 1,
ImGuiFocusedFlags_RootWindow = 2,
ImGuiFocusedFlags_AnyWindow = 4,
ImGuiFocusedFlags_RootAndChildWindows = 3,
_,
};
pub const ImGuiFocusedFlags_ = enum_unnamed_15;
pub const ImGuiHoveredFlags_None = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_None);
pub const ImGuiHoveredFlags_ChildWindows = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_ChildWindows);
pub const ImGuiHoveredFlags_RootWindow = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_RootWindow);
pub const ImGuiHoveredFlags_AnyWindow = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_AnyWindow);
pub const ImGuiHoveredFlags_AllowWhenBlockedByPopup = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_AllowWhenBlockedByPopup);
pub const ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_AllowWhenBlockedByActiveItem);
pub const ImGuiHoveredFlags_AllowWhenOverlapped = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_AllowWhenOverlapped);
pub const ImGuiHoveredFlags_AllowWhenDisabled = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_AllowWhenDisabled);
pub const ImGuiHoveredFlags_RectOnly = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_RectOnly);
pub const ImGuiHoveredFlags_RootAndChildWindows = @enumToInt(enum_unnamed_16.ImGuiHoveredFlags_RootAndChildWindows);
const enum_unnamed_16 = extern enum(c_int) {
ImGuiHoveredFlags_None = 0,
ImGuiHoveredFlags_ChildWindows = 1,
ImGuiHoveredFlags_RootWindow = 2,
ImGuiHoveredFlags_AnyWindow = 4,
ImGuiHoveredFlags_AllowWhenBlockedByPopup = 8,
ImGuiHoveredFlags_AllowWhenBlockedByActiveItem = 32,
ImGuiHoveredFlags_AllowWhenOverlapped = 64,
ImGuiHoveredFlags_AllowWhenDisabled = 128,
ImGuiHoveredFlags_RectOnly = 104,
ImGuiHoveredFlags_RootAndChildWindows = 3,
_,
};
pub const ImGuiHoveredFlags_ = enum_unnamed_16;
pub const ImGuiDockNodeFlags_None = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_None);
pub const ImGuiDockNodeFlags_KeepAliveOnly = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_KeepAliveOnly);
pub const ImGuiDockNodeFlags_NoDockingInCentralNode = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_NoDockingInCentralNode);
pub const ImGuiDockNodeFlags_PassthruCentralNode = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_PassthruCentralNode);
pub const ImGuiDockNodeFlags_NoSplit = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_NoSplit);
pub const ImGuiDockNodeFlags_NoResize = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_NoResize);
pub const ImGuiDockNodeFlags_AutoHideTabBar = @enumToInt(enum_unnamed_17.ImGuiDockNodeFlags_AutoHideTabBar);
const enum_unnamed_17 = extern enum(c_int) {
ImGuiDockNodeFlags_None = 0,
ImGuiDockNodeFlags_KeepAliveOnly = 1,
ImGuiDockNodeFlags_NoDockingInCentralNode = 4,
ImGuiDockNodeFlags_PassthruCentralNode = 8,
ImGuiDockNodeFlags_NoSplit = 16,
ImGuiDockNodeFlags_NoResize = 32,
ImGuiDockNodeFlags_AutoHideTabBar = 64,
_,
};
pub const ImGuiDockNodeFlags_ = enum_unnamed_17;
pub const ImGuiDragDropFlags_None = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_None);
pub const ImGuiDragDropFlags_SourceNoPreviewTooltip = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceNoPreviewTooltip);
pub const ImGuiDragDropFlags_SourceNoDisableHover = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceNoDisableHover);
pub const ImGuiDragDropFlags_SourceNoHoldToOpenOthers = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceNoHoldToOpenOthers);
pub const ImGuiDragDropFlags_SourceAllowNullID = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceAllowNullID);
pub const ImGuiDragDropFlags_SourceExtern = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceExtern);
pub const ImGuiDragDropFlags_SourceAutoExpirePayload = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_SourceAutoExpirePayload);
pub const ImGuiDragDropFlags_AcceptBeforeDelivery = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_AcceptBeforeDelivery);
pub const ImGuiDragDropFlags_AcceptNoDrawDefaultRect = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_AcceptNoDrawDefaultRect);
pub const ImGuiDragDropFlags_AcceptNoPreviewTooltip = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_AcceptNoPreviewTooltip);
pub const ImGuiDragDropFlags_AcceptPeekOnly = @enumToInt(enum_unnamed_18.ImGuiDragDropFlags_AcceptPeekOnly);
const enum_unnamed_18 = extern enum(c_int) {
ImGuiDragDropFlags_None = 0,
ImGuiDragDropFlags_SourceNoPreviewTooltip = 1,
ImGuiDragDropFlags_SourceNoDisableHover = 2,
ImGuiDragDropFlags_SourceNoHoldToOpenOthers = 4,
ImGuiDragDropFlags_SourceAllowNullID = 8,
ImGuiDragDropFlags_SourceExtern = 16,
ImGuiDragDropFlags_SourceAutoExpirePayload = 32,
ImGuiDragDropFlags_AcceptBeforeDelivery = 1024,
ImGuiDragDropFlags_AcceptNoDrawDefaultRect = 2048,
ImGuiDragDropFlags_AcceptNoPreviewTooltip = 4096,
ImGuiDragDropFlags_AcceptPeekOnly = 3072,
_,
};
pub const ImGuiDragDropFlags_ = enum_unnamed_18;
pub const ImGuiDataType_S8 = @enumToInt(enum_unnamed_19.ImGuiDataType_S8);
pub const ImGuiDataType_U8 = @enumToInt(enum_unnamed_19.ImGuiDataType_U8);
pub const ImGuiDataType_S16 = @enumToInt(enum_unnamed_19.ImGuiDataType_S16);
pub const ImGuiDataType_U16 = @enumToInt(enum_unnamed_19.ImGuiDataType_U16);
pub const ImGuiDataType_S32 = @enumToInt(enum_unnamed_19.ImGuiDataType_S32);
pub const ImGuiDataType_U32 = @enumToInt(enum_unnamed_19.ImGuiDataType_U32);
pub const ImGuiDataType_S64 = @enumToInt(enum_unnamed_19.ImGuiDataType_S64);
pub const ImGuiDataType_U64 = @enumToInt(enum_unnamed_19.ImGuiDataType_U64);
pub const ImGuiDataType_Float = @enumToInt(enum_unnamed_19.ImGuiDataType_Float);
pub const ImGuiDataType_Double = @enumToInt(enum_unnamed_19.ImGuiDataType_Double);
pub const ImGuiDataType_COUNT = @enumToInt(enum_unnamed_19.ImGuiDataType_COUNT);
const enum_unnamed_19 = extern enum(c_int) {
ImGuiDataType_S8,
ImGuiDataType_U8,
ImGuiDataType_S16,
ImGuiDataType_U16,
ImGuiDataType_S32,
ImGuiDataType_U32,
ImGuiDataType_S64,
ImGuiDataType_U64,
ImGuiDataType_Float,
ImGuiDataType_Double,
ImGuiDataType_COUNT,
_,
};
pub const ImGuiDataType_ = enum_unnamed_19;
pub const ImGuiDir_None = @enumToInt(enum_unnamed_20.ImGuiDir_None);
pub const ImGuiDir_Left = @enumToInt(enum_unnamed_20.ImGuiDir_Left);
pub const ImGuiDir_Right = @enumToInt(enum_unnamed_20.ImGuiDir_Right);
pub const ImGuiDir_Up = @enumToInt(enum_unnamed_20.ImGuiDir_Up);
pub const ImGuiDir_Down = @enumToInt(enum_unnamed_20.ImGuiDir_Down);
pub const ImGuiDir_COUNT = @enumToInt(enum_unnamed_20.ImGuiDir_COUNT);
const enum_unnamed_20 = extern enum(c_int) {
ImGuiDir_None = -1,
ImGuiDir_Left = 0,
ImGuiDir_Right = 1,
ImGuiDir_Up = 2,
ImGuiDir_Down = 3,
ImGuiDir_COUNT = 4,
_,
};
pub const ImGuiDir_ = enum_unnamed_20;
pub const ImGuiKey_Tab = @enumToInt(enum_unnamed_21.ImGuiKey_Tab);
pub const ImGuiKey_LeftArrow = @enumToInt(enum_unnamed_21.ImGuiKey_LeftArrow);
pub const ImGuiKey_RightArrow = @enumToInt(enum_unnamed_21.ImGuiKey_RightArrow);
pub const ImGuiKey_UpArrow = @enumToInt(enum_unnamed_21.ImGuiKey_UpArrow);
pub const ImGuiKey_DownArrow = @enumToInt(enum_unnamed_21.ImGuiKey_DownArrow);
pub const ImGuiKey_PageUp = @enumToInt(enum_unnamed_21.ImGuiKey_PageUp);
pub const ImGuiKey_PageDown = @enumToInt(enum_unnamed_21.ImGuiKey_PageDown);
pub const ImGuiKey_Home = @enumToInt(enum_unnamed_21.ImGuiKey_Home);
pub const ImGuiKey_End = @enumToInt(enum_unnamed_21.ImGuiKey_End);
pub const ImGuiKey_Insert = @enumToInt(enum_unnamed_21.ImGuiKey_Insert);
pub const ImGuiKey_Delete = @enumToInt(enum_unnamed_21.ImGuiKey_Delete);
pub const ImGuiKey_Backspace = @enumToInt(enum_unnamed_21.ImGuiKey_Backspace);
pub const ImGuiKey_Space = @enumToInt(enum_unnamed_21.ImGuiKey_Space);
pub const ImGuiKey_Enter = @enumToInt(enum_unnamed_21.ImGuiKey_Enter);
pub const ImGuiKey_Escape = @enumToInt(enum_unnamed_21.ImGuiKey_Escape);
pub const ImGuiKey_KeyPadEnter = @enumToInt(enum_unnamed_21.ImGuiKey_KeyPadEnter);
pub const ImGuiKey_A = @enumToInt(enum_unnamed_21.ImGuiKey_A);
pub const ImGuiKey_C = @enumToInt(enum_unnamed_21.ImGuiKey_C);
pub const ImGuiKey_V = @enumToInt(enum_unnamed_21.ImGuiKey_V);
pub const ImGuiKey_X = @enumToInt(enum_unnamed_21.ImGuiKey_X);
pub const ImGuiKey_Y = @enumToInt(enum_unnamed_21.ImGuiKey_Y);
pub const ImGuiKey_Z = @enumToInt(enum_unnamed_21.ImGuiKey_Z);
pub const ImGuiKey_COUNT = @enumToInt(enum_unnamed_21.ImGuiKey_COUNT);
const enum_unnamed_21 = extern enum(c_int) {
ImGuiKey_Tab,
ImGuiKey_LeftArrow,
ImGuiKey_RightArrow,
ImGuiKey_UpArrow,
ImGuiKey_DownArrow,
ImGuiKey_PageUp,
ImGuiKey_PageDown,
ImGuiKey_Home,
ImGuiKey_End,
ImGuiKey_Insert,
ImGuiKey_Delete,
ImGuiKey_Backspace,
ImGuiKey_Space,
ImGuiKey_Enter,
ImGuiKey_Escape,
ImGuiKey_KeyPadEnter,
ImGuiKey_A,
ImGuiKey_C,
ImGuiKey_V,
ImGuiKey_X,
ImGuiKey_Y,
ImGuiKey_Z,
ImGuiKey_COUNT,
_,
};
pub const ImGuiKey_ = enum_unnamed_21;
pub const ImGuiKeyModFlags_None = @enumToInt(enum_unnamed_22.ImGuiKeyModFlags_None);
pub const ImGuiKeyModFlags_Ctrl = @enumToInt(enum_unnamed_22.ImGuiKeyModFlags_Ctrl);
pub const ImGuiKeyModFlags_Shift = @enumToInt(enum_unnamed_22.ImGuiKeyModFlags_Shift);
pub const ImGuiKeyModFlags_Alt = @enumToInt(enum_unnamed_22.ImGuiKeyModFlags_Alt);
pub const ImGuiKeyModFlags_Super = @enumToInt(enum_unnamed_22.ImGuiKeyModFlags_Super);
const enum_unnamed_22 = extern enum(c_int) {
ImGuiKeyModFlags_None = 0,
ImGuiKeyModFlags_Ctrl = 1,
ImGuiKeyModFlags_Shift = 2,
ImGuiKeyModFlags_Alt = 4,
ImGuiKeyModFlags_Super = 8,
_,
};
pub const ImGuiKeyModFlags_ = enum_unnamed_22;
pub const ImGuiNavInput_Activate = @enumToInt(enum_unnamed_23.ImGuiNavInput_Activate);
pub const ImGuiNavInput_Cancel = @enumToInt(enum_unnamed_23.ImGuiNavInput_Cancel);
pub const ImGuiNavInput_Input = @enumToInt(enum_unnamed_23.ImGuiNavInput_Input);
pub const ImGuiNavInput_Menu = @enumToInt(enum_unnamed_23.ImGuiNavInput_Menu);
pub const ImGuiNavInput_DpadLeft = @enumToInt(enum_unnamed_23.ImGuiNavInput_DpadLeft);
pub const ImGuiNavInput_DpadRight = @enumToInt(enum_unnamed_23.ImGuiNavInput_DpadRight);
pub const ImGuiNavInput_DpadUp = @enumToInt(enum_unnamed_23.ImGuiNavInput_DpadUp);
pub const ImGuiNavInput_DpadDown = @enumToInt(enum_unnamed_23.ImGuiNavInput_DpadDown);
pub const ImGuiNavInput_LStickLeft = @enumToInt(enum_unnamed_23.ImGuiNavInput_LStickLeft);
pub const ImGuiNavInput_LStickRight = @enumToInt(enum_unnamed_23.ImGuiNavInput_LStickRight);
pub const ImGuiNavInput_LStickUp = @enumToInt(enum_unnamed_23.ImGuiNavInput_LStickUp);
pub const ImGuiNavInput_LStickDown = @enumToInt(enum_unnamed_23.ImGuiNavInput_LStickDown);
pub const ImGuiNavInput_FocusPrev = @enumToInt(enum_unnamed_23.ImGuiNavInput_FocusPrev);
pub const ImGuiNavInput_FocusNext = @enumToInt(enum_unnamed_23.ImGuiNavInput_FocusNext);
pub const ImGuiNavInput_TweakSlow = @enumToInt(enum_unnamed_23.ImGuiNavInput_TweakSlow);
pub const ImGuiNavInput_TweakFast = @enumToInt(enum_unnamed_23.ImGuiNavInput_TweakFast);
pub const ImGuiNavInput_KeyMenu_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_KeyMenu_);
pub const ImGuiNavInput_KeyLeft_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_KeyLeft_);
pub const ImGuiNavInput_KeyRight_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_KeyRight_);
pub const ImGuiNavInput_KeyUp_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_KeyUp_);
pub const ImGuiNavInput_KeyDown_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_KeyDown_);
pub const ImGuiNavInput_COUNT = @enumToInt(enum_unnamed_23.ImGuiNavInput_COUNT);
pub const ImGuiNavInput_InternalStart_ = @enumToInt(enum_unnamed_23.ImGuiNavInput_InternalStart_);
const enum_unnamed_23 = extern enum(c_int) {
ImGuiNavInput_Activate = 0,
ImGuiNavInput_Cancel = 1,
ImGuiNavInput_Input = 2,
ImGuiNavInput_Menu = 3,
ImGuiNavInput_DpadLeft = 4,
ImGuiNavInput_DpadRight = 5,
ImGuiNavInput_DpadUp = 6,
ImGuiNavInput_DpadDown = 7,
ImGuiNavInput_LStickLeft = 8,
ImGuiNavInput_LStickRight = 9,
ImGuiNavInput_LStickUp = 10,
ImGuiNavInput_LStickDown = 11,
ImGuiNavInput_FocusPrev = 12,
ImGuiNavInput_FocusNext = 13,
ImGuiNavInput_TweakSlow = 14,
ImGuiNavInput_TweakFast = 15,
ImGuiNavInput_KeyMenu_ = 16,
ImGuiNavInput_KeyLeft_ = 17,
ImGuiNavInput_KeyRight_ = 18,
ImGuiNavInput_KeyUp_ = 19,
ImGuiNavInput_KeyDown_ = 20,
ImGuiNavInput_COUNT = 21,
ImGuiNavInput_InternalStart_ = 16,
_,
};
pub const ImGuiNavInput_ = enum_unnamed_23;
pub const ImGuiConfigFlags_None = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_None);
pub const ImGuiConfigFlags_NavEnableKeyboard = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NavEnableKeyboard);
pub const ImGuiConfigFlags_NavEnableGamepad = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NavEnableGamepad);
pub const ImGuiConfigFlags_NavEnableSetMousePos = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NavEnableSetMousePos);
pub const ImGuiConfigFlags_NavNoCaptureKeyboard = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NavNoCaptureKeyboard);
pub const ImGuiConfigFlags_NoMouse = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NoMouse);
pub const ImGuiConfigFlags_NoMouseCursorChange = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_NoMouseCursorChange);
pub const ImGuiConfigFlags_DockingEnable = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_DockingEnable);
pub const ImGuiConfigFlags_ViewportsEnable = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_ViewportsEnable);
pub const ImGuiConfigFlags_DpiEnableScaleViewports = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_DpiEnableScaleViewports);
pub const ImGuiConfigFlags_DpiEnableScaleFonts = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_DpiEnableScaleFonts);
pub const ImGuiConfigFlags_IsSRGB = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_IsSRGB);
pub const ImGuiConfigFlags_IsTouchScreen = @enumToInt(enum_unnamed_24.ImGuiConfigFlags_IsTouchScreen);
const enum_unnamed_24 = extern enum(c_int) {
ImGuiConfigFlags_None = 0,
ImGuiConfigFlags_NavEnableKeyboard = 1,
ImGuiConfigFlags_NavEnableGamepad = 2,
ImGuiConfigFlags_NavEnableSetMousePos = 4,
ImGuiConfigFlags_NavNoCaptureKeyboard = 8,
ImGuiConfigFlags_NoMouse = 16,
ImGuiConfigFlags_NoMouseCursorChange = 32,
ImGuiConfigFlags_DockingEnable = 64,
ImGuiConfigFlags_ViewportsEnable = 1024,
ImGuiConfigFlags_DpiEnableScaleViewports = 16384,
ImGuiConfigFlags_DpiEnableScaleFonts = 32768,
ImGuiConfigFlags_IsSRGB = 1048576,
ImGuiConfigFlags_IsTouchScreen = 2097152,
_,
};
pub const ImGuiConfigFlags_ = enum_unnamed_24;
pub const ImGuiBackendFlags_None = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_None);
pub const ImGuiBackendFlags_HasGamepad = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_HasGamepad);
pub const ImGuiBackendFlags_HasMouseCursors = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_HasMouseCursors);
pub const ImGuiBackendFlags_HasSetMousePos = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_HasSetMousePos);
pub const ImGuiBackendFlags_RendererHasVtxOffset = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_RendererHasVtxOffset);
pub const ImGuiBackendFlags_PlatformHasViewports = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_PlatformHasViewports);
pub const ImGuiBackendFlags_HasMouseHoveredViewport = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_HasMouseHoveredViewport);
pub const ImGuiBackendFlags_RendererHasViewports = @enumToInt(enum_unnamed_25.ImGuiBackendFlags_RendererHasViewports);
const enum_unnamed_25 = extern enum(c_int) {
ImGuiBackendFlags_None = 0,
ImGuiBackendFlags_HasGamepad = 1,
ImGuiBackendFlags_HasMouseCursors = 2,
ImGuiBackendFlags_HasSetMousePos = 4,
ImGuiBackendFlags_RendererHasVtxOffset = 8,
ImGuiBackendFlags_PlatformHasViewports = 1024,
ImGuiBackendFlags_HasMouseHoveredViewport = 2048,
ImGuiBackendFlags_RendererHasViewports = 4096,
_,
};
pub const ImGuiBackendFlags_ = enum_unnamed_25;
pub const ImGuiCol_Text = @enumToInt(enum_unnamed_26.ImGuiCol_Text);
pub const ImGuiCol_TextDisabled = @enumToInt(enum_unnamed_26.ImGuiCol_TextDisabled);
pub const ImGuiCol_WindowBg = @enumToInt(enum_unnamed_26.ImGuiCol_WindowBg);
pub const ImGuiCol_ChildBg = @enumToInt(enum_unnamed_26.ImGuiCol_ChildBg);
pub const ImGuiCol_PopupBg = @enumToInt(enum_unnamed_26.ImGuiCol_PopupBg);
pub const ImGuiCol_Border = @enumToInt(enum_unnamed_26.ImGuiCol_Border);
pub const ImGuiCol_BorderShadow = @enumToInt(enum_unnamed_26.ImGuiCol_BorderShadow);
pub const ImGuiCol_FrameBg = @enumToInt(enum_unnamed_26.ImGuiCol_FrameBg);
pub const ImGuiCol_FrameBgHovered = @enumToInt(enum_unnamed_26.ImGuiCol_FrameBgHovered);
pub const ImGuiCol_FrameBgActive = @enumToInt(enum_unnamed_26.ImGuiCol_FrameBgActive);
pub const ImGuiCol_TitleBg = @enumToInt(enum_unnamed_26.ImGuiCol_TitleBg);
pub const ImGuiCol_TitleBgActive = @enumToInt(enum_unnamed_26.ImGuiCol_TitleBgActive);
pub const ImGuiCol_TitleBgCollapsed = @enumToInt(enum_unnamed_26.ImGuiCol_TitleBgCollapsed);
pub const ImGuiCol_MenuBarBg = @enumToInt(enum_unnamed_26.ImGuiCol_MenuBarBg);
pub const ImGuiCol_ScrollbarBg = @enumToInt(enum_unnamed_26.ImGuiCol_ScrollbarBg);
pub const ImGuiCol_ScrollbarGrab = @enumToInt(enum_unnamed_26.ImGuiCol_ScrollbarGrab);
pub const ImGuiCol_ScrollbarGrabHovered = @enumToInt(enum_unnamed_26.ImGuiCol_ScrollbarGrabHovered);
pub const ImGuiCol_ScrollbarGrabActive = @enumToInt(enum_unnamed_26.ImGuiCol_ScrollbarGrabActive);
pub const ImGuiCol_CheckMark = @enumToInt(enum_unnamed_26.ImGuiCol_CheckMark);
pub const ImGuiCol_SliderGrab = @enumToInt(enum_unnamed_26.ImGuiCol_SliderGrab);
pub const ImGuiCol_SliderGrabActive = @enumToInt(enum_unnamed_26.ImGuiCol_SliderGrabActive);
pub const ImGuiCol_Button = @enumToInt(enum_unnamed_26.ImGuiCol_Button);
pub const ImGuiCol_ButtonHovered = @enumToInt(enum_unnamed_26.ImGuiCol_ButtonHovered);
pub const ImGuiCol_ButtonActive = @enumToInt(enum_unnamed_26.ImGuiCol_ButtonActive);
pub const ImGuiCol_Header = @enumToInt(enum_unnamed_26.ImGuiCol_Header);
pub const ImGuiCol_HeaderHovered = @enumToInt(enum_unnamed_26.ImGuiCol_HeaderHovered);
pub const ImGuiCol_HeaderActive = @enumToInt(enum_unnamed_26.ImGuiCol_HeaderActive);
pub const ImGuiCol_Separator = @enumToInt(enum_unnamed_26.ImGuiCol_Separator);
pub const ImGuiCol_SeparatorHovered = @enumToInt(enum_unnamed_26.ImGuiCol_SeparatorHovered);
pub const ImGuiCol_SeparatorActive = @enumToInt(enum_unnamed_26.ImGuiCol_SeparatorActive);
pub const ImGuiCol_ResizeGrip = @enumToInt(enum_unnamed_26.ImGuiCol_ResizeGrip);
pub const ImGuiCol_ResizeGripHovered = @enumToInt(enum_unnamed_26.ImGuiCol_ResizeGripHovered);
pub const ImGuiCol_ResizeGripActive = @enumToInt(enum_unnamed_26.ImGuiCol_ResizeGripActive);
pub const ImGuiCol_Tab = @enumToInt(enum_unnamed_26.ImGuiCol_Tab);
pub const ImGuiCol_TabHovered = @enumToInt(enum_unnamed_26.ImGuiCol_TabHovered);
pub const ImGuiCol_TabActive = @enumToInt(enum_unnamed_26.ImGuiCol_TabActive);
pub const ImGuiCol_TabUnfocused = @enumToInt(enum_unnamed_26.ImGuiCol_TabUnfocused);
pub const ImGuiCol_TabUnfocusedActive = @enumToInt(enum_unnamed_26.ImGuiCol_TabUnfocusedActive);
pub const ImGuiCol_DockingPreview = @enumToInt(enum_unnamed_26.ImGuiCol_DockingPreview);
pub const ImGuiCol_DockingEmptyBg = @enumToInt(enum_unnamed_26.ImGuiCol_DockingEmptyBg);
pub const ImGuiCol_PlotLines = @enumToInt(enum_unnamed_26.ImGuiCol_PlotLines);
pub const ImGuiCol_PlotLinesHovered = @enumToInt(enum_unnamed_26.ImGuiCol_PlotLinesHovered);
pub const ImGuiCol_PlotHistogram = @enumToInt(enum_unnamed_26.ImGuiCol_PlotHistogram);
pub const ImGuiCol_PlotHistogramHovered = @enumToInt(enum_unnamed_26.ImGuiCol_PlotHistogramHovered);
pub const ImGuiCol_TextSelectedBg = @enumToInt(enum_unnamed_26.ImGuiCol_TextSelectedBg);
pub const ImGuiCol_DragDropTarget = @enumToInt(enum_unnamed_26.ImGuiCol_DragDropTarget);
pub const ImGuiCol_NavHighlight = @enumToInt(enum_unnamed_26.ImGuiCol_NavHighlight);
pub const ImGuiCol_NavWindowingHighlight = @enumToInt(enum_unnamed_26.ImGuiCol_NavWindowingHighlight);
pub const ImGuiCol_NavWindowingDimBg = @enumToInt(enum_unnamed_26.ImGuiCol_NavWindowingDimBg);
pub const ImGuiCol_ModalWindowDimBg = @enumToInt(enum_unnamed_26.ImGuiCol_ModalWindowDimBg);
pub const ImGuiCol_COUNT = @enumToInt(enum_unnamed_26.ImGuiCol_COUNT);
const enum_unnamed_26 = extern enum(c_int) {
ImGuiCol_Text,
ImGuiCol_TextDisabled,
ImGuiCol_WindowBg,
ImGuiCol_ChildBg,
ImGuiCol_PopupBg,
ImGuiCol_Border,
ImGuiCol_BorderShadow,
ImGuiCol_FrameBg,
ImGuiCol_FrameBgHovered,
ImGuiCol_FrameBgActive,
ImGuiCol_TitleBg,
ImGuiCol_TitleBgActive,
ImGuiCol_TitleBgCollapsed,
ImGuiCol_MenuBarBg,
ImGuiCol_ScrollbarBg,
ImGuiCol_ScrollbarGrab,
ImGuiCol_ScrollbarGrabHovered,
ImGuiCol_ScrollbarGrabActive,
ImGuiCol_CheckMark,
ImGuiCol_SliderGrab,
ImGuiCol_SliderGrabActive,
ImGuiCol_Button,
ImGuiCol_ButtonHovered,
ImGuiCol_ButtonActive,
ImGuiCol_Header,
ImGuiCol_HeaderHovered,
ImGuiCol_HeaderActive,
ImGuiCol_Separator,
ImGuiCol_SeparatorHovered,
ImGuiCol_SeparatorActive,
ImGuiCol_ResizeGrip,
ImGuiCol_ResizeGripHovered,
ImGuiCol_ResizeGripActive,
ImGuiCol_Tab,
ImGuiCol_TabHovered,
ImGuiCol_TabActive,
ImGuiCol_TabUnfocused,
ImGuiCol_TabUnfocusedActive,
ImGuiCol_DockingPreview,
ImGuiCol_DockingEmptyBg,
ImGuiCol_PlotLines,
ImGuiCol_PlotLinesHovered,
ImGuiCol_PlotHistogram,
ImGuiCol_PlotHistogramHovered,
ImGuiCol_TextSelectedBg,
ImGuiCol_DragDropTarget,
ImGuiCol_NavHighlight,
ImGuiCol_NavWindowingHighlight,
ImGuiCol_NavWindowingDimBg,
ImGuiCol_ModalWindowDimBg,
ImGuiCol_COUNT,
_,
};
pub const ImGuiCol_ = enum_unnamed_26;
pub const ImGuiStyleVar_Alpha = @enumToInt(enum_unnamed_27.ImGuiStyleVar_Alpha);
pub const ImGuiStyleVar_WindowPadding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_WindowPadding);
pub const ImGuiStyleVar_WindowRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_WindowRounding);
pub const ImGuiStyleVar_WindowBorderSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_WindowBorderSize);
pub const ImGuiStyleVar_WindowMinSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_WindowMinSize);
pub const ImGuiStyleVar_WindowTitleAlign = @enumToInt(enum_unnamed_27.ImGuiStyleVar_WindowTitleAlign);
pub const ImGuiStyleVar_ChildRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ChildRounding);
pub const ImGuiStyleVar_ChildBorderSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ChildBorderSize);
pub const ImGuiStyleVar_PopupRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_PopupRounding);
pub const ImGuiStyleVar_PopupBorderSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_PopupBorderSize);
pub const ImGuiStyleVar_FramePadding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_FramePadding);
pub const ImGuiStyleVar_FrameRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_FrameRounding);
pub const ImGuiStyleVar_FrameBorderSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_FrameBorderSize);
pub const ImGuiStyleVar_ItemSpacing = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ItemSpacing);
pub const ImGuiStyleVar_ItemInnerSpacing = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ItemInnerSpacing);
pub const ImGuiStyleVar_IndentSpacing = @enumToInt(enum_unnamed_27.ImGuiStyleVar_IndentSpacing);
pub const ImGuiStyleVar_ScrollbarSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ScrollbarSize);
pub const ImGuiStyleVar_ScrollbarRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ScrollbarRounding);
pub const ImGuiStyleVar_GrabMinSize = @enumToInt(enum_unnamed_27.ImGuiStyleVar_GrabMinSize);
pub const ImGuiStyleVar_GrabRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_GrabRounding);
pub const ImGuiStyleVar_TabRounding = @enumToInt(enum_unnamed_27.ImGuiStyleVar_TabRounding);
pub const ImGuiStyleVar_ButtonTextAlign = @enumToInt(enum_unnamed_27.ImGuiStyleVar_ButtonTextAlign);
pub const ImGuiStyleVar_SelectableTextAlign = @enumToInt(enum_unnamed_27.ImGuiStyleVar_SelectableTextAlign);
pub const ImGuiStyleVar_COUNT = @enumToInt(enum_unnamed_27.ImGuiStyleVar_COUNT);
const enum_unnamed_27 = extern enum(c_int) {
ImGuiStyleVar_Alpha,
ImGuiStyleVar_WindowPadding,
ImGuiStyleVar_WindowRounding,
ImGuiStyleVar_WindowBorderSize,
ImGuiStyleVar_WindowMinSize,
ImGuiStyleVar_WindowTitleAlign,
ImGuiStyleVar_ChildRounding,
ImGuiStyleVar_ChildBorderSize,
ImGuiStyleVar_PopupRounding,
ImGuiStyleVar_PopupBorderSize,
ImGuiStyleVar_FramePadding,
ImGuiStyleVar_FrameRounding,
ImGuiStyleVar_FrameBorderSize,
ImGuiStyleVar_ItemSpacing,
ImGuiStyleVar_ItemInnerSpacing,
ImGuiStyleVar_IndentSpacing,
ImGuiStyleVar_ScrollbarSize,
ImGuiStyleVar_ScrollbarRounding,
ImGuiStyleVar_GrabMinSize,
ImGuiStyleVar_GrabRounding,
ImGuiStyleVar_TabRounding,
ImGuiStyleVar_ButtonTextAlign,
ImGuiStyleVar_SelectableTextAlign,
ImGuiStyleVar_COUNT,
_,
};
pub const ImGuiStyleVar_ = enum_unnamed_27;
pub const ImGuiColorEditFlags_None = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_None);
pub const ImGuiColorEditFlags_NoAlpha = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoAlpha);
pub const ImGuiColorEditFlags_NoPicker = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoPicker);
pub const ImGuiColorEditFlags_NoOptions = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoOptions);
pub const ImGuiColorEditFlags_NoSmallPreview = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoSmallPreview);
pub const ImGuiColorEditFlags_NoInputs = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoInputs);
pub const ImGuiColorEditFlags_NoTooltip = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoTooltip);
pub const ImGuiColorEditFlags_NoLabel = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoLabel);
pub const ImGuiColorEditFlags_NoSidePreview = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoSidePreview);
pub const ImGuiColorEditFlags_NoDragDrop = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoDragDrop);
pub const ImGuiColorEditFlags_NoBorder = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_NoBorder);
pub const ImGuiColorEditFlags_AlphaBar = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_AlphaBar);
pub const ImGuiColorEditFlags_AlphaPreview = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_AlphaPreview);
pub const ImGuiColorEditFlags_AlphaPreviewHalf = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_AlphaPreviewHalf);
pub const ImGuiColorEditFlags_HDR = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_HDR);
pub const ImGuiColorEditFlags_DisplayRGB = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_DisplayRGB);
pub const ImGuiColorEditFlags_DisplayHSV = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_DisplayHSV);
pub const ImGuiColorEditFlags_DisplayHex = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_DisplayHex);
pub const ImGuiColorEditFlags_Uint8 = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_Uint8);
pub const ImGuiColorEditFlags_Float = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_Float);
pub const ImGuiColorEditFlags_PickerHueBar = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_PickerHueBar);
pub const ImGuiColorEditFlags_PickerHueWheel = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_PickerHueWheel);
pub const ImGuiColorEditFlags_InputRGB = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_InputRGB);
pub const ImGuiColorEditFlags_InputHSV = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags_InputHSV);
pub const ImGuiColorEditFlags__OptionsDefault = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags__OptionsDefault);
pub const ImGuiColorEditFlags__DisplayMask = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags__DisplayMask);
pub const ImGuiColorEditFlags__DataTypeMask = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags__DataTypeMask);
pub const ImGuiColorEditFlags__PickerMask = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags__PickerMask);
pub const ImGuiColorEditFlags__InputMask = @enumToInt(enum_unnamed_28.ImGuiColorEditFlags__InputMask);
const enum_unnamed_28 = extern enum(c_int) {
ImGuiColorEditFlags_None = 0,
ImGuiColorEditFlags_NoAlpha = 2,
ImGuiColorEditFlags_NoPicker = 4,
ImGuiColorEditFlags_NoOptions = 8,
ImGuiColorEditFlags_NoSmallPreview = 16,
ImGuiColorEditFlags_NoInputs = 32,
ImGuiColorEditFlags_NoTooltip = 64,
ImGuiColorEditFlags_NoLabel = 128,
ImGuiColorEditFlags_NoSidePreview = 256,
ImGuiColorEditFlags_NoDragDrop = 512,
ImGuiColorEditFlags_NoBorder = 1024,
ImGuiColorEditFlags_AlphaBar = 65536,
ImGuiColorEditFlags_AlphaPreview = 131072,
ImGuiColorEditFlags_AlphaPreviewHalf = 262144,
ImGuiColorEditFlags_HDR = 524288,
ImGuiColorEditFlags_DisplayRGB = 1048576,
ImGuiColorEditFlags_DisplayHSV = 2097152,
ImGuiColorEditFlags_DisplayHex = 4194304,
ImGuiColorEditFlags_Uint8 = 8388608,
ImGuiColorEditFlags_Float = 16777216,
ImGuiColorEditFlags_PickerHueBar = 33554432,
ImGuiColorEditFlags_PickerHueWheel = 67108864,
ImGuiColorEditFlags_InputRGB = 134217728,
ImGuiColorEditFlags_InputHSV = 268435456,
ImGuiColorEditFlags__OptionsDefault = 177209344,
ImGuiColorEditFlags__DisplayMask = 7340032,
ImGuiColorEditFlags__DataTypeMask = 25165824,
ImGuiColorEditFlags__PickerMask = 100663296,
ImGuiColorEditFlags__InputMask = 402653184,
_,
};
pub const ImGuiColorEditFlags_ = enum_unnamed_28;
pub const ImGuiMouseButton_Left = @enumToInt(enum_unnamed_29.ImGuiMouseButton_Left);
pub const ImGuiMouseButton_Right = @enumToInt(enum_unnamed_29.ImGuiMouseButton_Right);
pub const ImGuiMouseButton_Middle = @enumToInt(enum_unnamed_29.ImGuiMouseButton_Middle);
pub const ImGuiMouseButton_COUNT = @enumToInt(enum_unnamed_29.ImGuiMouseButton_COUNT);
const enum_unnamed_29 = extern enum(c_int) {
ImGuiMouseButton_Left = 0,
ImGuiMouseButton_Right = 1,
ImGuiMouseButton_Middle = 2,
ImGuiMouseButton_COUNT = 5,
_,
};
pub const ImGuiMouseButton_ = enum_unnamed_29;
pub const ImGuiMouseCursor_None = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_None);
pub const ImGuiMouseCursor_Arrow = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_Arrow);
pub const ImGuiMouseCursor_TextInput = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_TextInput);
pub const ImGuiMouseCursor_ResizeAll = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_ResizeAll);
pub const ImGuiMouseCursor_ResizeNS = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_ResizeNS);
pub const ImGuiMouseCursor_ResizeEW = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_ResizeEW);
pub const ImGuiMouseCursor_ResizeNESW = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_ResizeNESW);
pub const ImGuiMouseCursor_ResizeNWSE = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_ResizeNWSE);
pub const ImGuiMouseCursor_Hand = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_Hand);
pub const ImGuiMouseCursor_NotAllowed = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_NotAllowed);
pub const ImGuiMouseCursor_COUNT = @enumToInt(enum_unnamed_30.ImGuiMouseCursor_COUNT);
const enum_unnamed_30 = extern enum(c_int) {
ImGuiMouseCursor_None = -1,
ImGuiMouseCursor_Arrow = 0,
ImGuiMouseCursor_TextInput = 1,
ImGuiMouseCursor_ResizeAll = 2,
ImGuiMouseCursor_ResizeNS = 3,
ImGuiMouseCursor_ResizeEW = 4,
ImGuiMouseCursor_ResizeNESW = 5,
ImGuiMouseCursor_ResizeNWSE = 6,
ImGuiMouseCursor_Hand = 7,
ImGuiMouseCursor_NotAllowed = 8,
ImGuiMouseCursor_COUNT = 9,
_,
};
pub const ImGuiMouseCursor_ = enum_unnamed_30;
pub const ImGuiCond_Always = @enumToInt(enum_unnamed_31.ImGuiCond_Always);
pub const ImGuiCond_Once = @enumToInt(enum_unnamed_31.ImGuiCond_Once);
pub const ImGuiCond_FirstUseEver = @enumToInt(enum_unnamed_31.ImGuiCond_FirstUseEver);
pub const ImGuiCond_Appearing = @enumToInt(enum_unnamed_31.ImGuiCond_Appearing);
const enum_unnamed_31 = extern enum(c_int) {
ImGuiCond_Always = 1,
ImGuiCond_Once = 2,
ImGuiCond_FirstUseEver = 4,
ImGuiCond_Appearing = 8,
_,
};
pub const ImGuiCond_ = enum_unnamed_31;
pub const struct_ImVector_ImGuiTabBar = extern struct {
Size: c_int,
Capacity: c_int,
Data: [*c]ImGuiTabBar,
};
pub const ImVector_ImGuiTabBar = struct_ImVector_ImGuiTabBar;
pub const struct_ImPool_ImGuiTabBar = extern struct {
Buf: ImVector_ImGuiTabBar,
Map: ImGuiStorage,
FreeIdx: ImPoolIdx,
};
pub const ImPool_ImGuiTabBar = struct_ImPool_ImGuiTabBar;
pub const ImDrawCornerFlags_None = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_None);
pub const ImDrawCornerFlags_TopLeft = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_TopLeft);
pub const ImDrawCornerFlags_TopRight = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_TopRight);
pub const ImDrawCornerFlags_BotLeft = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_BotLeft);
pub const ImDrawCornerFlags_BotRight = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_BotRight);
pub const ImDrawCornerFlags_Top = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_Top);
pub const ImDrawCornerFlags_Bot = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_Bot);
pub const ImDrawCornerFlags_Left = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_Left);
pub const ImDrawCornerFlags_Right = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_Right);
pub const ImDrawCornerFlags_All = @enumToInt(enum_unnamed_32.ImDrawCornerFlags_All);
const enum_unnamed_32 = extern enum(c_int) {
ImDrawCornerFlags_None = 0,
ImDrawCornerFlags_TopLeft = 1,
ImDrawCornerFlags_TopRight = 2,
ImDrawCornerFlags_BotLeft = 4,
ImDrawCornerFlags_BotRight = 8,
ImDrawCornerFlags_Top = 3,
ImDrawCornerFlags_Bot = 12,
ImDrawCornerFlags_Left = 5,
ImDrawCornerFlags_Right = 10,
ImDrawCornerFlags_All = 15,
_,
};
pub const ImDrawCornerFlags_ = enum_unnamed_32;
pub const ImDrawListFlags_None = @enumToInt(enum_unnamed_33.ImDrawListFlags_None);
pub const ImDrawListFlags_AntiAliasedLines = @enumToInt(enum_unnamed_33.ImDrawListFlags_AntiAliasedLines);
pub const ImDrawListFlags_AntiAliasedFill = @enumToInt(enum_unnamed_33.ImDrawListFlags_AntiAliasedFill);
pub const ImDrawListFlags_AllowVtxOffset = @enumToInt(enum_unnamed_33.ImDrawListFlags_AllowVtxOffset);
const enum_unnamed_33 = extern enum(c_int) {
ImDrawListFlags_None = 0,
ImDrawListFlags_AntiAliasedLines = 1,
ImDrawListFlags_AntiAliasedFill = 2,
ImDrawListFlags_AllowVtxOffset = 4,
_,
};
pub const ImDrawListFlags_ = enum_unnamed_33;
pub const ImFontAtlasFlags_None = @enumToInt(enum_unnamed_34.ImFontAtlasFlags_None);
pub const ImFontAtlasFlags_NoPowerOfTwoHeight = @enumToInt(enum_unnamed_34.ImFontAtlasFlags_NoPowerOfTwoHeight);
pub const ImFontAtlasFlags_NoMouseCursors = @enumToInt(enum_unnamed_34.ImFontAtlasFlags_NoMouseCursors);
const enum_unnamed_34 = extern enum(c_int) {
ImFontAtlasFlags_None = 0,
ImFontAtlasFlags_NoPowerOfTwoHeight = 1,
ImFontAtlasFlags_NoMouseCursors = 2,
_,
};
pub const ImFontAtlasFlags_ = enum_unnamed_34;
pub const ImGuiViewportFlags_None = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_None);
pub const ImGuiViewportFlags_NoDecoration = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoDecoration);
pub const ImGuiViewportFlags_NoTaskBarIcon = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoTaskBarIcon);
pub const ImGuiViewportFlags_NoFocusOnAppearing = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoFocusOnAppearing);
pub const ImGuiViewportFlags_NoFocusOnClick = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoFocusOnClick);
pub const ImGuiViewportFlags_NoInputs = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoInputs);
pub const ImGuiViewportFlags_NoRendererClear = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoRendererClear);
pub const ImGuiViewportFlags_TopMost = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_TopMost);
pub const ImGuiViewportFlags_Minimized = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_Minimized);
pub const ImGuiViewportFlags_NoAutoMerge = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_NoAutoMerge);
pub const ImGuiViewportFlags_CanHostOtherWindows = @enumToInt(enum_unnamed_35.ImGuiViewportFlags_CanHostOtherWindows);
const enum_unnamed_35 = extern enum(c_int) {
ImGuiViewportFlags_None = 0,
ImGuiViewportFlags_NoDecoration = 1,
ImGuiViewportFlags_NoTaskBarIcon = 2,
ImGuiViewportFlags_NoFocusOnAppearing = 4,
ImGuiViewportFlags_NoFocusOnClick = 8,
ImGuiViewportFlags_NoInputs = 16,
ImGuiViewportFlags_NoRendererClear = 32,
ImGuiViewportFlags_TopMost = 64,
ImGuiViewportFlags_Minimized = 128,
ImGuiViewportFlags_NoAutoMerge = 256,
ImGuiViewportFlags_CanHostOtherWindows = 512,
_,
};
pub const ImGuiViewportFlags_ = enum_unnamed_35;
pub const ImGuiItemFlags_None = @enumToInt(enum_unnamed_36.ImGuiItemFlags_None);
pub const ImGuiItemFlags_NoTabStop = @enumToInt(enum_unnamed_36.ImGuiItemFlags_NoTabStop);
pub const ImGuiItemFlags_ButtonRepeat = @enumToInt(enum_unnamed_36.ImGuiItemFlags_ButtonRepeat);
pub const ImGuiItemFlags_Disabled = @enumToInt(enum_unnamed_36.ImGuiItemFlags_Disabled);
pub const ImGuiItemFlags_NoNav = @enumToInt(enum_unnamed_36.ImGuiItemFlags_NoNav);
pub const ImGuiItemFlags_NoNavDefaultFocus = @enumToInt(enum_unnamed_36.ImGuiItemFlags_NoNavDefaultFocus);
pub const ImGuiItemFlags_SelectableDontClosePopup = @enumToInt(enum_unnamed_36.ImGuiItemFlags_SelectableDontClosePopup);
pub const ImGuiItemFlags_MixedValue = @enumToInt(enum_unnamed_36.ImGuiItemFlags_MixedValue);
pub const ImGuiItemFlags_Default_ = @enumToInt(enum_unnamed_36.ImGuiItemFlags_Default_);
const enum_unnamed_36 = extern enum(c_int) {
ImGuiItemFlags_None = 0,
ImGuiItemFlags_NoTabStop = 1,
ImGuiItemFlags_ButtonRepeat = 2,
ImGuiItemFlags_Disabled = 4,
ImGuiItemFlags_NoNav = 8,
ImGuiItemFlags_NoNavDefaultFocus = 16,
ImGuiItemFlags_SelectableDontClosePopup = 32,
ImGuiItemFlags_MixedValue = 64,
ImGuiItemFlags_Default_ = 0,
_,
};
pub const ImGuiItemFlags_ = enum_unnamed_36;
pub const ImGuiItemStatusFlags_None = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_None);
pub const ImGuiItemStatusFlags_HoveredRect = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_HoveredRect);
pub const ImGuiItemStatusFlags_HasDisplayRect = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_HasDisplayRect);
pub const ImGuiItemStatusFlags_Edited = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_Edited);
pub const ImGuiItemStatusFlags_ToggledSelection = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_ToggledSelection);
pub const ImGuiItemStatusFlags_ToggledOpen = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_ToggledOpen);
pub const ImGuiItemStatusFlags_HasDeactivated = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_HasDeactivated);
pub const ImGuiItemStatusFlags_Deactivated = @enumToInt(enum_unnamed_37.ImGuiItemStatusFlags_Deactivated);
const enum_unnamed_37 = extern enum(c_int) {
ImGuiItemStatusFlags_None = 0,
ImGuiItemStatusFlags_HoveredRect = 1,
ImGuiItemStatusFlags_HasDisplayRect = 2,
ImGuiItemStatusFlags_Edited = 4,
ImGuiItemStatusFlags_ToggledSelection = 8,
ImGuiItemStatusFlags_ToggledOpen = 16,
ImGuiItemStatusFlags_HasDeactivated = 32,
ImGuiItemStatusFlags_Deactivated = 64,
_,
};
pub const ImGuiItemStatusFlags_ = enum_unnamed_37;
pub const ImGuiButtonFlags_None = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_None);
pub const ImGuiButtonFlags_Repeat = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_Repeat);
pub const ImGuiButtonFlags_PressedOnClick = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnClick);
pub const ImGuiButtonFlags_PressedOnClickRelease = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnClickRelease);
pub const ImGuiButtonFlags_PressedOnClickReleaseAnywhere = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnClickReleaseAnywhere);
pub const ImGuiButtonFlags_PressedOnRelease = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnRelease);
pub const ImGuiButtonFlags_PressedOnDoubleClick = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnDoubleClick);
pub const ImGuiButtonFlags_PressedOnDragDropHold = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnDragDropHold);
pub const ImGuiButtonFlags_FlattenChildren = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_FlattenChildren);
pub const ImGuiButtonFlags_AllowItemOverlap = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_AllowItemOverlap);
pub const ImGuiButtonFlags_DontClosePopups = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_DontClosePopups);
pub const ImGuiButtonFlags_Disabled = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_Disabled);
pub const ImGuiButtonFlags_AlignTextBaseLine = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_AlignTextBaseLine);
pub const ImGuiButtonFlags_NoKeyModifiers = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_NoKeyModifiers);
pub const ImGuiButtonFlags_NoHoldingActiveId = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_NoHoldingActiveId);
pub const ImGuiButtonFlags_NoNavFocus = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_NoNavFocus);
pub const ImGuiButtonFlags_NoHoveredOnFocus = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_NoHoveredOnFocus);
pub const ImGuiButtonFlags_MouseButtonLeft = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonLeft);
pub const ImGuiButtonFlags_MouseButtonRight = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonRight);
pub const ImGuiButtonFlags_MouseButtonMiddle = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonMiddle);
pub const ImGuiButtonFlags_MouseButtonMask_ = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonMask_);
pub const ImGuiButtonFlags_MouseButtonShift_ = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonShift_);
pub const ImGuiButtonFlags_MouseButtonDefault_ = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_MouseButtonDefault_);
pub const ImGuiButtonFlags_PressedOnMask_ = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnMask_);
pub const ImGuiButtonFlags_PressedOnDefault_ = @enumToInt(enum_unnamed_38.ImGuiButtonFlags_PressedOnDefault_);
const enum_unnamed_38 = extern enum(c_int) {
ImGuiButtonFlags_None = 0,
ImGuiButtonFlags_Repeat = 1,
ImGuiButtonFlags_PressedOnClick = 2,
ImGuiButtonFlags_PressedOnClickRelease = 4,
ImGuiButtonFlags_PressedOnClickReleaseAnywhere = 8,
ImGuiButtonFlags_PressedOnRelease = 16,
ImGuiButtonFlags_PressedOnDoubleClick = 32,
ImGuiButtonFlags_PressedOnDragDropHold = 64,
ImGuiButtonFlags_FlattenChildren = 128,
ImGuiButtonFlags_AllowItemOverlap = 256,
ImGuiButtonFlags_DontClosePopups = 512,
ImGuiButtonFlags_Disabled = 1024,
ImGuiButtonFlags_AlignTextBaseLine = 2048,
ImGuiButtonFlags_NoKeyModifiers = 4096,
ImGuiButtonFlags_NoHoldingActiveId = 8192,
ImGuiButtonFlags_NoNavFocus = 16384,
ImGuiButtonFlags_NoHoveredOnFocus = 32768,
ImGuiButtonFlags_MouseButtonLeft = 65536,
ImGuiButtonFlags_MouseButtonRight = 131072,
ImGuiButtonFlags_MouseButtonMiddle = 262144,
ImGuiButtonFlags_MouseButtonMask_ = 458752,
ImGuiButtonFlags_MouseButtonShift_ = 16,
ImGuiButtonFlags_MouseButtonDefault_ = 65536,
ImGuiButtonFlags_PressedOnMask_ = 126,
ImGuiButtonFlags_PressedOnDefault_ = 4,
_,
};
pub const ImGuiButtonFlags_ = enum_unnamed_38;
pub const ImGuiSliderFlags_None = @enumToInt(enum_unnamed_39.ImGuiSliderFlags_None);
pub const ImGuiSliderFlags_Vertical = @enumToInt(enum_unnamed_39.ImGuiSliderFlags_Vertical);
const enum_unnamed_39 = extern enum(c_int) {
ImGuiSliderFlags_None = 0,
ImGuiSliderFlags_Vertical = 1,
_,
};
pub const ImGuiSliderFlags_ = enum_unnamed_39;
pub const ImGuiDragFlags_None = @enumToInt(enum_unnamed_40.ImGuiDragFlags_None);
pub const ImGuiDragFlags_Vertical = @enumToInt(enum_unnamed_40.ImGuiDragFlags_Vertical);
const enum_unnamed_40 = extern enum(c_int) {
ImGuiDragFlags_None = 0,
ImGuiDragFlags_Vertical = 1,
_,
};
pub const ImGuiDragFlags_ = enum_unnamed_40;
pub const ImGuiSelectableFlags_NoHoldingActiveID = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_NoHoldingActiveID);
pub const ImGuiSelectableFlags_SelectOnClick = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_SelectOnClick);
pub const ImGuiSelectableFlags_SelectOnRelease = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_SelectOnRelease);
pub const ImGuiSelectableFlags_SpanAvailWidth = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_SpanAvailWidth);
pub const ImGuiSelectableFlags_DrawHoveredWhenHeld = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_DrawHoveredWhenHeld);
pub const ImGuiSelectableFlags_SetNavIdOnHover = @enumToInt(enum_unnamed_41.ImGuiSelectableFlags_SetNavIdOnHover);
const enum_unnamed_41 = extern enum(c_int) {
ImGuiSelectableFlags_NoHoldingActiveID = 1048576,
ImGuiSelectableFlags_SelectOnClick = 2097152,
ImGuiSelectableFlags_SelectOnRelease = 4194304,
ImGuiSelectableFlags_SpanAvailWidth = 8388608,
ImGuiSelectableFlags_DrawHoveredWhenHeld = 16777216,
ImGuiSelectableFlags_SetNavIdOnHover = 33554432,
_,
};
pub const ImGuiSelectableFlagsPrivate_ = enum_unnamed_41;
pub const ImGuiTreeNodeFlags_ClipLabelForTrailingButton = @enumToInt(enum_unnamed_42.ImGuiTreeNodeFlags_ClipLabelForTrailingButton);
const enum_unnamed_42 = extern enum(c_int) {
ImGuiTreeNodeFlags_ClipLabelForTrailingButton = 1048576,
_,
};
pub const ImGuiTreeNodeFlagsPrivate_ = enum_unnamed_42;
pub const ImGuiSeparatorFlags_None = @enumToInt(enum_unnamed_43.ImGuiSeparatorFlags_None);
pub const ImGuiSeparatorFlags_Horizontal = @enumToInt(enum_unnamed_43.ImGuiSeparatorFlags_Horizontal);
pub const ImGuiSeparatorFlags_Vertical = @enumToInt(enum_unnamed_43.ImGuiSeparatorFlags_Vertical);
pub const ImGuiSeparatorFlags_SpanAllColumns = @enumToInt(enum_unnamed_43.ImGuiSeparatorFlags_SpanAllColumns);
const enum_unnamed_43 = extern enum(c_int) {
ImGuiSeparatorFlags_None = 0,
ImGuiSeparatorFlags_Horizontal = 1,
ImGuiSeparatorFlags_Vertical = 2,
ImGuiSeparatorFlags_SpanAllColumns = 4,
_,
};
pub const ImGuiSeparatorFlags_ = enum_unnamed_43;
pub const ImGuiTextFlags_None = @enumToInt(enum_unnamed_44.ImGuiTextFlags_None);
pub const ImGuiTextFlags_NoWidthForLargeClippedText = @enumToInt(enum_unnamed_44.ImGuiTextFlags_NoWidthForLargeClippedText);
const enum_unnamed_44 = extern enum(c_int) {
ImGuiTextFlags_None = 0,
ImGuiTextFlags_NoWidthForLargeClippedText = 1,
_,
};
pub const ImGuiTextFlags_ = enum_unnamed_44;
pub const ImGuiTooltipFlags_None = @enumToInt(enum_unnamed_45.ImGuiTooltipFlags_None);
pub const ImGuiTooltipFlags_OverridePreviousTooltip = @enumToInt(enum_unnamed_45.ImGuiTooltipFlags_OverridePreviousTooltip);
const enum_unnamed_45 = extern enum(c_int) {
ImGuiTooltipFlags_None = 0,
ImGuiTooltipFlags_OverridePreviousTooltip = 1,
_,
};
pub const ImGuiTooltipFlags_ = enum_unnamed_45;
pub const ImGuiLayoutType_Horizontal = @enumToInt(enum_unnamed_46.ImGuiLayoutType_Horizontal);
pub const ImGuiLayoutType_Vertical = @enumToInt(enum_unnamed_46.ImGuiLayoutType_Vertical);
const enum_unnamed_46 = extern enum(c_int) {
ImGuiLayoutType_Horizontal = 0,
ImGuiLayoutType_Vertical = 1,
_,
};
pub const ImGuiLayoutType_ = enum_unnamed_46;
pub const ImGuiLogType_None = @enumToInt(enum_unnamed_47.ImGuiLogType_None);
pub const ImGuiLogType_TTY = @enumToInt(enum_unnamed_47.ImGuiLogType_TTY);
pub const ImGuiLogType_File = @enumToInt(enum_unnamed_47.ImGuiLogType_File);
pub const ImGuiLogType_Buffer = @enumToInt(enum_unnamed_47.ImGuiLogType_Buffer);
pub const ImGuiLogType_Clipboard = @enumToInt(enum_unnamed_47.ImGuiLogType_Clipboard);
const enum_unnamed_47 = extern enum(c_int) {
ImGuiLogType_None = 0,
ImGuiLogType_TTY = 1,
ImGuiLogType_File = 2,
ImGuiLogType_Buffer = 3,
ImGuiLogType_Clipboard = 4,
_,
};
pub const ImGuiLogType = enum_unnamed_47;
pub const ImGuiAxis_None = @enumToInt(enum_unnamed_48.ImGuiAxis_None);
pub const ImGuiAxis_X = @enumToInt(enum_unnamed_48.ImGuiAxis_X);
pub const ImGuiAxis_Y = @enumToInt(enum_unnamed_48.ImGuiAxis_Y);
const enum_unnamed_48 = extern enum(c_int) {
ImGuiAxis_None = -1,
ImGuiAxis_X = 0,
ImGuiAxis_Y = 1,
_,
};
pub const ImGuiAxis = enum_unnamed_48;
pub const ImGuiPlotType_Lines = @enumToInt(enum_unnamed_49.ImGuiPlotType_Lines);
pub const ImGuiPlotType_Histogram = @enumToInt(enum_unnamed_49.ImGuiPlotType_Histogram);
const enum_unnamed_49 = extern enum(c_int) {
ImGuiPlotType_Lines,
ImGuiPlotType_Histogram,
_,
};
pub const ImGuiPlotType = enum_unnamed_49;
pub const ImGuiInputSource_None = @enumToInt(enum_unnamed_50.ImGuiInputSource_None);
pub const ImGuiInputSource_Mouse = @enumToInt(enum_unnamed_50.ImGuiInputSource_Mouse);
pub const ImGuiInputSource_Nav = @enumToInt(enum_unnamed_50.ImGuiInputSource_Nav);
pub const ImGuiInputSource_NavKeyboard = @enumToInt(enum_unnamed_50.ImGuiInputSource_NavKeyboard);
pub const ImGuiInputSource_NavGamepad = @enumToInt(enum_unnamed_50.ImGuiInputSource_NavGamepad);
pub const ImGuiInputSource_COUNT = @enumToInt(enum_unnamed_50.ImGuiInputSource_COUNT);
const enum_unnamed_50 = extern enum(c_int) {
ImGuiInputSource_None = 0,
ImGuiInputSource_Mouse = 1,
ImGuiInputSource_Nav = 2,
ImGuiInputSource_NavKeyboard = 3,
ImGuiInputSource_NavGamepad = 4,
ImGuiInputSource_COUNT = 5,
_,
};
pub const ImGuiInputSource = enum_unnamed_50;
pub const ImGuiInputReadMode_Down = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_Down);
pub const ImGuiInputReadMode_Pressed = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_Pressed);
pub const ImGuiInputReadMode_Released = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_Released);
pub const ImGuiInputReadMode_Repeat = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_Repeat);
pub const ImGuiInputReadMode_RepeatSlow = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_RepeatSlow);
pub const ImGuiInputReadMode_RepeatFast = @enumToInt(enum_unnamed_51.ImGuiInputReadMode_RepeatFast);
const enum_unnamed_51 = extern enum(c_int) {
ImGuiInputReadMode_Down,
ImGuiInputReadMode_Pressed,
ImGuiInputReadMode_Released,
ImGuiInputReadMode_Repeat,
ImGuiInputReadMode_RepeatSlow,
ImGuiInputReadMode_RepeatFast,
_,
};
pub const ImGuiInputReadMode = enum_unnamed_51;
pub const ImGuiNavHighlightFlags_None = @enumToInt(enum_unnamed_52.ImGuiNavHighlightFlags_None);
pub const ImGuiNavHighlightFlags_TypeDefault = @enumToInt(enum_unnamed_52.ImGuiNavHighlightFlags_TypeDefault);
pub const ImGuiNavHighlightFlags_TypeThin = @enumToInt(enum_unnamed_52.ImGuiNavHighlightFlags_TypeThin);
pub const ImGuiNavHighlightFlags_AlwaysDraw = @enumToInt(enum_unnamed_52.ImGuiNavHighlightFlags_AlwaysDraw);
pub const ImGuiNavHighlightFlags_NoRounding = @enumToInt(enum_unnamed_52.ImGuiNavHighlightFlags_NoRounding);
const enum_unnamed_52 = extern enum(c_int) {
ImGuiNavHighlightFlags_None = 0,
ImGuiNavHighlightFlags_TypeDefault = 1,
ImGuiNavHighlightFlags_TypeThin = 2,
ImGuiNavHighlightFlags_AlwaysDraw = 4,
ImGuiNavHighlightFlags_NoRounding = 8,
_,
};
pub const ImGuiNavHighlightFlags_ = enum_unnamed_52;
pub const ImGuiNavDirSourceFlags_None = @enumToInt(enum_unnamed_53.ImGuiNavDirSourceFlags_None);
pub const ImGuiNavDirSourceFlags_Keyboard = @enumToInt(enum_unnamed_53.ImGuiNavDirSourceFlags_Keyboard);
pub const ImGuiNavDirSourceFlags_PadDPad = @enumToInt(enum_unnamed_53.ImGuiNavDirSourceFlags_PadDPad);
pub const ImGuiNavDirSourceFlags_PadLStick = @enumToInt(enum_unnamed_53.ImGuiNavDirSourceFlags_PadLStick);
const enum_unnamed_53 = extern enum(c_int) {
ImGuiNavDirSourceFlags_None = 0,
ImGuiNavDirSourceFlags_Keyboard = 1,
ImGuiNavDirSourceFlags_PadDPad = 2,
ImGuiNavDirSourceFlags_PadLStick = 4,
_,
};
pub const ImGuiNavDirSourceFlags_ = enum_unnamed_53;
pub const ImGuiNavMoveFlags_None = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_None);
pub const ImGuiNavMoveFlags_LoopX = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_LoopX);
pub const ImGuiNavMoveFlags_LoopY = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_LoopY);
pub const ImGuiNavMoveFlags_WrapX = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_WrapX);
pub const ImGuiNavMoveFlags_WrapY = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_WrapY);
pub const ImGuiNavMoveFlags_AllowCurrentNavId = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_AllowCurrentNavId);
pub const ImGuiNavMoveFlags_AlsoScoreVisibleSet = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_AlsoScoreVisibleSet);
pub const ImGuiNavMoveFlags_ScrollToEdge = @enumToInt(enum_unnamed_54.ImGuiNavMoveFlags_ScrollToEdge);
const enum_unnamed_54 = extern enum(c_int) {
ImGuiNavMoveFlags_None = 0,
ImGuiNavMoveFlags_LoopX = 1,
ImGuiNavMoveFlags_LoopY = 2,
ImGuiNavMoveFlags_WrapX = 4,
ImGuiNavMoveFlags_WrapY = 8,
ImGuiNavMoveFlags_AllowCurrentNavId = 16,
ImGuiNavMoveFlags_AlsoScoreVisibleSet = 32,
ImGuiNavMoveFlags_ScrollToEdge = 64,
_,
};
pub const ImGuiNavMoveFlags_ = enum_unnamed_54;
pub const ImGuiNavForward_None = @enumToInt(enum_unnamed_55.ImGuiNavForward_None);
pub const ImGuiNavForward_ForwardQueued = @enumToInt(enum_unnamed_55.ImGuiNavForward_ForwardQueued);
pub const ImGuiNavForward_ForwardActive = @enumToInt(enum_unnamed_55.ImGuiNavForward_ForwardActive);
const enum_unnamed_55 = extern enum(c_int) {
ImGuiNavForward_None,
ImGuiNavForward_ForwardQueued,
ImGuiNavForward_ForwardActive,
_,
};
pub const ImGuiNavForward = enum_unnamed_55;
pub const ImGuiNavLayer_Main = @enumToInt(enum_unnamed_56.ImGuiNavLayer_Main);
pub const ImGuiNavLayer_Menu = @enumToInt(enum_unnamed_56.ImGuiNavLayer_Menu);
pub const ImGuiNavLayer_COUNT = @enumToInt(enum_unnamed_56.ImGuiNavLayer_COUNT);
const enum_unnamed_56 = extern enum(c_int) {
ImGuiNavLayer_Main = 0,
ImGuiNavLayer_Menu = 1,
ImGuiNavLayer_COUNT = 2,
_,
};
pub const ImGuiNavLayer = enum_unnamed_56;
pub const ImGuiPopupPositionPolicy_Default = @enumToInt(enum_unnamed_57.ImGuiPopupPositionPolicy_Default);
pub const ImGuiPopupPositionPolicy_ComboBox = @enumToInt(enum_unnamed_57.ImGuiPopupPositionPolicy_ComboBox);
const enum_unnamed_57 = extern enum(c_int) {
ImGuiPopupPositionPolicy_Default,
ImGuiPopupPositionPolicy_ComboBox,
_,
};
pub const ImGuiPopupPositionPolicy = enum_unnamed_57;
pub const ImGuiDataType_String = @enumToInt(enum_unnamed_58.ImGuiDataType_String);
pub const ImGuiDataType_Pointer = @enumToInt(enum_unnamed_58.ImGuiDataType_Pointer);
pub const ImGuiDataType_ID = @enumToInt(enum_unnamed_58.ImGuiDataType_ID);
const enum_unnamed_58 = extern enum(c_int) {
ImGuiDataType_String = 11,
ImGuiDataType_Pointer = 12,
ImGuiDataType_ID = 13,
_,
};
pub const ImGuiDataTypePrivate_ = enum_unnamed_58;
pub const ImGuiNextWindowDataFlags_None = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_None);
pub const ImGuiNextWindowDataFlags_HasPos = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasPos);
pub const ImGuiNextWindowDataFlags_HasSize = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasSize);
pub const ImGuiNextWindowDataFlags_HasContentSize = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasContentSize);
pub const ImGuiNextWindowDataFlags_HasCollapsed = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasCollapsed);
pub const ImGuiNextWindowDataFlags_HasSizeConstraint = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasSizeConstraint);
pub const ImGuiNextWindowDataFlags_HasFocus = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasFocus);
pub const ImGuiNextWindowDataFlags_HasBgAlpha = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasBgAlpha);
pub const ImGuiNextWindowDataFlags_HasScroll = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasScroll);
pub const ImGuiNextWindowDataFlags_HasViewport = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasViewport);
pub const ImGuiNextWindowDataFlags_HasDock = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasDock);
pub const ImGuiNextWindowDataFlags_HasWindowClass = @enumToInt(enum_unnamed_59.ImGuiNextWindowDataFlags_HasWindowClass);
const enum_unnamed_59 = extern enum(c_int) {
ImGuiNextWindowDataFlags_None = 0,
ImGuiNextWindowDataFlags_HasPos = 1,
ImGuiNextWindowDataFlags_HasSize = 2,
ImGuiNextWindowDataFlags_HasContentSize = 4,
ImGuiNextWindowDataFlags_HasCollapsed = 8,
ImGuiNextWindowDataFlags_HasSizeConstraint = 16,
ImGuiNextWindowDataFlags_HasFocus = 32,
ImGuiNextWindowDataFlags_HasBgAlpha = 64,
ImGuiNextWindowDataFlags_HasScroll = 128,
ImGuiNextWindowDataFlags_HasViewport = 256,
ImGuiNextWindowDataFlags_HasDock = 512,
ImGuiNextWindowDataFlags_HasWindowClass = 1024,
_,
};
pub const ImGuiNextWindowDataFlags_ = enum_unnamed_59;
pub const ImGuiNextItemDataFlags_None = @enumToInt(enum_unnamed_60.ImGuiNextItemDataFlags_None);
pub const ImGuiNextItemDataFlags_HasWidth = @enumToInt(enum_unnamed_60.ImGuiNextItemDataFlags_HasWidth);
pub const ImGuiNextItemDataFlags_HasOpen = @enumToInt(enum_unnamed_60.ImGuiNextItemDataFlags_HasOpen);
const enum_unnamed_60 = extern enum(c_int) {
ImGuiNextItemDataFlags_None = 0,
ImGuiNextItemDataFlags_HasWidth = 1,
ImGuiNextItemDataFlags_HasOpen = 2,
_,
};
pub const ImGuiNextItemDataFlags_ = enum_unnamed_60;
pub const ImGuiColumnsFlags_None = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_None);
pub const ImGuiColumnsFlags_NoBorder = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_NoBorder);
pub const ImGuiColumnsFlags_NoResize = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_NoResize);
pub const ImGuiColumnsFlags_NoPreserveWidths = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_NoPreserveWidths);
pub const ImGuiColumnsFlags_NoForceWithinWindow = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_NoForceWithinWindow);
pub const ImGuiColumnsFlags_GrowParentContentsSize = @enumToInt(enum_unnamed_61.ImGuiColumnsFlags_GrowParentContentsSize);
const enum_unnamed_61 = extern enum(c_int) {
ImGuiColumnsFlags_None = 0,
ImGuiColumnsFlags_NoBorder = 1,
ImGuiColumnsFlags_NoResize = 2,
ImGuiColumnsFlags_NoPreserveWidths = 4,
ImGuiColumnsFlags_NoForceWithinWindow = 8,
ImGuiColumnsFlags_GrowParentContentsSize = 16,
_,
};
pub const ImGuiColumnsFlags_ = enum_unnamed_61;
pub const ImGuiDockNodeFlags_DockSpace = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_DockSpace);
pub const ImGuiDockNodeFlags_CentralNode = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_CentralNode);
pub const ImGuiDockNodeFlags_NoTabBar = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_NoTabBar);
pub const ImGuiDockNodeFlags_HiddenTabBar = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_HiddenTabBar);
pub const ImGuiDockNodeFlags_NoWindowMenuButton = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_NoWindowMenuButton);
pub const ImGuiDockNodeFlags_NoCloseButton = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_NoCloseButton);
pub const ImGuiDockNodeFlags_NoDocking = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_NoDocking);
pub const ImGuiDockNodeFlags_SharedFlagsInheritMask_ = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_SharedFlagsInheritMask_);
pub const ImGuiDockNodeFlags_LocalFlagsMask_ = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_LocalFlagsMask_);
pub const ImGuiDockNodeFlags_LocalFlagsTransferMask_ = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_LocalFlagsTransferMask_);
pub const ImGuiDockNodeFlags_SavedFlagsMask_ = @enumToInt(enum_unnamed_62.ImGuiDockNodeFlags_SavedFlagsMask_);
const enum_unnamed_62 = extern enum(c_int) {
ImGuiDockNodeFlags_DockSpace = 1024,
ImGuiDockNodeFlags_CentralNode = 2048,
ImGuiDockNodeFlags_NoTabBar = 4096,
ImGuiDockNodeFlags_HiddenTabBar = 8192,
ImGuiDockNodeFlags_NoWindowMenuButton = 16384,
ImGuiDockNodeFlags_NoCloseButton = 32768,
ImGuiDockNodeFlags_NoDocking = 65536,
ImGuiDockNodeFlags_SharedFlagsInheritMask_ = -1,
ImGuiDockNodeFlags_LocalFlagsMask_ = 130160,
ImGuiDockNodeFlags_LocalFlagsTransferMask_ = 129136,
ImGuiDockNodeFlags_SavedFlagsMask_ = 130080,
_,
};
pub const ImGuiDockNodeFlagsPrivate_ = enum_unnamed_62;
pub const ImGuiDataAuthority_Auto = @enumToInt(enum_unnamed_63.ImGuiDataAuthority_Auto);
pub const ImGuiDataAuthority_DockNode = @enumToInt(enum_unnamed_63.ImGuiDataAuthority_DockNode);
pub const ImGuiDataAuthority_Window = @enumToInt(enum_unnamed_63.ImGuiDataAuthority_Window);
const enum_unnamed_63 = extern enum(c_int) {
ImGuiDataAuthority_Auto,
ImGuiDataAuthority_DockNode,
ImGuiDataAuthority_Window,
_,
};
pub const ImGuiDataAuthority_ = enum_unnamed_63;
pub const ImGuiDockNodeState_Unknown = @enumToInt(enum_unnamed_64.ImGuiDockNodeState_Unknown);
pub const ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow = @enumToInt(enum_unnamed_64.ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow);
pub const ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing = @enumToInt(enum_unnamed_64.ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing);
pub const ImGuiDockNodeState_HostWindowVisible = @enumToInt(enum_unnamed_64.ImGuiDockNodeState_HostWindowVisible);
const enum_unnamed_64 = extern enum(c_int) {
ImGuiDockNodeState_Unknown,
ImGuiDockNodeState_HostWindowHiddenBecauseSingleWindow,
ImGuiDockNodeState_HostWindowHiddenBecauseWindowsAreResizing,
ImGuiDockNodeState_HostWindowVisible,
_,
};
pub const ImGuiDockNodeState = enum_unnamed_64;
pub const ImGuiTabBarFlags_DockNode = @enumToInt(enum_unnamed_65.ImGuiTabBarFlags_DockNode);
pub const ImGuiTabBarFlags_IsFocused = @enumToInt(enum_unnamed_65.ImGuiTabBarFlags_IsFocused);
pub const ImGuiTabBarFlags_SaveSettings = @enumToInt(enum_unnamed_65.ImGuiTabBarFlags_SaveSettings);
const enum_unnamed_65 = extern enum(c_int) {
ImGuiTabBarFlags_DockNode = 1048576,
ImGuiTabBarFlags_IsFocused = 2097152,
ImGuiTabBarFlags_SaveSettings = 4194304,
_,
};
pub const ImGuiTabBarFlagsPrivate_ = enum_unnamed_65;
pub const ImGuiTabItemFlags_NoCloseButton = @enumToInt(enum_unnamed_66.ImGuiTabItemFlags_NoCloseButton);
pub const ImGuiTabItemFlags_Unsorted = @enumToInt(enum_unnamed_66.ImGuiTabItemFlags_Unsorted);
pub const ImGuiTabItemFlags_Preview = @enumToInt(enum_unnamed_66.ImGuiTabItemFlags_Preview);
const enum_unnamed_66 = extern enum(c_int) {
ImGuiTabItemFlags_NoCloseButton = 1048576,
ImGuiTabItemFlags_Unsorted = 2097152,
ImGuiTabItemFlags_Preview = 4194304,
_,
};
pub const ImGuiTabItemFlagsPrivate_ = enum_unnamed_66;
pub extern fn ImVec2_ImVec2Nil() [*c]ImVec2;
pub extern fn ImVec2_destroy(self: [*c]ImVec2) void;
pub extern fn ImVec2_ImVec2Float(_x: f32, _y: f32) [*c]ImVec2;
pub extern fn ImVec4_ImVec4Nil() [*c]ImVec4;
pub extern fn ImVec4_destroy(self: [*c]ImVec4) void;
pub extern fn ImVec4_ImVec4Float(_x: f32, _y: f32, _z: f32, _w: f32) [*c]ImVec4;
pub extern fn igCreateContext(shared_font_atlas: [*c]ImFontAtlas) [*c]ImGuiContext;
pub extern fn igDestroyContext(ctx: [*c]ImGuiContext) void;
pub extern fn igGetCurrentContext() *ImGuiContext;
pub extern fn igSetCurrentContext(ctx: [*c]ImGuiContext) void;
pub extern fn igGetIO() *ImGuiIO;
pub extern fn igGetStyle() *ImGuiStyle;
pub extern fn igNewFrame() callconv(.C) void;
pub extern fn igEndFrame() callconv(.C) void;
pub extern fn igRender() void;
pub extern fn igGetDrawData() *ImDrawData;
pub extern fn igShowDemoWindow(p_open: [*c]bool) void;
pub extern fn igShowAboutWindow(p_open: [*c]bool) void;
pub extern fn igShowMetricsWindow(p_open: [*c]bool) void;
pub extern fn igShowStyleEditor(ref: [*c]ImGuiStyle) void;
pub extern fn igShowStyleSelector(label: [*c]const u8) bool;
pub extern fn igShowFontSelector(label: [*c]const u8) void;
pub extern fn igShowUserGuide() void;
pub extern fn igGetVersion() [*c]const u8;
pub extern fn igStyleColorsDark(dst: [*c]ImGuiStyle) void;
pub extern fn igStyleColorsClassic(dst: [*c]ImGuiStyle) void;
pub extern fn igStyleColorsLight(dst: [*c]ImGuiStyle) void;
pub extern fn igBegin(name: [*c]const u8, p_open: [*c]bool, flags: ImGuiWindowFlags) bool;
pub extern fn igEnd() void;
pub extern fn igBeginChildStr(str_id: [*c]const u8, size: ImVec2, border: bool, flags: ImGuiWindowFlags) bool;
pub extern fn igBeginChildID(id: ImGuiID, size: ImVec2, border: bool, flags: ImGuiWindowFlags) bool;
pub extern fn igEndChild() void;
pub extern fn igIsWindowAppearing() bool;
pub extern fn igIsWindowCollapsed() bool;
pub extern fn igIsWindowFocused(flags: ImGuiFocusedFlags) bool;
pub extern fn igIsWindowHovered(flags: ImGuiHoveredFlags) bool;
pub extern fn igGetWindowDrawList() [*c]ImDrawList;
pub extern fn igGetWindowDpiScale() f32;
pub extern fn igGetWindowViewport() [*c]ImGuiViewport;
pub extern fn igGetWindowPos(pOut: [*c]ImVec2) void;
pub extern fn igGetWindowSize(pOut: [*c]ImVec2) void;
pub extern fn igGetWindowWidth() f32;
pub extern fn igGetWindowHeight() f32;
pub extern fn igSetNextWindowPos(pos: ImVec2, cond: ImGuiCond, pivot: ImVec2) void;
pub extern fn igSetNextWindowSize(size: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetNextWindowSizeConstraints(size_min: ImVec2, size_max: ImVec2, custom_callback: ImGuiSizeCallback, custom_callback_data: ?*c_void) void;
pub extern fn igSetNextWindowContentSize(size: ImVec2) void;
pub extern fn igSetNextWindowCollapsed(collapsed: bool, cond: ImGuiCond) void;
pub extern fn igSetNextWindowFocus() void;
pub extern fn igSetNextWindowBgAlpha(alpha: f32) void;
pub extern fn igSetNextWindowViewport(viewport_id: ImGuiID) void;
pub extern fn igSetWindowPosVec2(pos: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowSizeVec2(size: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowCollapsedBool(collapsed: bool, cond: ImGuiCond) void;
pub extern fn igSetWindowFocusNil() void;
pub extern fn igSetWindowFontScale(scale: f32) void;
pub extern fn igSetWindowPosStr(name: [*c]const u8, pos: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowSizeStr(name: [*c]const u8, size: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowCollapsedStr(name: [*c]const u8, collapsed: bool, cond: ImGuiCond) void;
pub extern fn igSetWindowFocusStr(name: [*c]const u8) void;
pub extern fn igGetContentRegionMax(pOut: [*c]ImVec2) void;
pub extern fn igGetContentRegionAvail(pOut: [*c]ImVec2) void;
pub extern fn igGetWindowContentRegionMin(pOut: [*c]ImVec2) void;
pub extern fn igGetWindowContentRegionMax(pOut: [*c]ImVec2) void;
pub extern fn igGetWindowContentRegionWidth() f32;
pub extern fn igGetScrollX() f32;
pub extern fn igGetScrollY() f32;
pub extern fn igGetScrollMaxX() f32;
pub extern fn igGetScrollMaxY() f32;
pub extern fn igSetScrollXFloat(scroll_x: f32) void;
pub extern fn igSetScrollYFloat(scroll_y: f32) void;
pub extern fn igSetScrollHereX(center_x_ratio: f32) void;
pub extern fn igSetScrollHereY(center_y_ratio: f32) void;
pub extern fn igSetScrollFromPosXFloat(local_x: f32, center_x_ratio: f32) void;
pub extern fn igSetScrollFromPosYFloat(local_y: f32, center_y_ratio: f32) void;
pub extern fn igPushFont(font: [*c]ImFont) void;
pub extern fn igPopFont() void;
pub extern fn igPushStyleColorU32(idx: ImGuiCol, col: ImU32) void;
pub extern fn igPushStyleColorVec4(idx: ImGuiCol, col: ImVec4) void;
pub extern fn igPopStyleColor(count: c_int) void;
pub extern fn igPushStyleVarFloat(idx: ImGuiStyleVar, val: f32) void;
pub extern fn igPushStyleVarVec2(idx: ImGuiStyleVar, val: ImVec2) void;
pub extern fn igPopStyleVar(count: c_int) void;
pub extern fn igGetStyleColorVec4(idx: ImGuiCol) [*c]const ImVec4;
pub extern fn igGetFont() [*c]ImFont;
pub extern fn igGetFontSize() f32;
pub extern fn igGetFontTexUvWhitePixel(pOut: [*c]ImVec2) void;
pub extern fn igGetColorU32Col(idx: ImGuiCol, alpha_mul: f32) ImU32;
pub extern fn igGetColorU32Vec4(col: ImVec4) ImU32;
pub extern fn igGetColorU32U32(col: ImU32) ImU32;
pub extern fn igPushItemWidth(item_width: f32) void;
pub extern fn igPopItemWidth() void;
pub extern fn igSetNextItemWidth(item_width: f32) void;
pub extern fn igCalcItemWidth() f32;
pub extern fn igPushTextWrapPos(wrap_local_pos_x: f32) void;
pub extern fn igPopTextWrapPos() void;
pub extern fn igPushAllowKeyboardFocus(allow_keyboard_focus: bool) void;
pub extern fn igPopAllowKeyboardFocus() void;
pub extern fn igPushButtonRepeat(repeat: bool) void;
pub extern fn igPopButtonRepeat() void;
pub extern fn igSeparator() void;
pub extern fn igSameLine(offset_from_start_x: f32, spacing: f32) void;
pub extern fn igNewLine() void;
pub extern fn igSpacing() void;
pub extern fn igDummy(size: ImVec2) void;
pub extern fn igIndent(indent_w: f32) void;
pub extern fn igUnindent(indent_w: f32) void;
pub extern fn igBeginGroup() void;
pub extern fn igEndGroup() void;
pub extern fn igGetCursorPos(pOut: [*c]ImVec2) void;
pub extern fn igGetCursorPosX() f32;
pub extern fn igGetCursorPosY() f32;
pub extern fn igSetCursorPos(local_pos: ImVec2) void;
pub extern fn igSetCursorPosX(local_x: f32) void;
pub extern fn igSetCursorPosY(local_y: f32) void;
pub extern fn igGetCursorStartPos(pOut: [*c]ImVec2) void;
pub extern fn igGetCursorScreenPos(pOut: [*c]ImVec2) void;
pub extern fn igSetCursorScreenPos(pos: ImVec2) void;
pub extern fn igAlignTextToFramePadding() void;
pub extern fn igGetTextLineHeight() f32;
pub extern fn igGetTextLineHeightWithSpacing() f32;
pub extern fn igGetFrameHeight() f32;
pub extern fn igGetFrameHeightWithSpacing() f32;
pub extern fn igPushIDStr(str_id: [*c]const u8) void;
pub extern fn igPushIDStrStr(str_id_begin: [*c]const u8, str_id_end: [*c]const u8) void;
pub extern fn igPushIDPtr(ptr_id: ?*const c_void) void;
pub extern fn igPushIDInt(int_id: c_int) void;
pub extern fn igPopID() void;
pub extern fn igGetIDStr(str_id: [*c]const u8) ImGuiID;
pub extern fn igGetIDStrStr(str_id_begin: [*c]const u8, str_id_end: [*c]const u8) ImGuiID;
pub extern fn igGetIDPtr(ptr_id: ?*const c_void) ImGuiID;
pub extern fn igTextUnformatted(text: [*c]const u8, text_end: [*c]const u8) void;
pub extern fn igText(fmt: [*c]const u8, ...) void;
pub extern fn igTextV(fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igTextColored(col: ImVec4, fmt: [*c]const u8, ...) void;
pub extern fn igTextColoredV(col: ImVec4, fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igTextDisabled(fmt: [*c]const u8, ...) void;
pub extern fn igTextDisabledV(fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igTextWrapped(fmt: [*c]const u8, ...) void;
pub extern fn igTextWrappedV(fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igLabelText(label: [*c]const u8, fmt: [*c]const u8, ...) void;
pub extern fn igLabelTextV(label: [*c]const u8, fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igBulletText(fmt: [*c]const u8, ...) void;
pub extern fn igBulletTextV(fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igButton(label: [*c]const u8, size: ImVec2) bool;
pub extern fn igSmallButton(label: [*c]const u8) bool;
pub extern fn igInvisibleButton(str_id: [*c]const u8, size: ImVec2) bool;
pub extern fn igArrowButton(str_id: [*c]const u8, dir: ImGuiDir) bool;
pub extern fn igImage(user_texture_id: ImTextureID, size: ImVec2, uv0: ImVec2, uv1: ImVec2, tint_col: ImVec4, border_col: ImVec4) void;
pub extern fn igImageButton(user_texture_id: ImTextureID, size: ImVec2, uv0: ImVec2, uv1: ImVec2, frame_padding: c_int, bg_col: ImVec4, tint_col: ImVec4) bool;
pub extern fn igCheckbox(label: [*c]const u8, v: [*c]bool) bool;
pub extern fn igCheckboxFlags(label: [*c]const u8, flags: [*c]c_uint, flags_value: c_uint) bool;
pub extern fn igRadioButtonBool(label: [*c]const u8, active: bool) bool;
pub extern fn igRadioButtonIntPtr(label: [*c]const u8, v: [*c]c_int, v_button: c_int) bool;
pub extern fn igProgressBar(fraction: f32, size_arg: ImVec2, overlay: [*c]const u8) void;
pub extern fn igBullet() void;
pub extern fn igBeginCombo(label: [*c]const u8, preview_value: [*c]const u8, flags: ImGuiComboFlags) bool;
pub extern fn igEndCombo() void;
pub extern fn igComboStr_arr(label: [*c]const u8, current_item: [*c]c_int, items: [*c]const [*c]const u8, items_count: c_int, popup_max_height_in_items: c_int) bool;
pub extern fn igComboStr(label: [*c]const u8, current_item: [*c]c_int, items_separated_by_zeros: [*c]const u8, popup_max_height_in_items: c_int) bool;
pub extern fn igComboFnBoolPtr(label: [*c]const u8, current_item: [*c]c_int, items_getter: ?fn (?*c_void, c_int, [*c][*c]const u8) callconv(.C) bool, data: ?*c_void, items_count: c_int, popup_max_height_in_items: c_int) bool;
pub extern fn igDragFloat(label: [*c]const u8, v: [*c]f32, v_speed: f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igDragFloat2(label: [*c]const u8, v: [*c]f32, v_speed: f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igDragFloat3(label: [*c]const u8, v: [*c]f32, v_speed: f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igDragFloat4(label: [*c]const u8, v: [*c]f32, v_speed: f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igDragFloatRange2(label: [*c]const u8, v_current_min: [*c]f32, v_current_max: [*c]f32, v_speed: f32, v_min: f32, v_max: f32, format: [*c]const u8, format_max: [*c]const u8, power: f32) bool;
pub extern fn igDragInt(label: [*c]const u8, v: [*c]c_int, v_speed: f32, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igDragInt2(label: [*c]const u8, v: [*c]c_int, v_speed: f32, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igDragInt3(label: [*c]const u8, v: [*c]c_int, v_speed: f32, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igDragInt4(label: [*c]const u8, v: [*c]c_int, v_speed: f32, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igDragIntRange2(label: [*c]const u8, v_current_min: [*c]c_int, v_current_max: [*c]c_int, v_speed: f32, v_min: c_int, v_max: c_int, format: [*c]const u8, format_max: [*c]const u8) bool;
pub extern fn igDragScalar(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32) bool;
pub extern fn igDragScalarN(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, components: c_int, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderFloat(label: [*c]const u8, v: [*c]f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderFloat2(label: [*c]const u8, v: [*c]f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderFloat3(label: [*c]const u8, v: [*c]f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderFloat4(label: [*c]const u8, v: [*c]f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderAngle(label: [*c]const u8, v_rad: [*c]f32, v_degrees_min: f32, v_degrees_max: f32, format: [*c]const u8) bool;
pub extern fn igSliderInt(label: [*c]const u8, v: [*c]c_int, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igSliderInt2(label: [*c]const u8, v: [*c]c_int, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igSliderInt3(label: [*c]const u8, v: [*c]c_int, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igSliderInt4(label: [*c]const u8, v: [*c]c_int, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igSliderScalar(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32) bool;
pub extern fn igSliderScalarN(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, components: c_int, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32) bool;
pub extern fn igVSliderFloat(label: [*c]const u8, size: ImVec2, v: [*c]f32, v_min: f32, v_max: f32, format: [*c]const u8, power: f32) bool;
pub extern fn igVSliderInt(label: [*c]const u8, size: ImVec2, v: [*c]c_int, v_min: c_int, v_max: c_int, format: [*c]const u8) bool;
pub extern fn igVSliderScalar(label: [*c]const u8, size: ImVec2, data_type: ImGuiDataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32) bool;
pub extern fn igInputText(label: [*c]const u8, buf: [*c]u8, buf_size: usize, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback, user_data: ?*c_void) bool;
pub extern fn igInputTextMultiline(label: [*c]const u8, buf: [*c]u8, buf_size: usize, size: ImVec2, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback, user_data: ?*c_void) bool;
pub extern fn igInputTextWithHint(label: [*c]const u8, hint: [*c]const u8, buf: [*c]u8, buf_size: usize, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback, user_data: ?*c_void) bool;
pub extern fn igInputFloat(label: [*c]const u8, v: [*c]f32, step: f32, step_fast: f32, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputFloat2(label: [*c]const u8, v: [*c]f32, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputFloat3(label: [*c]const u8, v: [*c]f32, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputFloat4(label: [*c]const u8, v: [*c]f32, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputInt(label: [*c]const u8, v: [*c]c_int, step: c_int, step_fast: c_int, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputInt2(label: [*c]const u8, v: [*c]c_int, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputInt3(label: [*c]const u8, v: [*c]c_int, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputInt4(label: [*c]const u8, v: [*c]c_int, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputDouble(label: [*c]const u8, v: [*c]f64, step: f64, step_fast: f64, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputScalar(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igInputScalarN(label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, components: c_int, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: [*c]const u8, flags: ImGuiInputTextFlags) bool;
pub extern fn igColorEdit3(label: [*c]const u8, col: [*c]f32, flags: ImGuiColorEditFlags) bool;
pub extern fn igColorEdit4(label: [*c]const u8, col: [*c]f32, flags: ImGuiColorEditFlags) bool;
pub extern fn igColorPicker3(label: [*c]const u8, col: [*c]f32, flags: ImGuiColorEditFlags) bool;
pub extern fn igColorPicker4(label: [*c]const u8, col: [*c]f32, flags: ImGuiColorEditFlags, ref_col: [*c]const f32) bool;
pub extern fn igColorButton(desc_id: [*c]const u8, col: ImVec4, flags: ImGuiColorEditFlags, size: ImVec2) bool;
pub extern fn igSetColorEditOptions(flags: ImGuiColorEditFlags) void;
pub extern fn igTreeNodeStr(label: [*c]const u8) bool;
pub extern fn igTreeNodeStrStr(str_id: [*c]const u8, fmt: [*c]const u8, ...) bool;
pub extern fn igTreeNodePtr(ptr_id: ?*const c_void, fmt: [*c]const u8, ...) bool;
pub extern fn igTreeNodeVStr(str_id: [*c]const u8, fmt: [*c]const u8, args: [*c]struct___va_list_tag) bool;
pub extern fn igTreeNodeVPtr(ptr_id: ?*const c_void, fmt: [*c]const u8, args: [*c]struct___va_list_tag) bool;
pub extern fn igTreeNodeExStr(label: [*c]const u8, flags: ImGuiTreeNodeFlags) bool;
pub extern fn igTreeNodeExStrStr(str_id: [*c]const u8, flags: ImGuiTreeNodeFlags, fmt: [*c]const u8, ...) bool;
pub extern fn igTreeNodeExPtr(ptr_id: ?*const c_void, flags: ImGuiTreeNodeFlags, fmt: [*c]const u8, ...) bool;
pub extern fn igTreeNodeExVStr(str_id: [*c]const u8, flags: ImGuiTreeNodeFlags, fmt: [*c]const u8, args: [*c]struct___va_list_tag) bool;
pub extern fn igTreeNodeExVPtr(ptr_id: ?*const c_void, flags: ImGuiTreeNodeFlags, fmt: [*c]const u8, args: [*c]struct___va_list_tag) bool;
pub extern fn igTreePushStr(str_id: [*c]const u8) void;
pub extern fn igTreePushPtr(ptr_id: ?*const c_void) void;
pub extern fn igTreePop() void;
pub extern fn igGetTreeNodeToLabelSpacing() f32;
pub extern fn igCollapsingHeaderTreeNodeFlags(label: [*c]const u8, flags: ImGuiTreeNodeFlags) bool;
pub extern fn igCollapsingHeaderBoolPtr(label: [*c]const u8, p_open: [*c]bool, flags: ImGuiTreeNodeFlags) bool;
pub extern fn igSetNextItemOpen(is_open: bool, cond: ImGuiCond) void;
pub extern fn igSelectableBool(label: [*c]const u8, selected: bool, flags: ImGuiSelectableFlags, size: ImVec2) bool;
pub extern fn igSelectableBoolPtr(label: [*c]const u8, p_selected: [*c]bool, flags: ImGuiSelectableFlags, size: ImVec2) bool;
pub extern fn igListBoxStr_arr(label: [*c]const u8, current_item: [*c]c_int, items: [*c]const [*c]const u8, items_count: c_int, height_in_items: c_int) bool;
pub extern fn igListBoxFnBoolPtr(label: [*c]const u8, current_item: [*c]c_int, items_getter: ?fn (?*c_void, c_int, [*c][*c]const u8) callconv(.C) bool, data: ?*c_void, items_count: c_int, height_in_items: c_int) bool;
pub extern fn igListBoxHeaderVec2(label: [*c]const u8, size: ImVec2) bool;
pub extern fn igListBoxHeaderInt(label: [*c]const u8, items_count: c_int, height_in_items: c_int) bool;
pub extern fn igListBoxFooter() void;
pub extern fn igPlotLinesFloatPtr(label: [*c]const u8, values: [*c]const f32, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, graph_size: ImVec2, stride: c_int) void;
pub extern fn igPlotLinesFnFloatPtr(label: [*c]const u8, values_getter: ?fn (?*c_void, c_int) callconv(.C) f32, data: ?*c_void, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, graph_size: ImVec2) void;
pub extern fn igPlotHistogramFloatPtr(label: [*c]const u8, values: [*c]const f32, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, graph_size: ImVec2, stride: c_int) void;
pub extern fn igPlotHistogramFnFloatPtr(label: [*c]const u8, values_getter: ?fn (?*c_void, c_int) callconv(.C) f32, data: ?*c_void, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, graph_size: ImVec2) void;
pub extern fn igValueBool(prefix: [*c]const u8, b: bool) void;
pub extern fn igValueInt(prefix: [*c]const u8, v: c_int) void;
pub extern fn igValueUint(prefix: [*c]const u8, v: c_uint) void;
pub extern fn igValueFloat(prefix: [*c]const u8, v: f32, float_format: [*c]const u8) void;
pub extern fn igBeginMenuBar() bool;
pub extern fn igEndMenuBar() void;
pub extern fn igBeginMainMenuBar() bool;
pub extern fn igEndMainMenuBar() void;
pub extern fn igBeginMenu(label: [*c]const u8, enabled: bool) bool;
pub extern fn igEndMenu() void;
pub extern fn igMenuItemBool(label: [*c]const u8, shortcut: [*c]const u8, selected: bool, enabled: bool) bool;
pub extern fn igMenuItemBoolPtr(label: [*c]const u8, shortcut: [*c]const u8, p_selected: [*c]bool, enabled: bool) bool;
pub extern fn igBeginTooltip() void;
pub extern fn igEndTooltip() void;
pub extern fn igSetTooltip(fmt: [*c]const u8, ...) void;
pub extern fn igSetTooltipV(fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn igOpenPopup(str_id: [*c]const u8) void;
pub extern fn igBeginPopup(str_id: [*c]const u8, flags: ImGuiWindowFlags) bool;
pub extern fn igBeginPopupContextItem(str_id: [*c]const u8, mouse_button: ImGuiMouseButton) bool;
pub extern fn igBeginPopupContextWindow(str_id: [*c]const u8, mouse_button: ImGuiMouseButton, also_over_items: bool) bool;
pub extern fn igBeginPopupContextVoid(str_id: [*c]const u8, mouse_button: ImGuiMouseButton) bool;
pub extern fn igBeginPopupModal(name: [*c]const u8, p_open: [*c]bool, flags: ImGuiWindowFlags) bool;
pub extern fn igEndPopup() void;
pub extern fn igOpenPopupOnItemClick(str_id: [*c]const u8, mouse_button: ImGuiMouseButton) bool;
pub extern fn igIsPopupOpenStr(str_id: [*c]const u8) bool;
pub extern fn igCloseCurrentPopup() void;
pub extern fn igColumns(count: c_int, id: [*c]const u8, border: bool) void;
pub extern fn igNextColumn() void;
pub extern fn igGetColumnIndex() c_int;
pub extern fn igGetColumnWidth(column_index: c_int) f32;
pub extern fn igSetColumnWidth(column_index: c_int, width: f32) void;
pub extern fn igGetColumnOffset(column_index: c_int) f32;
pub extern fn igSetColumnOffset(column_index: c_int, offset_x: f32) void;
pub extern fn igGetColumnsCount() c_int;
pub extern fn igBeginTabBar(str_id: [*c]const u8, flags: ImGuiTabBarFlags) bool;
pub extern fn igEndTabBar() void;
pub extern fn igBeginTabItem(label: [*c]const u8, p_open: [*c]bool, flags: ImGuiTabItemFlags) bool;
pub extern fn igEndTabItem() void;
pub extern fn igSetTabItemClosed(tab_or_docked_window_label: [*c]const u8) void;
pub extern fn igDockSpace(id: ImGuiID, size: ImVec2, flags: ImGuiDockNodeFlags, window_class: [*c]const ImGuiWindowClass) void;
pub extern fn igDockSpaceOverViewport(viewport: [*c]ImGuiViewport, flags: ImGuiDockNodeFlags, window_class: [*c]const ImGuiWindowClass) ImGuiID;
pub extern fn igSetNextWindowDockID(dock_id: ImGuiID, cond: ImGuiCond) void;
pub extern fn igSetNextWindowClass(window_class: [*c]const ImGuiWindowClass) void;
pub extern fn igGetWindowDockID() ImGuiID;
pub extern fn igIsWindowDocked() bool;
pub extern fn igLogToTTY(auto_open_depth: c_int) void;
pub extern fn igLogToFile(auto_open_depth: c_int, filename: [*c]const u8) void;
pub extern fn igLogToClipboard(auto_open_depth: c_int) void;
pub extern fn igLogFinish() void;
pub extern fn igLogButtons() void;
pub extern fn igBeginDragDropSource(flags: ImGuiDragDropFlags) bool;
pub extern fn igSetDragDropPayload(type: [*c]const u8, data: ?*const c_void, sz: usize, cond: ImGuiCond) bool;
pub extern fn igEndDragDropSource() void;
pub extern fn igBeginDragDropTarget() bool;
pub extern fn igAcceptDragDropPayload(type: [*c]const u8, flags: ImGuiDragDropFlags) ?*const ImGuiPayload;
pub extern fn igEndDragDropTarget() void;
pub extern fn igGetDragDropPayload() [*c]const ImGuiPayload;
pub extern fn igPushClipRect(clip_rect_min: ImVec2, clip_rect_max: ImVec2, intersect_with_current_clip_rect: bool) void;
pub extern fn igPopClipRect() void;
pub extern fn igSetItemDefaultFocus() void;
pub extern fn igSetKeyboardFocusHere(offset: c_int) void;
pub extern fn igIsItemHovered(flags: ImGuiHoveredFlags) bool;
pub extern fn igIsItemActive() bool;
pub extern fn igIsItemFocused() bool;
pub extern fn igIsItemClicked(mouse_button: ImGuiMouseButton) bool;
pub extern fn igIsItemVisible() bool;
pub extern fn igIsItemEdited() bool;
pub extern fn igIsItemActivated() bool;
pub extern fn igIsItemDeactivated() bool;
pub extern fn igIsItemDeactivatedAfterEdit() bool;
pub extern fn igIsItemToggledOpen() bool;
pub extern fn igIsAnyItemHovered() bool;
pub extern fn igIsAnyItemActive() bool;
pub extern fn igIsAnyItemFocused() bool;
pub extern fn igGetItemRectMin(pOut: [*c]ImVec2) void;
pub extern fn igGetItemRectMax(pOut: [*c]ImVec2) void;
pub extern fn igGetItemRectSize(pOut: [*c]ImVec2) void;
pub extern fn igSetItemAllowOverlap() void;
pub extern fn igIsRectVisibleNil(size: ImVec2) bool;
pub extern fn igIsRectVisibleVec2(rect_min: ImVec2, rect_max: ImVec2) bool;
pub extern fn igGetTime() f64;
pub extern fn igGetFrameCount() c_int;
pub extern fn igGetBackgroundDrawListNil() [*c]ImDrawList;
pub extern fn igGetForegroundDrawListNil() [*c]ImDrawList;
pub extern fn igGetBackgroundDrawListViewportPtr(viewport: [*c]ImGuiViewport) [*c]ImDrawList;
pub extern fn igGetForegroundDrawListViewportPtr(viewport: [*c]ImGuiViewport) [*c]ImDrawList;
pub extern fn igGetDrawListSharedData() [*c]ImDrawListSharedData;
pub extern fn igGetStyleColorName(idx: ImGuiCol) [*c]const u8;
pub extern fn igSetStateStorage(storage: [*c]ImGuiStorage) void;
pub extern fn igGetStateStorage() [*c]ImGuiStorage;
pub extern fn igCalcListClipping(items_count: c_int, items_height: f32, out_items_display_start: [*c]c_int, out_items_display_end: [*c]c_int) void;
pub extern fn igBeginChildFrame(id: ImGuiID, size: ImVec2, flags: ImGuiWindowFlags) bool;
pub extern fn igEndChildFrame() void;
pub extern fn igCalcTextSize(pOut: [*c]ImVec2, text: [*c]const u8, text_end: [*c]const u8, hide_text_after_double_hash: bool, wrap_width: f32) void;
pub extern fn igColorConvertU32ToFloat4(pOut: [*c]ImVec4, in: ImU32) void;
pub extern fn igColorConvertFloat4ToU32(in: ImVec4) ImU32;
pub extern fn igColorConvertRGBtoHSV(r: f32, g: f32, b: f32, out_h: [*c]f32, out_s: [*c]f32, out_v: [*c]f32) void;
pub extern fn igColorConvertHSVtoRGB(h: f32, s: f32, v: f32, out_r: [*c]f32, out_g: [*c]f32, out_b: [*c]f32) void;
pub extern fn igGetKeyIndex(imgui_key: ImGuiKey) c_int;
pub extern fn igIsKeyDown(user_key_index: c_int) bool;
pub extern fn igIsKeyPressed(user_key_index: c_int, repeat: bool) bool;
pub extern fn igIsKeyReleased(user_key_index: c_int) bool;
pub extern fn igGetKeyPressedAmount(key_index: c_int, repeat_delay: f32, rate: f32) c_int;
pub extern fn igCaptureKeyboardFromApp(want_capture_keyboard_value: bool) void;
pub extern fn igIsMouseDown(button: ImGuiMouseButton) bool;
pub extern fn igIsMouseClicked(button: ImGuiMouseButton, repeat: bool) bool;
pub extern fn igIsMouseReleased(button: ImGuiMouseButton) bool;
pub extern fn igIsMouseDoubleClicked(button: ImGuiMouseButton) bool;
pub extern fn igIsMouseHoveringRect(r_min: ImVec2, r_max: ImVec2, clip: bool) bool;
pub extern fn igIsMousePosValid(mouse_pos: [*c]const ImVec2) bool;
pub extern fn igIsAnyMouseDown() bool;
pub extern fn igGetMousePos(pOut: [*c]ImVec2) void;
pub extern fn igGetMousePosOnOpeningCurrentPopup(pOut: [*c]ImVec2) void;
pub extern fn igIsMouseDragging(button: ImGuiMouseButton, lock_threshold: f32) bool;
pub extern fn igGetMouseDragDelta(pOut: [*c]ImVec2, button: ImGuiMouseButton, lock_threshold: f32) void;
pub extern fn igResetMouseDragDelta(button: ImGuiMouseButton) void;
pub extern fn igGetMouseCursor() ImGuiMouseCursor;
pub extern fn igSetMouseCursor(cursor_type: ImGuiMouseCursor) void;
pub extern fn igCaptureMouseFromApp(want_capture_mouse_value: bool) void;
pub extern fn igGetClipboardText() [*c]const u8;
pub extern fn igSetClipboardText(text: [*c]const u8) void;
pub extern fn igLoadIniSettingsFromDisk(ini_filename: [*c]const u8) void;
pub extern fn igLoadIniSettingsFromMemory(ini_data: [*c]const u8, ini_size: usize) void;
pub extern fn igSaveIniSettingsToDisk(ini_filename: [*c]const u8) void;
pub extern fn igSaveIniSettingsToMemory(out_ini_size: [*c]usize) [*c]const u8;
pub extern fn igDebugCheckVersionAndDataLayout(version_str: [*c]const u8, sz_io: usize, sz_style: usize, sz_vec2: usize, sz_vec4: usize, sz_drawvert: usize, sz_drawidx: usize) bool;
pub extern fn igSetAllocatorFunctions(alloc_func: ?fn (usize, ?*c_void) callconv(.C) ?*c_void, free_func: ?fn (?*c_void, ?*c_void) callconv(.C) void, user_data: ?*c_void) void;
pub extern fn igMemAlloc(size: usize) ?*c_void;
pub extern fn igMemFree(ptr: ?*c_void) void;
pub extern fn igGetPlatformIO() [*c]ImGuiPlatformIO;
pub extern fn igGetMainViewport() *ImGuiViewport;
pub extern fn igUpdatePlatformWindows() void;
pub extern fn igRenderPlatformWindowsDefault(platform_render_arg: ?*c_void, renderer_render_arg: ?*c_void) void;
pub extern fn igDestroyPlatformWindows() void;
pub extern fn igFindViewportByID(id: ImGuiID) [*c]ImGuiViewport;
pub extern fn igFindViewportByPlatformHandle(platform_handle: ?*c_void) ?*ImGuiViewport;
pub extern fn ImGuiStyle_ImGuiStyle() [*c]ImGuiStyle;
pub extern fn ImGuiStyle_destroy(self: [*c]ImGuiStyle) void;
pub extern fn ImGuiStyle_ScaleAllSizes(self: [*c]ImGuiStyle, scale_factor: f32) void;
pub extern fn ImGuiIO_AddInputCharacter(self: [*c]ImGuiIO, c: c_uint) void;
pub extern fn ImGuiIO_AddInputCharacterUTF16(self: [*c]ImGuiIO, c: ImWchar16) void;
pub extern fn ImGuiIO_AddInputCharactersUTF8(self: [*c]ImGuiIO, str: [*c]const u8) void;
pub extern fn ImGuiIO_ClearInputCharacters(self: [*c]ImGuiIO) void;
pub extern fn ImGuiIO_ImGuiIO() [*c]ImGuiIO;
pub extern fn ImGuiIO_destroy(self: [*c]ImGuiIO) void;
pub extern fn ImGuiInputTextCallbackData_ImGuiInputTextCallbackData() [*c]ImGuiInputTextCallbackData;
pub extern fn ImGuiInputTextCallbackData_destroy(self: [*c]ImGuiInputTextCallbackData) void;
pub extern fn ImGuiInputTextCallbackData_DeleteChars(self: [*c]ImGuiInputTextCallbackData, pos: c_int, bytes_count: c_int) void;
pub extern fn ImGuiInputTextCallbackData_InsertChars(self: [*c]ImGuiInputTextCallbackData, pos: c_int, text: [*c]const u8, text_end: [*c]const u8) void;
pub extern fn ImGuiInputTextCallbackData_HasSelection(self: [*c]ImGuiInputTextCallbackData) bool;
pub extern fn ImGuiWindowClass_ImGuiWindowClass() [*c]ImGuiWindowClass;
pub extern fn ImGuiWindowClass_destroy(self: [*c]ImGuiWindowClass) void;
pub extern fn ImGuiPayload_ImGuiPayload() [*c]ImGuiPayload;
pub extern fn ImGuiPayload_destroy(self: [*c]ImGuiPayload) void;
pub extern fn ImGuiPayload_Clear(self: [*c]ImGuiPayload) void;
pub extern fn ImGuiPayload_IsDataType(self: [*c]ImGuiPayload, type: [*c]const u8) bool;
pub extern fn ImGuiPayload_IsPreview(self: [*c]ImGuiPayload) bool;
pub extern fn ImGuiPayload_IsDelivery(self: [*c]ImGuiPayload) bool;
pub extern fn ImGuiOnceUponAFrame_ImGuiOnceUponAFrame() [*c]ImGuiOnceUponAFrame;
pub extern fn ImGuiOnceUponAFrame_destroy(self: [*c]ImGuiOnceUponAFrame) void;
pub extern fn ImGuiTextFilter_ImGuiTextFilter(default_filter: [*c]const u8) [*c]ImGuiTextFilter;
pub extern fn ImGuiTextFilter_destroy(self: [*c]ImGuiTextFilter) void;
pub extern fn ImGuiTextFilter_Draw(self: [*c]ImGuiTextFilter, label: [*c]const u8, width: f32) bool;
pub extern fn ImGuiTextFilter_PassFilter(self: [*c]ImGuiTextFilter, text: [*c]const u8, text_end: [*c]const u8) bool;
pub extern fn ImGuiTextFilter_Build(self: [*c]ImGuiTextFilter) void;
pub extern fn ImGuiTextFilter_Clear(self: [*c]ImGuiTextFilter) void;
pub extern fn ImGuiTextFilter_IsActive(self: [*c]ImGuiTextFilter) bool;
pub extern fn ImGuiTextRange_ImGuiTextRangeNil() [*c]ImGuiTextRange;
pub extern fn ImGuiTextRange_destroy(self: [*c]ImGuiTextRange) void;
pub extern fn ImGuiTextRange_ImGuiTextRangeStr(_b: [*c]const u8, _e: [*c]const u8) [*c]ImGuiTextRange;
pub extern fn ImGuiTextRange_empty(self: [*c]ImGuiTextRange) bool;
pub extern fn ImGuiTextRange_split(self: [*c]ImGuiTextRange, separator: u8, out: [*c]ImVector_ImGuiTextRange) void;
pub extern fn ImGuiTextBuffer_ImGuiTextBuffer() [*c]ImGuiTextBuffer;
pub extern fn ImGuiTextBuffer_destroy(self: [*c]ImGuiTextBuffer) void;
pub extern fn ImGuiTextBuffer_begin(self: [*c]ImGuiTextBuffer) [*c]const u8;
pub extern fn ImGuiTextBuffer_end(self: [*c]ImGuiTextBuffer) [*c]const u8;
pub extern fn ImGuiTextBuffer_size(self: [*c]ImGuiTextBuffer) c_int;
pub extern fn ImGuiTextBuffer_empty(self: [*c]ImGuiTextBuffer) bool;
pub extern fn ImGuiTextBuffer_clear(self: [*c]ImGuiTextBuffer) void;
pub extern fn ImGuiTextBuffer_reserve(self: [*c]ImGuiTextBuffer, capacity: c_int) void;
pub extern fn ImGuiTextBuffer_c_str(self: [*c]ImGuiTextBuffer) [*c]const u8;
pub extern fn ImGuiTextBuffer_append(self: [*c]ImGuiTextBuffer, str: [*c]const u8, str_end: [*c]const u8) void;
pub extern fn ImGuiTextBuffer_appendfv(self: [*c]ImGuiTextBuffer, fmt: [*c]const u8, args: [*c]struct___va_list_tag) void;
pub extern fn ImGuiStoragePair_ImGuiStoragePairInt(_key: ImGuiID, _val_i: c_int) [*c]ImGuiStoragePair;
pub extern fn ImGuiStoragePair_destroy(self: [*c]ImGuiStoragePair) void;
pub extern fn ImGuiStoragePair_ImGuiStoragePairFloat(_key: ImGuiID, _val_f: f32) [*c]ImGuiStoragePair;
pub extern fn ImGuiStoragePair_ImGuiStoragePairPtr(_key: ImGuiID, _val_p: ?*c_void) [*c]ImGuiStoragePair;
pub extern fn ImGuiStorage_Clear(self: [*c]ImGuiStorage) void;
pub extern fn ImGuiStorage_GetInt(self: [*c]ImGuiStorage, key: ImGuiID, default_val: c_int) c_int;
pub extern fn ImGuiStorage_SetInt(self: [*c]ImGuiStorage, key: ImGuiID, val: c_int) void;
pub extern fn ImGuiStorage_GetBool(self: [*c]ImGuiStorage, key: ImGuiID, default_val: bool) bool;
pub extern fn ImGuiStorage_SetBool(self: [*c]ImGuiStorage, key: ImGuiID, val: bool) void;
pub extern fn ImGuiStorage_GetFloat(self: [*c]ImGuiStorage, key: ImGuiID, default_val: f32) f32;
pub extern fn ImGuiStorage_SetFloat(self: [*c]ImGuiStorage, key: ImGuiID, val: f32) void;
pub extern fn ImGuiStorage_GetVoidPtr(self: [*c]ImGuiStorage, key: ImGuiID) ?*c_void;
pub extern fn ImGuiStorage_SetVoidPtr(self: [*c]ImGuiStorage, key: ImGuiID, val: ?*c_void) void;
pub extern fn ImGuiStorage_GetIntRef(self: [*c]ImGuiStorage, key: ImGuiID, default_val: c_int) [*c]c_int;
pub extern fn ImGuiStorage_GetBoolRef(self: [*c]ImGuiStorage, key: ImGuiID, default_val: bool) [*c]bool;
pub extern fn ImGuiStorage_GetFloatRef(self: [*c]ImGuiStorage, key: ImGuiID, default_val: f32) [*c]f32;
pub extern fn ImGuiStorage_GetVoidPtrRef(self: [*c]ImGuiStorage, key: ImGuiID, default_val: ?*c_void) [*c]?*c_void;
pub extern fn ImGuiStorage_SetAllInt(self: [*c]ImGuiStorage, val: c_int) void;
pub extern fn ImGuiStorage_BuildSortByKey(self: [*c]ImGuiStorage) void;
pub extern fn ImGuiListClipper_ImGuiListClipper(items_count: c_int, items_height: f32) [*c]ImGuiListClipper;
pub extern fn ImGuiListClipper_destroy(self: [*c]ImGuiListClipper) void;
pub extern fn ImGuiListClipper_Step(self: [*c]ImGuiListClipper) bool;
pub extern fn ImGuiListClipper_Begin(self: [*c]ImGuiListClipper, items_count: c_int, items_height: f32) void;
pub extern fn ImGuiListClipper_End(self: [*c]ImGuiListClipper) void;
pub extern fn ImColor_ImColorNil() [*c]ImColor;
pub extern fn ImColor_destroy(self: [*c]ImColor) void;
pub extern fn ImColor_ImColorInt(r: c_int, g: c_int, b: c_int, a: c_int) [*c]ImColor;
pub extern fn ImColor_ImColorU32(rgba: ImU32) [*c]ImColor;
pub extern fn ImColor_ImColorFloat(r: f32, g: f32, b: f32, a: f32) [*c]ImColor;
pub extern fn ImColor_ImColorVec4(col: ImVec4) [*c]ImColor;
pub extern fn ImColor_SetHSV(self: [*c]ImColor, h: f32, s: f32, v: f32, a: f32) void;
pub extern fn ImColor_HSV(pOut: [*c]ImColor, self: [*c]ImColor, h: f32, s: f32, v: f32, a: f32) void;
pub extern fn ImDrawCmd_ImDrawCmd() [*c]ImDrawCmd;
pub extern fn ImDrawCmd_destroy(self: [*c]ImDrawCmd) void;
pub extern fn ImDrawListSplitter_ImDrawListSplitter() [*c]ImDrawListSplitter;
pub extern fn ImDrawListSplitter_destroy(self: [*c]ImDrawListSplitter) void;
pub extern fn ImDrawListSplitter_Clear(self: [*c]ImDrawListSplitter) void;
pub extern fn ImDrawListSplitter_ClearFreeMemory(self: [*c]ImDrawListSplitter) void;
pub extern fn ImDrawListSplitter_Split(self: [*c]ImDrawListSplitter, draw_list: [*c]ImDrawList, count: c_int) void;
pub extern fn ImDrawListSplitter_Merge(self: [*c]ImDrawListSplitter, draw_list: [*c]ImDrawList) void;
pub extern fn ImDrawListSplitter_SetCurrentChannel(self: [*c]ImDrawListSplitter, draw_list: [*c]ImDrawList, channel_idx: c_int) void;
pub extern fn ImDrawList_ImDrawList(shared_data: [*c]const ImDrawListSharedData) [*c]ImDrawList;
pub extern fn ImDrawList_destroy(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_PushClipRect(self: [*c]ImDrawList, clip_rect_min: ImVec2, clip_rect_max: ImVec2, intersect_with_current_clip_rect: bool) void;
pub extern fn ImDrawList_PushClipRectFullScreen(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_PopClipRect(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_PushTextureID(self: [*c]ImDrawList, texture_id: ImTextureID) void;
pub extern fn ImDrawList_PopTextureID(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_GetClipRectMin(pOut: [*c]ImVec2, self: [*c]ImDrawList) void;
pub extern fn ImDrawList_GetClipRectMax(pOut: [*c]ImVec2, self: [*c]ImDrawList) void;
pub extern fn ImDrawList_AddLine(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, col: ImU32, thickness: f32) void;
pub extern fn ImDrawList_AddRect(self: [*c]ImDrawList, p_min: ImVec2, p_max: ImVec2, col: ImU32, rounding: f32, rounding_corners: ImDrawCornerFlags, thickness: f32) void;
pub extern fn ImDrawList_AddRectFilled(self: [*c]ImDrawList, p_min: ImVec2, p_max: ImVec2, col: ImU32, rounding: f32, rounding_corners: ImDrawCornerFlags) void;
pub extern fn ImDrawList_AddRectFilledMultiColor(self: [*c]ImDrawList, p_min: ImVec2, p_max: ImVec2, col_upr_left: ImU32, col_upr_right: ImU32, col_bot_right: ImU32, col_bot_left: ImU32) void;
pub extern fn ImDrawList_AddQuad(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, col: ImU32, thickness: f32) void;
pub extern fn ImDrawList_AddQuadFilled(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_AddTriangle(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, p3: ImVec2, col: ImU32, thickness: f32) void;
pub extern fn ImDrawList_AddTriangleFilled(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, p3: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_AddCircle(self: [*c]ImDrawList, center: ImVec2, radius: f32, col: ImU32, num_segments: c_int, thickness: f32) void;
pub extern fn ImDrawList_AddCircleFilled(self: [*c]ImDrawList, center: ImVec2, radius: f32, col: ImU32, num_segments: c_int) void;
pub extern fn ImDrawList_AddNgon(self: [*c]ImDrawList, center: ImVec2, radius: f32, col: ImU32, num_segments: c_int, thickness: f32) void;
pub extern fn ImDrawList_AddNgonFilled(self: [*c]ImDrawList, center: ImVec2, radius: f32, col: ImU32, num_segments: c_int) void;
pub extern fn ImDrawList_AddTextVec2(self: [*c]ImDrawList, pos: ImVec2, col: ImU32, text_begin: [*c]const u8, text_end: [*c]const u8) void;
pub extern fn ImDrawList_AddTextFontPtr(self: [*c]ImDrawList, font: [*c]const ImFont, font_size: f32, pos: ImVec2, col: ImU32, text_begin: [*c]const u8, text_end: [*c]const u8, wrap_width: f32, cpu_fine_clip_rect: [*c]const ImVec4) void;
pub extern fn ImDrawList_AddPolyline(self: [*c]ImDrawList, points: [*c]const ImVec2, num_points: c_int, col: ImU32, closed: bool, thickness: f32) void;
pub extern fn ImDrawList_AddConvexPolyFilled(self: [*c]ImDrawList, points: [*c]const ImVec2, num_points: c_int, col: ImU32) void;
pub extern fn ImDrawList_AddBezierCurve(self: [*c]ImDrawList, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, col: ImU32, thickness: f32, num_segments: c_int) void;
pub extern fn ImDrawList_AddImage(self: [*c]ImDrawList, user_texture_id: ImTextureID, p_min: ImVec2, p_max: ImVec2, uv_min: ImVec2, uv_max: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_AddImageQuad(self: [*c]ImDrawList, user_texture_id: ImTextureID, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, uv1: ImVec2, uv2: ImVec2, uv3: ImVec2, uv4: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_AddImageRounded(self: [*c]ImDrawList, user_texture_id: ImTextureID, p_min: ImVec2, p_max: ImVec2, uv_min: ImVec2, uv_max: ImVec2, col: ImU32, rounding: f32, rounding_corners: ImDrawCornerFlags) void;
pub extern fn ImDrawList_PathClear(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_PathLineTo(self: [*c]ImDrawList, pos: ImVec2) void;
pub extern fn ImDrawList_PathLineToMergeDuplicate(self: [*c]ImDrawList, pos: ImVec2) void;
pub extern fn ImDrawList_PathFillConvex(self: [*c]ImDrawList, col: ImU32) void;
pub extern fn ImDrawList_PathStroke(self: [*c]ImDrawList, col: ImU32, closed: bool, thickness: f32) void;
pub extern fn ImDrawList_PathArcTo(self: [*c]ImDrawList, center: ImVec2, radius: f32, a_min: f32, a_max: f32, num_segments: c_int) void;
pub extern fn ImDrawList_PathArcToFast(self: [*c]ImDrawList, center: ImVec2, radius: f32, a_min_of_12: c_int, a_max_of_12: c_int) void;
pub extern fn ImDrawList_PathBezierCurveTo(self: [*c]ImDrawList, p2: ImVec2, p3: ImVec2, p4: ImVec2, num_segments: c_int) void;
pub extern fn ImDrawList_PathRect(self: [*c]ImDrawList, rect_min: ImVec2, rect_max: ImVec2, rounding: f32, rounding_corners: ImDrawCornerFlags) void;
pub extern fn ImDrawList_AddCallback(self: [*c]ImDrawList, callback: ImDrawCallback, callback_data: ?*c_void) void;
pub extern fn ImDrawList_AddDrawCmd(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_CloneOutput(self: [*c]ImDrawList) [*c]ImDrawList;
pub extern fn ImDrawList_ChannelsSplit(self: [*c]ImDrawList, count: c_int) void;
pub extern fn ImDrawList_ChannelsMerge(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_ChannelsSetCurrent(self: [*c]ImDrawList, n: c_int) void;
pub extern fn ImDrawList_Clear(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_ClearFreeMemory(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_PrimReserve(self: [*c]ImDrawList, idx_count: c_int, vtx_count: c_int) void;
pub extern fn ImDrawList_PrimUnreserve(self: [*c]ImDrawList, idx_count: c_int, vtx_count: c_int) void;
pub extern fn ImDrawList_PrimRect(self: [*c]ImDrawList, a: ImVec2, b: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_PrimRectUV(self: [*c]ImDrawList, a: ImVec2, b: ImVec2, uv_a: ImVec2, uv_b: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_PrimQuadUV(self: [*c]ImDrawList, a: ImVec2, b: ImVec2, c: ImVec2, d: ImVec2, uv_a: ImVec2, uv_b: ImVec2, uv_c: ImVec2, uv_d: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_PrimWriteVtx(self: [*c]ImDrawList, pos: ImVec2, uv: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_PrimWriteIdx(self: [*c]ImDrawList, idx: ImDrawIdx) void;
pub extern fn ImDrawList_PrimVtx(self: [*c]ImDrawList, pos: ImVec2, uv: ImVec2, col: ImU32) void;
pub extern fn ImDrawList_UpdateClipRect(self: [*c]ImDrawList) void;
pub extern fn ImDrawList_UpdateTextureID(self: [*c]ImDrawList) void;
pub extern fn ImDrawData_ImDrawData() [*c]ImDrawData;
pub extern fn ImDrawData_destroy(self: [*c]ImDrawData) void;
pub extern fn ImDrawData_Clear(self: [*c]ImDrawData) void;
pub extern fn ImDrawData_DeIndexAllBuffers(self: [*c]ImDrawData) void;
pub extern fn ImDrawData_ScaleClipRects(self: [*c]ImDrawData, fb_scale: ImVec2) void;
pub extern fn ImFontConfig_ImFontConfig() [*c]ImFontConfig;
pub extern fn ImFontConfig_destroy(self: [*c]ImFontConfig) void;
pub extern fn ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder() [*c]ImFontGlyphRangesBuilder;
pub extern fn ImFontGlyphRangesBuilder_destroy(self: [*c]ImFontGlyphRangesBuilder) void;
pub extern fn ImFontGlyphRangesBuilder_Clear(self: [*c]ImFontGlyphRangesBuilder) void;
pub extern fn ImFontGlyphRangesBuilder_GetBit(self: [*c]ImFontGlyphRangesBuilder, n: usize) bool;
pub extern fn ImFontGlyphRangesBuilder_SetBit(self: [*c]ImFontGlyphRangesBuilder, n: usize) void;
pub extern fn ImFontGlyphRangesBuilder_AddChar(self: [*c]ImFontGlyphRangesBuilder, c: ImWchar) void;
pub extern fn ImFontGlyphRangesBuilder_AddText(self: [*c]ImFontGlyphRangesBuilder, text: [*c]const u8, text_end: [*c]const u8) void;
pub extern fn ImFontGlyphRangesBuilder_AddRanges(self: [*c]ImFontGlyphRangesBuilder, ranges: [*c]const ImWchar) void;
pub extern fn ImFontGlyphRangesBuilder_BuildRanges(self: [*c]ImFontGlyphRangesBuilder, out_ranges: [*c]ImVector_ImWchar) void;
pub extern fn ImFontAtlasCustomRect_ImFontAtlasCustomRect() [*c]ImFontAtlasCustomRect;
pub extern fn ImFontAtlasCustomRect_destroy(self: [*c]ImFontAtlasCustomRect) void;
pub extern fn ImFontAtlasCustomRect_IsPacked(self: [*c]ImFontAtlasCustomRect) bool;
pub extern fn ImFontAtlas_ImFontAtlas() [*c]ImFontAtlas;
pub extern fn ImFontAtlas_destroy(self: [*c]ImFontAtlas) void;
pub extern fn ImFontAtlas_AddFont(self: [*c]ImFontAtlas, font_cfg: [*c]const ImFontConfig) [*c]ImFont;
pub extern fn ImFontAtlas_AddFontDefault(self: [*c]ImFontAtlas, font_cfg: [*c]const ImFontConfig) [*c]ImFont;
pub extern fn ImFontAtlas_AddFontFromFileTTF(self: [*c]ImFontAtlas, filename: [*c]const u8, size_pixels: f32, font_cfg: [*c]const ImFontConfig, glyph_ranges: [*c]const ImWchar) [*c]ImFont;
pub extern fn ImFontAtlas_AddFontFromMemoryTTF(self: [*c]ImFontAtlas, font_data: ?*const c_void, font_size: c_int, size_pixels: f32, font_cfg: [*c]const ImFontConfig, glyph_ranges: [*c]const ImWchar) [*c]ImFont;
pub extern fn ImFontAtlas_AddFontFromMemoryCompressedTTF(self: [*c]ImFontAtlas, compressed_font_data: ?*const c_void, compressed_font_size: c_int, size_pixels: f32, font_cfg: [*c]const ImFontConfig, glyph_ranges: [*c]const ImWchar) [*c]ImFont;
pub extern fn ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(self: [*c]ImFontAtlas, compressed_font_data_base85: [*c]const u8, size_pixels: f32, font_cfg: [*c]const ImFontConfig, glyph_ranges: [*c]const ImWchar) [*c]ImFont;
pub extern fn ImFontAtlas_ClearInputData(self: [*c]ImFontAtlas) void;
pub extern fn ImFontAtlas_ClearTexData(self: [*c]ImFontAtlas) void;
pub extern fn ImFontAtlas_ClearFonts(self: [*c]ImFontAtlas) void;
pub extern fn ImFontAtlas_Clear(self: [*c]ImFontAtlas) void;
pub extern fn ImFontAtlas_Build(self: [*c]ImFontAtlas) bool;
pub extern fn ImFontAtlas_GetTexDataAsAlpha8(self: [*c]ImFontAtlas, out_pixels: [*c][*c]u8, out_width: [*c]c_int, out_height: [*c]c_int, out_bytes_per_pixel: [*c]c_int) void;
pub extern fn ImFontAtlas_GetTexDataAsRGBA32(self: [*c]ImFontAtlas, out_pixels: [*c][*c]u8, out_width: [*c]c_int, out_height: [*c]c_int, out_bytes_per_pixel: [*c]c_int) void;
pub extern fn ImFontAtlas_IsBuilt(self: [*c]ImFontAtlas) bool;
pub extern fn ImFontAtlas_SetTexID(self: [*c]ImFontAtlas, id: ImTextureID) void;
pub extern fn ImFontAtlas_GetGlyphRangesDefault(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesKorean(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesJapanese(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesChineseFull(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesCyrillic(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesThai(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_GetGlyphRangesVietnamese(self: [*c]ImFontAtlas) [*c]const ImWchar;
pub extern fn ImFontAtlas_AddCustomRectRegular(self: [*c]ImFontAtlas, width: c_int, height: c_int) c_int;
pub extern fn ImFontAtlas_AddCustomRectFontGlyph(self: [*c]ImFontAtlas, font: [*c]ImFont, id: ImWchar, width: c_int, height: c_int, advance_x: f32, offset: ImVec2) c_int;
pub extern fn ImFontAtlas_GetCustomRectByIndex(self: [*c]ImFontAtlas, index: c_int) [*c]const ImFontAtlasCustomRect;
pub extern fn ImFontAtlas_CalcCustomRectUV(self: [*c]ImFontAtlas, rect: [*c]const ImFontAtlasCustomRect, out_uv_min: [*c]ImVec2, out_uv_max: [*c]ImVec2) void;
pub extern fn ImFontAtlas_GetMouseCursorTexData(self: [*c]ImFontAtlas, cursor: ImGuiMouseCursor, out_offset: [*c]ImVec2, out_size: [*c]ImVec2, out_uv_border: [*c]ImVec2, out_uv_fill: [*c]ImVec2) bool;
pub extern fn ImFont_ImFont() [*c]ImFont;
pub extern fn ImFont_destroy(self: [*c]ImFont) void;
pub extern fn ImFont_FindGlyph(self: [*c]ImFont, c: ImWchar) ?*const ImFontGlyph;
pub extern fn ImFont_FindGlyphNoFallback(self: [*c]ImFont, c: ImWchar) ?*const ImFontGlyph;
pub extern fn ImFont_GetCharAdvance(self: [*c]ImFont, c: ImWchar) f32;
pub extern fn ImFont_IsLoaded(self: [*c]ImFont) bool;
pub extern fn ImFont_GetDebugName(self: [*c]ImFont) [*c]const u8;
pub extern fn ImFont_CalcTextSizeA(pOut: [*c]ImVec2, self: [*c]ImFont, size: f32, max_width: f32, wrap_width: f32, text_begin: [*c]const u8, text_end: [*c]const u8, remaining: [*c][*c]const u8) void;
pub extern fn ImFont_CalcWordWrapPositionA(self: [*c]ImFont, scale: f32, text: [*c]const u8, text_end: [*c]const u8, wrap_width: f32) [*c]const u8;
pub extern fn ImFont_RenderChar(self: [*c]ImFont, draw_list: [*c]ImDrawList, size: f32, pos: ImVec2, col: ImU32, c: ImWchar) void;
pub extern fn ImFont_RenderText(self: [*c]ImFont, draw_list: [*c]ImDrawList, size: f32, pos: ImVec2, col: ImU32, clip_rect: ImVec4, text_begin: [*c]const u8, text_end: [*c]const u8, wrap_width: f32, cpu_fine_clip: bool) void;
pub extern fn ImFont_BuildLookupTable(self: [*c]ImFont) void;
pub extern fn ImFont_ClearOutputData(self: [*c]ImFont) void;
pub extern fn ImFont_GrowIndex(self: [*c]ImFont, new_size: c_int) void;
pub extern fn ImFont_AddGlyph(self: [*c]ImFont, c: ImWchar, x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, advance_x: f32) void;
pub extern fn ImFont_AddRemapChar(self: [*c]ImFont, dst: ImWchar, src: ImWchar, overwrite_dst: bool) void;
pub extern fn ImFont_SetGlyphVisible(self: [*c]ImFont, c: ImWchar, visible: bool) void;
pub extern fn ImFont_SetFallbackChar(self: [*c]ImFont, c: ImWchar) void;
pub extern fn ImFont_IsGlyphRangeUnused(self: [*c]ImFont, c_begin: c_uint, c_last: c_uint) bool;
pub extern fn ImGuiPlatformIO_ImGuiPlatformIO() [*c]ImGuiPlatformIO;
pub extern fn ImGuiPlatformIO_destroy(self: [*c]ImGuiPlatformIO) void;
pub extern fn ImGuiPlatformMonitor_ImGuiPlatformMonitor() [*c]ImGuiPlatformMonitor;
pub extern fn ImGuiPlatformMonitor_destroy(self: [*c]ImGuiPlatformMonitor) void;
pub extern fn ImGuiViewport_ImGuiViewport() [*c]ImGuiViewport;
pub extern fn ImGuiViewport_destroy(self: [*c]ImGuiViewport) void;
pub extern fn ImGuiViewport_GetWorkPos(pOut: [*c]ImVec2, self: [*c]ImGuiViewport) void;
pub extern fn ImGuiViewport_GetWorkSize(pOut: [*c]ImVec2, self: [*c]ImGuiViewport) void;
pub extern fn igImHashData(data: ?*const c_void, data_size: usize, seed: ImU32) ImU32;
pub extern fn igImHashStr(data: [*c]const u8, data_size: usize, seed: ImU32) ImU32;
pub extern fn igImAlphaBlendColors(col_a: ImU32, col_b: ImU32) ImU32;
pub extern fn igImIsPowerOfTwo(v: c_int) bool;
pub extern fn igImUpperPowerOfTwo(v: c_int) c_int;
pub extern fn igImStricmp(str1: [*c]const u8, str2: [*c]const u8) c_int;
pub extern fn igImStrnicmp(str1: [*c]const u8, str2: [*c]const u8, count: usize) c_int;
pub extern fn igImStrncpy(dst: [*c]u8, src: [*c]const u8, count: usize) void;
pub extern fn igImStrdup(str: [*c]const u8) [*c]u8;
pub extern fn igImStrdupcpy(dst: [*c]u8, p_dst_size: [*c]usize, str: [*c]const u8) [*c]u8;
pub extern fn igImStrchrRange(str_begin: [*c]const u8, str_end: [*c]const u8, c: u8) [*c]const u8;
pub extern fn igImStrlenW(str: [*c]const ImWchar) c_int;
pub extern fn igImStreolRange(str: [*c]const u8, str_end: [*c]const u8) [*c]const u8;
pub extern fn igImStrbolW(buf_mid_line: [*c]const ImWchar, buf_begin: [*c]const ImWchar) [*c]const ImWchar;
pub extern fn igImStristr(haystack: [*c]const u8, haystack_end: [*c]const u8, needle: [*c]const u8, needle_end: [*c]const u8) [*c]const u8;
pub extern fn igImStrTrimBlanks(str: [*c]u8) void;
pub extern fn igImStrSkipBlank(str: [*c]const u8) [*c]const u8;
pub extern fn igImFormatString(buf: [*c]u8, buf_size: usize, fmt: [*c]const u8, ...) c_int;
pub extern fn igImFormatStringV(buf: [*c]u8, buf_size: usize, fmt: [*c]const u8, args: [*c]struct___va_list_tag) c_int;
pub extern fn igImParseFormatFindStart(format: [*c]const u8) [*c]const u8;
pub extern fn igImParseFormatFindEnd(format: [*c]const u8) [*c]const u8;
pub extern fn igImParseFormatTrimDecorations(format: [*c]const u8, buf: [*c]u8, buf_size: usize) [*c]const u8;
pub extern fn igImParseFormatPrecision(format: [*c]const u8, default_value: c_int) c_int;
pub extern fn igImCharIsBlankA(c: u8) bool;
pub extern fn igImCharIsBlankW(c: c_uint) bool;
pub extern fn igImTextStrToUtf8(buf: [*c]u8, buf_size: c_int, in_text: [*c]const ImWchar, in_text_end: [*c]const ImWchar) c_int;
pub extern fn igImTextCharFromUtf8(out_char: [*c]c_uint, in_text: [*c]const u8, in_text_end: [*c]const u8) c_int;
pub extern fn igImTextStrFromUtf8(buf: [*c]ImWchar, buf_size: c_int, in_text: [*c]const u8, in_text_end: [*c]const u8, in_remaining: [*c][*c]const u8) c_int;
pub extern fn igImTextCountCharsFromUtf8(in_text: [*c]const u8, in_text_end: [*c]const u8) c_int;
pub extern fn igImTextCountUtf8BytesFromChar(in_text: [*c]const u8, in_text_end: [*c]const u8) c_int;
pub extern fn igImTextCountUtf8BytesFromStr(in_text: [*c]const ImWchar, in_text_end: [*c]const ImWchar) c_int;
pub extern fn igImFileOpen(filename: [*c]const u8, mode: [*c]const u8) ImFileHandle;
pub extern fn igImFileClose(file: ImFileHandle) bool;
pub extern fn igImFileGetSize(file: ImFileHandle) ImU64;
pub extern fn igImFileRead(data: ?*c_void, size: ImU64, count: ImU64, file: ImFileHandle) ImU64;
pub extern fn igImFileWrite(data: ?*const c_void, size: ImU64, count: ImU64, file: ImFileHandle) ImU64;
pub extern fn igImFileLoadToMemory(filename: [*c]const u8, mode: [*c]const u8, out_file_size: [*c]usize, padding_bytes: c_int) ?*c_void;
pub extern fn igImPowFloat(x: f32, y: f32) f32;
pub extern fn igImPowdouble(x: f64, y: f64) f64;
pub extern fn igImMin(pOut: [*c]ImVec2, lhs: ImVec2, rhs: ImVec2) void;
pub extern fn igImMax(pOut: [*c]ImVec2, lhs: ImVec2, rhs: ImVec2) void;
pub extern fn igImClamp(pOut: [*c]ImVec2, v: ImVec2, mn: ImVec2, mx: ImVec2) void;
pub extern fn igImLerpVec2Float(pOut: [*c]ImVec2, a: ImVec2, b: ImVec2, t: f32) void;
pub extern fn igImLerpVec2Vec2(pOut: [*c]ImVec2, a: ImVec2, b: ImVec2, t: ImVec2) void;
pub extern fn igImLerpVec4(pOut: [*c]ImVec4, a: ImVec4, b: ImVec4, t: f32) void;
pub extern fn igImSaturate(f: f32) f32;
pub extern fn igImLengthSqrVec2(lhs: ImVec2) f32;
pub extern fn igImLengthSqrVec4(lhs: ImVec4) f32;
pub extern fn igImInvLength(lhs: ImVec2, fail_value: f32) f32;
pub extern fn igImFloorFloat(f: f32) f32;
pub extern fn igImFloorVec2(pOut: [*c]ImVec2, v: ImVec2) void;
pub extern fn igImModPositive(a: c_int, b: c_int) c_int;
pub extern fn igImDot(a: ImVec2, b: ImVec2) f32;
pub extern fn igImRotate(pOut: [*c]ImVec2, v: ImVec2, cos_a: f32, sin_a: f32) void;
pub extern fn igImLinearSweep(current: f32, target: f32, speed: f32) f32;
pub extern fn igImMul(pOut: [*c]ImVec2, lhs: ImVec2, rhs: ImVec2) void;
pub extern fn igImBezierCalc(pOut: [*c]ImVec2, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, t: f32) void;
pub extern fn igImBezierClosestPoint(pOut: [*c]ImVec2, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, p: ImVec2, num_segments: c_int) void;
pub extern fn igImBezierClosestPointCasteljau(pOut: [*c]ImVec2, p1: ImVec2, p2: ImVec2, p3: ImVec2, p4: ImVec2, p: ImVec2, tess_tol: f32) void;
pub extern fn igImLineClosestPoint(pOut: [*c]ImVec2, a: ImVec2, b: ImVec2, p: ImVec2) void;
pub extern fn igImTriangleContainsPoint(a: ImVec2, b: ImVec2, c: ImVec2, p: ImVec2) bool;
pub extern fn igImTriangleClosestPoint(pOut: [*c]ImVec2, a: ImVec2, b: ImVec2, c: ImVec2, p: ImVec2) void;
pub extern fn igImTriangleBarycentricCoords(a: ImVec2, b: ImVec2, c: ImVec2, p: ImVec2, out_u: [*c]f32, out_v: [*c]f32, out_w: [*c]f32) void;
pub extern fn igImTriangleArea(a: ImVec2, b: ImVec2, c: ImVec2) f32;
pub extern fn igImGetDirQuadrantFromDelta(dx: f32, dy: f32) ImGuiDir;
pub extern fn ImVec1_ImVec1Nil() [*c]ImVec1;
pub extern fn ImVec1_destroy(self: [*c]ImVec1) void;
pub extern fn ImVec1_ImVec1Float(_x: f32) [*c]ImVec1;
pub extern fn ImVec2ih_ImVec2ihNil() [*c]ImVec2ih;
pub extern fn ImVec2ih_destroy(self: [*c]ImVec2ih) void;
pub extern fn ImVec2ih_ImVec2ihshort(_x: c_short, _y: c_short) [*c]ImVec2ih;
pub extern fn ImVec2ih_ImVec2ihVec2(rhs: ImVec2) [*c]ImVec2ih;
pub extern fn ImRect_ImRectNil() [*c]ImRect;
pub extern fn ImRect_destroy(self: [*c]ImRect) void;
pub extern fn ImRect_ImRectVec2(min: ImVec2, max: ImVec2) [*c]ImRect;
pub extern fn ImRect_ImRectVec4(v: ImVec4) [*c]ImRect;
pub extern fn ImRect_ImRectFloat(x1: f32, y1: f32, x2: f32, y2: f32) [*c]ImRect;
pub extern fn ImRect_GetCenter(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_GetSize(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_GetWidth(self: [*c]ImRect) f32;
pub extern fn ImRect_GetHeight(self: [*c]ImRect) f32;
pub extern fn ImRect_GetTL(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_GetTR(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_GetBL(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_GetBR(pOut: [*c]ImVec2, self: [*c]ImRect) void;
pub extern fn ImRect_ContainsVec2(self: [*c]ImRect, p: ImVec2) bool;
pub extern fn ImRect_ContainsRect(self: [*c]ImRect, r: ImRect) bool;
pub extern fn ImRect_Overlaps(self: [*c]ImRect, r: ImRect) bool;
pub extern fn ImRect_AddVec2(self: [*c]ImRect, p: ImVec2) void;
pub extern fn ImRect_AddRect(self: [*c]ImRect, r: ImRect) void;
pub extern fn ImRect_ExpandFloat(self: [*c]ImRect, amount: f32) void;
pub extern fn ImRect_ExpandVec2(self: [*c]ImRect, amount: ImVec2) void;
pub extern fn ImRect_Translate(self: [*c]ImRect, d: ImVec2) void;
pub extern fn ImRect_TranslateX(self: [*c]ImRect, dx: f32) void;
pub extern fn ImRect_TranslateY(self: [*c]ImRect, dy: f32) void;
pub extern fn ImRect_ClipWith(self: [*c]ImRect, r: ImRect) void;
pub extern fn ImRect_ClipWithFull(self: [*c]ImRect, r: ImRect) void;
pub extern fn ImRect_Floor(self: [*c]ImRect) void;
pub extern fn ImRect_IsInverted(self: [*c]ImRect) bool;
pub extern fn igImBitArrayTestBit(arr: [*c]const ImU32, n: c_int) bool;
pub extern fn igImBitArrayClearBit(arr: [*c]ImU32, n: c_int) void;
pub extern fn igImBitArraySetBit(arr: [*c]ImU32, n: c_int) void;
pub extern fn igImBitArraySetBitRange(arr: [*c]ImU32, n: c_int, n2: c_int) void;
pub extern fn ImBitVector_Create(self: [*c]ImBitVector, sz: c_int) void;
pub extern fn ImBitVector_Clear(self: [*c]ImBitVector) void;
pub extern fn ImBitVector_TestBit(self: [*c]ImBitVector, n: c_int) bool;
pub extern fn ImBitVector_SetBit(self: [*c]ImBitVector, n: c_int) void;
pub extern fn ImBitVector_ClearBit(self: [*c]ImBitVector, n: c_int) void;
pub extern fn ImDrawListSharedData_ImDrawListSharedData() [*c]ImDrawListSharedData;
pub extern fn ImDrawListSharedData_destroy(self: [*c]ImDrawListSharedData) void;
pub extern fn ImDrawListSharedData_SetCircleSegmentMaxError(self: [*c]ImDrawListSharedData, max_error: f32) void;
pub extern fn ImDrawDataBuilder_Clear(self: [*c]ImDrawDataBuilder) void;
pub extern fn ImDrawDataBuilder_ClearFreeMemory(self: [*c]ImDrawDataBuilder) void;
pub extern fn ImDrawDataBuilder_FlattenIntoSingleLayer(self: [*c]ImDrawDataBuilder) void;
pub extern fn ImGuiStyleMod_ImGuiStyleModInt(idx: ImGuiStyleVar, v: c_int) [*c]ImGuiStyleMod;
pub extern fn ImGuiStyleMod_destroy(self: [*c]ImGuiStyleMod) void;
pub extern fn ImGuiStyleMod_ImGuiStyleModFloat(idx: ImGuiStyleVar, v: f32) [*c]ImGuiStyleMod;
pub extern fn ImGuiStyleMod_ImGuiStyleModVec2(idx: ImGuiStyleVar, v: ImVec2) [*c]ImGuiStyleMod;
pub extern fn ImGuiMenuColumns_ImGuiMenuColumns() [*c]ImGuiMenuColumns;
pub extern fn ImGuiMenuColumns_destroy(self: [*c]ImGuiMenuColumns) void;
pub extern fn ImGuiMenuColumns_Update(self: [*c]ImGuiMenuColumns, count: c_int, spacing: f32, clear: bool) void;
pub extern fn ImGuiMenuColumns_DeclColumns(self: [*c]ImGuiMenuColumns, w0: f32, w1: f32, w2: f32) f32;
pub extern fn ImGuiMenuColumns_CalcExtraSpace(self: [*c]ImGuiMenuColumns, avail_w: f32) f32;
pub extern fn ImGuiInputTextState_ImGuiInputTextState() [*c]ImGuiInputTextState;
pub extern fn ImGuiInputTextState_destroy(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_ClearText(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_ClearFreeMemory(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_GetUndoAvailCount(self: [*c]ImGuiInputTextState) c_int;
pub extern fn ImGuiInputTextState_GetRedoAvailCount(self: [*c]ImGuiInputTextState) c_int;
pub extern fn ImGuiInputTextState_OnKeyPressed(self: [*c]ImGuiInputTextState, key: c_int) void;
pub extern fn ImGuiInputTextState_CursorAnimReset(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_CursorClamp(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_HasSelection(self: [*c]ImGuiInputTextState) bool;
pub extern fn ImGuiInputTextState_ClearSelection(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiInputTextState_SelectAll(self: [*c]ImGuiInputTextState) void;
pub extern fn ImGuiPopupData_ImGuiPopupData() [*c]ImGuiPopupData;
pub extern fn ImGuiPopupData_destroy(self: [*c]ImGuiPopupData) void;
pub extern fn ImGuiNavMoveResult_ImGuiNavMoveResult() [*c]ImGuiNavMoveResult;
pub extern fn ImGuiNavMoveResult_destroy(self: [*c]ImGuiNavMoveResult) void;
pub extern fn ImGuiNavMoveResult_Clear(self: [*c]ImGuiNavMoveResult) void;
pub extern fn ImGuiNextWindowData_ImGuiNextWindowData() [*c]ImGuiNextWindowData;
pub extern fn ImGuiNextWindowData_destroy(self: [*c]ImGuiNextWindowData) void;
pub extern fn ImGuiNextWindowData_ClearFlags(self: [*c]ImGuiNextWindowData) void;
pub extern fn ImGuiNextItemData_ImGuiNextItemData() [*c]ImGuiNextItemData;
pub extern fn ImGuiNextItemData_destroy(self: [*c]ImGuiNextItemData) void;
pub extern fn ImGuiNextItemData_ClearFlags(self: [*c]ImGuiNextItemData) void;
pub extern fn ImGuiPtrOrIndex_ImGuiPtrOrIndexPtr(ptr: ?*c_void) [*c]ImGuiPtrOrIndex;
pub extern fn ImGuiPtrOrIndex_destroy(self: [*c]ImGuiPtrOrIndex) void;
pub extern fn ImGuiPtrOrIndex_ImGuiPtrOrIndexInt(index: c_int) [*c]ImGuiPtrOrIndex;
pub extern fn ImGuiColumnData_ImGuiColumnData() [*c]ImGuiColumnData;
pub extern fn ImGuiColumnData_destroy(self: [*c]ImGuiColumnData) void;
pub extern fn ImGuiColumns_ImGuiColumns() [*c]ImGuiColumns;
pub extern fn ImGuiColumns_destroy(self: [*c]ImGuiColumns) void;
pub extern fn ImGuiColumns_Clear(self: [*c]ImGuiColumns) void;
pub extern fn ImGuiDockNode_ImGuiDockNode(id: ImGuiID) ?*ImGuiDockNode;
pub extern fn ImGuiDockNode_destroy(self: ?*ImGuiDockNode) void;
pub extern fn ImGuiDockNode_IsRootNode(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsDockSpace(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsFloatingNode(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsCentralNode(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsHiddenTabBar(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsNoTabBar(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsSplitNode(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsLeafNode(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_IsEmpty(self: ?*ImGuiDockNode) bool;
pub extern fn ImGuiDockNode_GetMergedFlags(self: ?*ImGuiDockNode) ImGuiDockNodeFlags;
pub extern fn ImGuiDockNode_Rect(pOut: [*c]ImRect, self: ?*ImGuiDockNode) void;
pub extern fn ImGuiDockContext_ImGuiDockContext() [*c]ImGuiDockContext;
pub extern fn ImGuiDockContext_destroy(self: [*c]ImGuiDockContext) void;
pub extern fn ImGuiViewportP_ImGuiViewportP() [*c]ImGuiViewportP;
pub extern fn ImGuiViewportP_destroy(self: [*c]ImGuiViewportP) void;
pub extern fn ImGuiViewportP_GetMainRect(pOut: [*c]ImRect, self: [*c]ImGuiViewportP) void;
pub extern fn ImGuiViewportP_GetWorkRect(pOut: [*c]ImRect, self: [*c]ImGuiViewportP) void;
pub extern fn ImGuiViewportP_ClearRequestFlags(self: [*c]ImGuiViewportP) void;
pub extern fn ImGuiWindowSettings_ImGuiWindowSettings() [*c]ImGuiWindowSettings;
pub extern fn ImGuiWindowSettings_destroy(self: [*c]ImGuiWindowSettings) void;
pub extern fn ImGuiWindowSettings_GetName(self: [*c]ImGuiWindowSettings) [*c]u8;
pub extern fn ImGuiSettingsHandler_ImGuiSettingsHandler() *ImGuiSettingsHandler;
pub extern fn ImGuiSettingsHandler_destroy(self: *ImGuiSettingsHandler) void;
pub extern fn ImGuiContext_ImGuiContext(shared_font_atlas: [*c]ImFontAtlas) [*c]ImGuiContext;
pub extern fn ImGuiContext_destroy(self: [*c]ImGuiContext) void;
pub extern fn ImGuiWindowTempData_ImGuiWindowTempData() [*c]ImGuiWindowTempData;
pub extern fn ImGuiWindowTempData_destroy(self: [*c]ImGuiWindowTempData) void;
pub extern fn ImGuiWindow_ImGuiWindow(context: [*c]ImGuiContext, name: [*c]const u8) ?*ImGuiWindow;
pub extern fn ImGuiWindow_destroy(self: ?*ImGuiWindow) void;
pub extern fn ImGuiWindow_GetIDStr(self: ?*ImGuiWindow, str: [*c]const u8, str_end: [*c]const u8) ImGuiID;
pub extern fn ImGuiWindow_GetIDPtr(self: ?*ImGuiWindow, ptr: ?*const c_void) ImGuiID;
pub extern fn ImGuiWindow_GetIDInt(self: ?*ImGuiWindow, n: c_int) ImGuiID;
pub extern fn ImGuiWindow_GetIDNoKeepAliveStr(self: ?*ImGuiWindow, str: [*c]const u8, str_end: [*c]const u8) ImGuiID;
pub extern fn ImGuiWindow_GetIDNoKeepAlivePtr(self: ?*ImGuiWindow, ptr: ?*const c_void) ImGuiID;
pub extern fn ImGuiWindow_GetIDNoKeepAliveInt(self: ?*ImGuiWindow, n: c_int) ImGuiID;
pub extern fn ImGuiWindow_GetIDFromRectangle(self: ?*ImGuiWindow, r_abs: ImRect) ImGuiID;
pub extern fn ImGuiWindow_Rect(pOut: [*c]ImRect, self: ?*ImGuiWindow) void;
pub extern fn ImGuiWindow_CalcFontSize(self: ?*ImGuiWindow) f32;
pub extern fn ImGuiWindow_TitleBarHeight(self: ?*ImGuiWindow) f32;
pub extern fn ImGuiWindow_TitleBarRect(pOut: [*c]ImRect, self: ?*ImGuiWindow) void;
pub extern fn ImGuiWindow_MenuBarHeight(self: ?*ImGuiWindow) f32;
pub extern fn ImGuiWindow_MenuBarRect(pOut: [*c]ImRect, self: ?*ImGuiWindow) void;
pub extern fn ImGuiItemHoveredDataBackup_ImGuiItemHoveredDataBackup() [*c]ImGuiItemHoveredDataBackup;
pub extern fn ImGuiItemHoveredDataBackup_destroy(self: [*c]ImGuiItemHoveredDataBackup) void;
pub extern fn ImGuiItemHoveredDataBackup_Backup(self: [*c]ImGuiItemHoveredDataBackup) void;
pub extern fn ImGuiItemHoveredDataBackup_Restore(self: [*c]ImGuiItemHoveredDataBackup) void;
pub extern fn ImGuiTabItem_ImGuiTabItem() [*c]ImGuiTabItem;
pub extern fn ImGuiTabItem_destroy(self: [*c]ImGuiTabItem) void;
pub extern fn ImGuiTabBar_ImGuiTabBar() [*c]ImGuiTabBar;
pub extern fn ImGuiTabBar_destroy(self: [*c]ImGuiTabBar) void;
pub extern fn ImGuiTabBar_GetTabOrder(self: [*c]ImGuiTabBar, tab: [*c]const ImGuiTabItem) c_int;
pub extern fn ImGuiTabBar_GetTabName(self: [*c]ImGuiTabBar, tab: [*c]const ImGuiTabItem) [*c]const u8;
pub extern fn igGetCurrentWindowRead() ?*ImGuiWindow;
pub extern fn igGetCurrentWindow() ?*ImGuiWindow;
pub extern fn igFindWindowByID(id: ImGuiID) ?*ImGuiWindow;
pub extern fn igFindWindowByName(name: [*c]const u8) ?*ImGuiWindow;
pub extern fn igUpdateWindowParentAndRootLinks(window: ?*ImGuiWindow, flags: ImGuiWindowFlags, parent_window: ?*ImGuiWindow) void;
pub extern fn igCalcWindowExpectedSize(pOut: [*c]ImVec2, window: ?*ImGuiWindow) void;
pub extern fn igIsWindowChildOf(window: ?*ImGuiWindow, potential_parent: ?*ImGuiWindow) bool;
pub extern fn igIsWindowNavFocusable(window: ?*ImGuiWindow) bool;
pub extern fn igGetWindowAllowedExtentRect(pOut: [*c]ImRect, window: ?*ImGuiWindow) void;
pub extern fn igSetWindowPosWindowPtr(window: ?*ImGuiWindow, pos: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowSizeWindowPtr(window: ?*ImGuiWindow, size: ImVec2, cond: ImGuiCond) void;
pub extern fn igSetWindowCollapsedWindowPtr(window: ?*ImGuiWindow, collapsed: bool, cond: ImGuiCond) void;
pub extern fn igSetWindowHitTestHole(window: ?*ImGuiWindow, pos: ImVec2, size: ImVec2) void;
pub extern fn igFocusWindow(window: ?*ImGuiWindow) void;
pub extern fn igFocusTopMostWindowUnderOne(under_this_window: ?*ImGuiWindow, ignore_window: ?*ImGuiWindow) void;
pub extern fn igBringWindowToFocusFront(window: ?*ImGuiWindow) void;
pub extern fn igBringWindowToDisplayFront(window: ?*ImGuiWindow) void;
pub extern fn igBringWindowToDisplayBack(window: ?*ImGuiWindow) void;
pub extern fn igSetCurrentFont(font: [*c]ImFont) void;
pub extern fn igGetDefaultFont() [*c]ImFont;
pub extern fn igGetForegroundDrawListWindowPtr(window: ?*ImGuiWindow) [*c]ImDrawList;
pub extern fn igInitialize(context: [*c]ImGuiContext) void;
pub extern fn igShutdown(context: [*c]ImGuiContext) void;
pub extern fn igUpdateHoveredWindowAndCaptureFlags() void;
pub extern fn igStartMouseMovingWindow(window: ?*ImGuiWindow) void;
pub extern fn igStartMouseMovingWindowOrNode(window: ?*ImGuiWindow, node: ?*ImGuiDockNode, undock_floating_node: bool) void;
pub extern fn igUpdateMouseMovingWindowNewFrame() void;
pub extern fn igUpdateMouseMovingWindowEndFrame() void;
pub extern fn igTranslateWindowsInViewport(viewport: [*c]ImGuiViewportP, old_pos: ImVec2, new_pos: ImVec2) void;
pub extern fn igScaleWindowsInViewport(viewport: [*c]ImGuiViewportP, scale: f32) void;
pub extern fn igDestroyPlatformWindow(viewport: [*c]ImGuiViewportP) void;
pub extern fn igShowViewportThumbnails() void;
pub extern fn igMarkIniSettingsDirtyNil() void;
pub extern fn igMarkIniSettingsDirtyWindowPtr(window: ?*ImGuiWindow) void;
pub extern fn igClearIniSettings() void;
pub extern fn igCreateNewWindowSettings(name: [*c]const u8) [*c]ImGuiWindowSettings;
pub extern fn igFindWindowSettings(id: ImGuiID) [*c]ImGuiWindowSettings;
pub extern fn igFindOrCreateWindowSettings(name: [*c]const u8) *ImGuiWindowSettings;
pub extern fn igFindSettingsHandler(type_name: [*c]const u8) *ImGuiSettingsHandler;
pub extern fn igSetNextWindowScroll(scroll: ImVec2) void;
pub extern fn igSetScrollXWindowPtr(window: ?*ImGuiWindow, new_scroll_x: f32) void;
pub extern fn igSetScrollYWindowPtr(window: ?*ImGuiWindow, new_scroll_y: f32) void;
pub extern fn igSetScrollFromPosXWindowPtr(window: ?*ImGuiWindow, local_x: f32, center_x_ratio: f32) void;
pub extern fn igSetScrollFromPosYWindowPtr(window: ?*ImGuiWindow, local_y: f32, center_y_ratio: f32) void;
pub extern fn igScrollToBringRectIntoView(pOut: [*c]ImVec2, window: ?*ImGuiWindow, item_rect: ImRect) void;
pub extern fn igGetItemID() ImGuiID;
pub extern fn igGetItemStatusFlags() ImGuiItemStatusFlags;
pub extern fn igGetActiveID() ImGuiID;
pub extern fn igGetFocusID() ImGuiID;
pub extern fn igSetActiveID(id: ImGuiID, window: ?*ImGuiWindow) void;
pub extern fn igSetFocusID(id: ImGuiID, window: ?*ImGuiWindow) void;
pub extern fn igClearActiveID() void;
pub extern fn igGetHoveredID() ImGuiID;
pub extern fn igSetHoveredID(id: ImGuiID) void;
pub extern fn igKeepAliveID(id: ImGuiID) void;
pub extern fn igMarkItemEdited(id: ImGuiID) void;
pub extern fn igPushOverrideID(id: ImGuiID) void;
pub extern fn igItemSizeVec2(size: ImVec2, text_baseline_y: f32) void;
pub extern fn igItemSizeRect(bb: ImRect, text_baseline_y: f32) void;
pub extern fn igItemAdd(bb: ImRect, id: ImGuiID, nav_bb: [*c]const ImRect) bool;
pub extern fn igItemHoverable(bb: ImRect, id: ImGuiID) bool;
pub extern fn igIsClippedEx(bb: ImRect, id: ImGuiID, clip_even_when_logged: bool) bool;
pub extern fn igFocusableItemRegister(window: ?*ImGuiWindow, id: ImGuiID) bool;
pub extern fn igFocusableItemUnregister(window: ?*ImGuiWindow) void;
pub extern fn igCalcItemSize(pOut: [*c]ImVec2, size: ImVec2, default_w: f32, default_h: f32) void;
pub extern fn igCalcWrapWidthForPos(pos: ImVec2, wrap_pos_x: f32) f32;
pub extern fn igPushMultiItemsWidths(components: c_int, width_full: f32) void;
pub extern fn igPushItemFlag(option: ImGuiItemFlags, enabled: bool) void;
pub extern fn igPopItemFlag() void;
pub extern fn igIsItemToggledSelection() bool;
pub extern fn igGetContentRegionMaxAbs(pOut: [*c]ImVec2) void;
pub extern fn igShrinkWidths(items: [*c]ImGuiShrinkWidthItem, count: c_int, width_excess: f32) void;
pub extern fn igLogBegin(type: ImGuiLogType, auto_open_depth: c_int) void;
pub extern fn igLogToBuffer(auto_open_depth: c_int) void;
pub extern fn igBeginChildEx(name: [*c]const u8, id: ImGuiID, size_arg: ImVec2, border: bool, flags: ImGuiWindowFlags) bool;
pub extern fn igOpenPopupEx(id: ImGuiID) void;
pub extern fn igClosePopupToLevel(remaining: c_int, restore_focus_to_window_under_popup: bool) void;
pub extern fn igClosePopupsOverWindow(ref_window: ?*ImGuiWindow, restore_focus_to_window_under_popup: bool) void;
pub extern fn igIsPopupOpenID(id: ImGuiID) bool;
pub extern fn igBeginPopupEx(id: ImGuiID, extra_flags: ImGuiWindowFlags) bool;
pub extern fn igBeginTooltipEx(extra_flags: ImGuiWindowFlags, tooltip_flags: ImGuiTooltipFlags) void;
pub extern fn igGetTopMostPopupModal() ?*ImGuiWindow;
pub extern fn igFindBestWindowPosForPopup(pOut: [*c]ImVec2, window: ?*ImGuiWindow) void;
pub extern fn igFindBestWindowPosForPopupEx(pOut: [*c]ImVec2, ref_pos: ImVec2, size: ImVec2, last_dir: [*c]ImGuiDir, r_outer: ImRect, r_avoid: ImRect, policy: ImGuiPopupPositionPolicy) void;
pub extern fn igNavInitWindow(window: ?*ImGuiWindow, force_reinit: bool) void;
pub extern fn igNavMoveRequestButNoResultYet() bool;
pub extern fn igNavMoveRequestCancel() void;
pub extern fn igNavMoveRequestForward(move_dir: ImGuiDir, clip_dir: ImGuiDir, bb_rel: ImRect, move_flags: ImGuiNavMoveFlags) void;
pub extern fn igNavMoveRequestTryWrapping(window: ?*ImGuiWindow, move_flags: ImGuiNavMoveFlags) void;
pub extern fn igGetNavInputAmount(n: ImGuiNavInput, mode: ImGuiInputReadMode) f32;
pub extern fn igGetNavInputAmount2d(pOut: [*c]ImVec2, dir_sources: ImGuiNavDirSourceFlags, mode: ImGuiInputReadMode, slow_factor: f32, fast_factor: f32) void;
pub extern fn igCalcTypematicRepeatAmount(t0: f32, t1: f32, repeat_delay: f32, repeat_rate: f32) c_int;
pub extern fn igActivateItem(id: ImGuiID) void;
pub extern fn igSetNavID(id: ImGuiID, nav_layer: c_int, focus_scope_id: ImGuiID) void;
pub extern fn igSetNavIDWithRectRel(id: ImGuiID, nav_layer: c_int, focus_scope_id: ImGuiID, rect_rel: ImRect) void;
pub extern fn igPushFocusScope(id: ImGuiID) void;
pub extern fn igPopFocusScope() void;
pub extern fn igGetFocusScopeID() ImGuiID;
pub extern fn igIsActiveIdUsingNavDir(dir: ImGuiDir) bool;
pub extern fn igIsActiveIdUsingNavInput(input: ImGuiNavInput) bool;
pub extern fn igIsActiveIdUsingKey(key: ImGuiKey) bool;
pub extern fn igIsMouseDragPastThreshold(button: ImGuiMouseButton, lock_threshold: f32) bool;
pub extern fn igIsKeyPressedMap(key: ImGuiKey, repeat: bool) bool;
pub extern fn igIsNavInputDown(n: ImGuiNavInput) bool;
pub extern fn igIsNavInputTest(n: ImGuiNavInput, rm: ImGuiInputReadMode) bool;
pub extern fn igGetMergedKeyModFlags() ImGuiKeyModFlags;
pub extern fn igDockContextInitialize(ctx: [*c]ImGuiContext) void;
pub extern fn igDockContextShutdown(ctx: [*c]ImGuiContext) void;
pub extern fn igDockContextClearNodes(ctx: [*c]ImGuiContext, root_id: ImGuiID, clear_settings_refs: bool) void;
pub extern fn igDockContextRebuildNodes(ctx: [*c]ImGuiContext) void;
pub extern fn igDockContextUpdateUndocking(ctx: [*c]ImGuiContext) void;
pub extern fn igDockContextUpdateDocking(ctx: [*c]ImGuiContext) void;
pub extern fn igDockContextGenNodeID(ctx: [*c]ImGuiContext) ImGuiID;
pub extern fn igDockContextQueueDock(ctx: [*c]ImGuiContext, target: ?*ImGuiWindow, target_node: ?*ImGuiDockNode, payload: ?*ImGuiWindow, split_dir: ImGuiDir, split_ratio: f32, split_outer: bool) void;
pub extern fn igDockContextQueueUndockWindow(ctx: [*c]ImGuiContext, window: ?*ImGuiWindow) void;
pub extern fn igDockContextQueueUndockNode(ctx: [*c]ImGuiContext, node: ?*ImGuiDockNode) void;
pub extern fn igDockContextCalcDropPosForDocking(target: ?*ImGuiWindow, target_node: ?*ImGuiDockNode, payload: ?*ImGuiWindow, split_dir: ImGuiDir, split_outer: bool, out_pos: [*c]ImVec2) bool;
pub extern fn igDockNodeGetRootNode(node: ?*ImGuiDockNode) ?*ImGuiDockNode;
pub extern fn igDockNodeGetDepth(node: ?*const ImGuiDockNode) c_int;
pub extern fn igGetWindowDockNode() ?*ImGuiDockNode;
pub extern fn igGetWindowAlwaysWantOwnTabBar(window: ?*ImGuiWindow) bool;
pub extern fn igBeginDocked(window: ?*ImGuiWindow, p_open: [*c]bool) void;
pub extern fn igBeginDockableDragDropSource(window: ?*ImGuiWindow) void;
pub extern fn igBeginDockableDragDropTarget(window: ?*ImGuiWindow) void;
pub extern fn igSetWindowDock(window: ?*ImGuiWindow, dock_id: ImGuiID, cond: ImGuiCond) void;
pub extern fn igDockBuilderDockWindow(window_name: [*c]const u8, node_id: ImGuiID) void;
pub extern fn igDockBuilderGetNode(node_id: ImGuiID) ?*ImGuiDockNode;
pub extern fn igDockBuilderGetCentralNode(node_id: ImGuiID) ?*ImGuiDockNode;
pub extern fn igDockBuilderAddNode(node_id: ImGuiID, flags: ImGuiDockNodeFlags) ImGuiID;
pub extern fn igDockBuilderRemoveNode(node_id: ImGuiID) void;
pub extern fn igDockBuilderRemoveNodeDockedWindows(node_id: ImGuiID, clear_settings_refs: bool) void;
pub extern fn igDockBuilderRemoveNodeChildNodes(node_id: ImGuiID) void;
pub extern fn igDockBuilderSetNodePos(node_id: ImGuiID, pos: ImVec2) void;
pub extern fn igDockBuilderSetNodeSize(node_id: ImGuiID, size: ImVec2) void;
pub extern fn igDockBuilderSplitNode(node_id: ImGuiID, split_dir: ImGuiDir, size_ratio_for_node_at_dir: f32, out_id_at_dir: [*c]ImGuiID, out_id_at_opposite_dir: [*c]ImGuiID) ImGuiID;
pub extern fn igDockBuilderCopyDockSpace(src_dockspace_id: ImGuiID, dst_dockspace_id: ImGuiID, in_window_remap_pairs: [*c]ImVector_const_charPtr) void;
pub extern fn igDockBuilderCopyNode(src_node_id: ImGuiID, dst_node_id: ImGuiID, out_node_remap_pairs: [*c]ImVector_ImGuiID) void;
pub extern fn igDockBuilderCopyWindowSettings(src_name: [*c]const u8, dst_name: [*c]const u8) void;
pub extern fn igDockBuilderFinish(node_id: ImGuiID) void;
pub extern fn igBeginDragDropTargetCustom(bb: ImRect, id: ImGuiID) bool;
pub extern fn igClearDragDrop() void;
pub extern fn igIsDragDropPayloadBeingAccepted() bool;
pub extern fn igBeginColumns(str_id: [*c]const u8, count: c_int, flags: ImGuiColumnsFlags) void;
pub extern fn igEndColumns() void;
pub extern fn igPushColumnClipRect(column_index: c_int) void;
pub extern fn igPushColumnsBackground() void;
pub extern fn igPopColumnsBackground() void;
pub extern fn igGetColumnsID(str_id: [*c]const u8, count: c_int) ImGuiID;
pub extern fn igFindOrCreateColumns(window: ?*ImGuiWindow, id: ImGuiID) [*c]ImGuiColumns;
pub extern fn igGetColumnOffsetFromNorm(columns: [*c]const ImGuiColumns, offset_norm: f32) f32;
pub extern fn igGetColumnNormFromOffset(columns: [*c]const ImGuiColumns, offset: f32) f32;
pub extern fn igBeginTabBarEx(tab_bar: [*c]ImGuiTabBar, bb: ImRect, flags: ImGuiTabBarFlags, dock_node: ?*ImGuiDockNode) bool;
pub extern fn igTabBarFindTabByID(tab_bar: [*c]ImGuiTabBar, tab_id: ImGuiID) [*c]ImGuiTabItem;
pub extern fn igTabBarFindMostRecentlySelectedTabForActiveWindow(tab_bar: [*c]ImGuiTabBar) [*c]ImGuiTabItem;
pub extern fn igTabBarAddTab(tab_bar: [*c]ImGuiTabBar, tab_flags: ImGuiTabItemFlags, window: ?*ImGuiWindow) void;
pub extern fn igTabBarRemoveTab(tab_bar: [*c]ImGuiTabBar, tab_id: ImGuiID) void;
pub extern fn igTabBarCloseTab(tab_bar: [*c]ImGuiTabBar, tab: [*c]ImGuiTabItem) void;
pub extern fn igTabBarQueueChangeTabOrder(tab_bar: [*c]ImGuiTabBar, tab: [*c]const ImGuiTabItem, dir: c_int) void;
pub extern fn igTabItemEx(tab_bar: [*c]ImGuiTabBar, label: [*c]const u8, p_open: [*c]bool, flags: ImGuiTabItemFlags, docked_window: ?*ImGuiWindow) bool;
pub extern fn igTabItemCalcSize(pOut: [*c]ImVec2, label: [*c]const u8, has_close_button: bool) void;
pub extern fn igTabItemBackground(draw_list: [*c]ImDrawList, bb: ImRect, flags: ImGuiTabItemFlags, col: ImU32) void;
pub extern fn igTabItemLabelAndCloseButton(draw_list: [*c]ImDrawList, bb: ImRect, flags: ImGuiTabItemFlags, frame_padding: ImVec2, label: [*c]const u8, tab_id: ImGuiID, close_button_id: ImGuiID, is_contents_visible: bool) bool;
pub extern fn igRenderText(pos: ImVec2, text: [*c]const u8, text_end: [*c]const u8, hide_text_after_hash: bool) void;
pub extern fn igRenderTextWrapped(pos: ImVec2, text: [*c]const u8, text_end: [*c]const u8, wrap_width: f32) void;
pub extern fn igRenderTextClipped(pos_min: ImVec2, pos_max: ImVec2, text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: [*c]const ImVec2, @"align": ImVec2, clip_rect: [*c]const ImRect) void;
pub extern fn igRenderTextClippedEx(draw_list: [*c]ImDrawList, pos_min: ImVec2, pos_max: ImVec2, text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: [*c]const ImVec2, @"align": ImVec2, clip_rect: [*c]const ImRect) void;
pub extern fn igRenderTextEllipsis(draw_list: [*c]ImDrawList, pos_min: ImVec2, pos_max: ImVec2, clip_max_x: f32, ellipsis_max_x: f32, text: [*c]const u8, text_end: [*c]const u8, text_size_if_known: [*c]const ImVec2) void;
pub extern fn igRenderFrame(p_min: ImVec2, p_max: ImVec2, fill_col: ImU32, border: bool, rounding: f32) void;
pub extern fn igRenderFrameBorder(p_min: ImVec2, p_max: ImVec2, rounding: f32) void;
pub extern fn igRenderColorRectWithAlphaCheckerboard(draw_list: [*c]ImDrawList, p_min: ImVec2, p_max: ImVec2, fill_col: ImU32, grid_step: f32, grid_off: ImVec2, rounding: f32, rounding_corners_flags: c_int) void;
pub extern fn igRenderNavHighlight(bb: ImRect, id: ImGuiID, flags: ImGuiNavHighlightFlags) void;
pub extern fn igFindRenderedTextEnd(text: [*c]const u8, text_end: [*c]const u8) [*c]const u8;
pub extern fn igLogRenderedText(ref_pos: [*c]const ImVec2, text: [*c]const u8, text_end: [*c]const u8) void;
pub extern fn igRenderArrow(draw_list: [*c]ImDrawList, pos: ImVec2, col: ImU32, dir: ImGuiDir, scale: f32) void;
pub extern fn igRenderBullet(draw_list: [*c]ImDrawList, pos: ImVec2, col: ImU32) void;
pub extern fn igRenderCheckMark(draw_list: [*c]ImDrawList, pos: ImVec2, col: ImU32, sz: f32) void;
pub extern fn igRenderMouseCursor(draw_list: [*c]ImDrawList, pos: ImVec2, scale: f32, mouse_cursor: ImGuiMouseCursor, col_fill: ImU32, col_border: ImU32, col_shadow: ImU32) void;
pub extern fn igRenderArrowPointingAt(draw_list: [*c]ImDrawList, pos: ImVec2, half_sz: ImVec2, direction: ImGuiDir, col: ImU32) void;
pub extern fn igRenderArrowDockMenu(draw_list: [*c]ImDrawList, p_min: ImVec2, sz: f32, col: ImU32) void;
pub extern fn igRenderRectFilledRangeH(draw_list: [*c]ImDrawList, rect: ImRect, col: ImU32, x_start_norm: f32, x_end_norm: f32, rounding: f32) void;
pub extern fn igRenderRectFilledWithHole(draw_list: [*c]ImDrawList, outer: ImRect, inner: ImRect, col: ImU32, rounding: f32) void;
pub extern fn igTextEx(text: [*c]const u8, text_end: [*c]const u8, flags: ImGuiTextFlags) void;
pub extern fn igButtonEx(label: [*c]const u8, size_arg: ImVec2, flags: ImGuiButtonFlags) bool;
pub extern fn igCloseButton(id: ImGuiID, pos: ImVec2) bool;
pub extern fn igCollapseButton(id: ImGuiID, pos: ImVec2, dock_node: ?*ImGuiDockNode) bool;
pub extern fn igArrowButtonEx(str_id: [*c]const u8, dir: ImGuiDir, size_arg: ImVec2, flags: ImGuiButtonFlags) bool;
pub extern fn igScrollbar(axis: ImGuiAxis) void;
pub extern fn igScrollbarEx(bb: ImRect, id: ImGuiID, axis: ImGuiAxis, p_scroll_v: [*c]f32, avail_v: f32, contents_v: f32, rounding_corners: ImDrawCornerFlags) bool;
pub extern fn igGetWindowScrollbarRect(pOut: [*c]ImRect, window: ?*ImGuiWindow, axis: ImGuiAxis) void;
pub extern fn igGetWindowScrollbarID(window: ?*ImGuiWindow, axis: ImGuiAxis) ImGuiID;
pub extern fn igGetWindowResizeID(window: ?*ImGuiWindow, n: c_int) ImGuiID;
pub extern fn igSeparatorEx(flags: ImGuiSeparatorFlags) void;
pub extern fn igButtonBehavior(bb: ImRect, id: ImGuiID, out_hovered: [*c]bool, out_held: [*c]bool, flags: ImGuiButtonFlags) bool;
pub extern fn igDragBehavior(id: ImGuiID, data_type: ImGuiDataType, p_v: ?*c_void, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32, flags: ImGuiDragFlags) bool;
pub extern fn igSliderBehavior(bb: ImRect, id: ImGuiID, data_type: ImGuiDataType, p_v: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: [*c]const u8, power: f32, flags: ImGuiSliderFlags, out_grab_bb: [*c]ImRect) bool;
pub extern fn igSplitterBehavior(bb: ImRect, id: ImGuiID, axis: ImGuiAxis, size1: [*c]f32, size2: [*c]f32, min_size1: f32, min_size2: f32, hover_extend: f32, hover_visibility_delay: f32) bool;
pub extern fn igTreeNodeBehavior(id: ImGuiID, flags: ImGuiTreeNodeFlags, label: [*c]const u8, label_end: [*c]const u8) bool;
pub extern fn igTreeNodeBehaviorIsOpen(id: ImGuiID, flags: ImGuiTreeNodeFlags) bool;
pub extern fn igTreePushOverrideID(id: ImGuiID) void;
pub extern fn igDataTypeGetInfo(data_type: ImGuiDataType) [*c]const ImGuiDataTypeInfo;
pub extern fn igDataTypeFormatString(buf: [*c]u8, buf_size: c_int, data_type: ImGuiDataType, p_data: ?*const c_void, format: [*c]const u8) c_int;
pub extern fn igDataTypeApplyOp(data_type: ImGuiDataType, op: c_int, output: ?*c_void, arg_1: ?*c_void, arg_2: ?*const c_void) void;
pub extern fn igDataTypeApplyOpFromText(buf: [*c]const u8, initial_value_buf: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, format: [*c]const u8) bool;
pub extern fn igDataTypeClamp(data_type: ImGuiDataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void) bool;
pub extern fn igInputTextEx(label: [*c]const u8, hint: [*c]const u8, buf: [*c]u8, buf_size: c_int, size_arg: ImVec2, flags: ImGuiInputTextFlags, callback: ImGuiInputTextCallback, user_data: ?*c_void) bool;
pub extern fn igTempInputText(bb: ImRect, id: ImGuiID, label: [*c]const u8, buf: [*c]u8, buf_size: c_int, flags: ImGuiInputTextFlags) bool;
pub extern fn igTempInputScalar(bb: ImRect, id: ImGuiID, label: [*c]const u8, data_type: ImGuiDataType, p_data: ?*c_void, format: [*c]const u8, p_clamp_min: ?*const c_void, p_clamp_max: ?*const c_void) bool;
pub extern fn igTempInputIsActive(id: ImGuiID) bool;
pub extern fn igGetInputTextState(id: ImGuiID) [*c]ImGuiInputTextState;
pub extern fn igColorTooltip(text: [*c]const u8, col: [*c]const f32, flags: ImGuiColorEditFlags) void;
pub extern fn igColorEditOptionsPopup(col: [*c]const f32, flags: ImGuiColorEditFlags) void;
pub extern fn igColorPickerOptionsPopup(ref_col: [*c]const f32, flags: ImGuiColorEditFlags) void;
pub extern fn igPlotEx(plot_type: ImGuiPlotType, label: [*c]const u8, values_getter: ?fn (?*c_void, c_int) callconv(.C) f32, data: ?*c_void, values_count: c_int, values_offset: c_int, overlay_text: [*c]const u8, scale_min: f32, scale_max: f32, frame_size: ImVec2) c_int;
pub extern fn igShadeVertsLinearColorGradientKeepAlpha(draw_list: [*c]ImDrawList, vert_start_idx: c_int, vert_end_idx: c_int, gradient_p0: ImVec2, gradient_p1: ImVec2, col0: ImU32, col1: ImU32) void;
pub extern fn igShadeVertsLinearUV(draw_list: [*c]ImDrawList, vert_start_idx: c_int, vert_end_idx: c_int, a: ImVec2, b: ImVec2, uv_a: ImVec2, uv_b: ImVec2, clamp: bool) void;
pub extern fn igGcCompactTransientWindowBuffers(window: ?*ImGuiWindow) void;
pub extern fn igGcAwakeTransientWindowBuffers(window: ?*ImGuiWindow) void;
pub extern fn igDebugDrawItemRect(col: ImU32) void;
pub extern fn igDebugStartItemPicker() void;
pub extern fn igImFontAtlasBuildWithStbTruetype(atlas: [*c]ImFontAtlas) bool;
pub extern fn igImFontAtlasBuildInit(atlas: [*c]ImFontAtlas) void;
pub extern fn igImFontAtlasBuildSetupFont(atlas: [*c]ImFontAtlas, font: [*c]ImFont, font_config: [*c]ImFontConfig, ascent: f32, descent: f32) void;
pub extern fn igImFontAtlasBuildPackCustomRects(atlas: [*c]ImFontAtlas, stbrp_context_opaque: ?*c_void) void;
pub extern fn igImFontAtlasBuildFinish(atlas: [*c]ImFontAtlas) void;
pub extern fn igImFontAtlasBuildMultiplyCalcLookupTable(out_table: [*c]u8, in_multiply_factor: f32) void;
pub extern fn igImFontAtlasBuildMultiplyRectAlpha8(table: [*c]const u8, pixels: [*c]u8, x: c_int, y: c_int, w: c_int, h: c_int, stride: c_int) void;
pub extern fn igLogText(fmt: [*c]const u8, ...) void;
pub extern fn ImGuiTextBuffer_appendf(buffer: [*c]struct_ImGuiTextBuffer, fmt: [*c]const u8, ...) void;
pub extern fn igGET_FLT_MAX(...) f32;
pub extern fn ImVector_ImWchar_create(...) [*c]ImVector_ImWchar;
pub extern fn ImVector_ImWchar_destroy(self: [*c]ImVector_ImWchar) void;
pub extern fn ImVector_ImWchar_Init(p: [*c]ImVector_ImWchar) void;
pub extern fn ImVector_ImWchar_UnInit(p: [*c]ImVector_ImWchar) void; | src/deps/imgui/imgui.zig |
const std = @import("std");
const tls = @import("tls.zig");
const enums = @import("enums.zig");
const structs = @import("structs.zig");
pub fn printRecord(record: structs.Record, note: []const u8) anyerror!void {
std.debug.print("\n===> {s}\n", .{note});
std.debug.print("Type is {}\n", .{record.type});
std.debug.print("Version is {}\n", .{record.version});
switch (record.type) {
.handshake => {
const handshake_type = @intToEnum(enums.HandshakeType, record.data[0]);
std.debug.print("Handshake type is {}\n", .{handshake_type});
const size = @intCast(u64, record.data[1]) << 16 | @intCast(u64, record.data[2]) << 8 | @intCast(u64, record.data[3]);
std.debug.print("Handshake size is {} bytes\n", .{size});
var reading: usize = 4;
switch (handshake_type) {
.client_hello => {
const version = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
reading += 2;
std.debug.print("Protocol version is {}\n", .{@intToEnum(enums.Version, version)});
std.debug.print("Client random is 0x", .{});
for (record.data[reading .. reading + 32]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += 32;
std.debug.print("\nSession ID is ", .{});
if (record.data[reading] == 0) {
std.debug.print("not provided", .{});
reading += 1;
} else {
std.debug.print("0x", .{});
for (record.data[reading + 1 .. reading + 1 + record.data[reading]]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += 1 + record.data[reading];
}
const ciphersuites_n = (@intCast(u16, record.data[reading]) << 8 | record.data[reading + 1]) >> 1;
std.debug.print("\nProposed {d} ciphersuites:\n", .{ciphersuites_n});
reading += 2;
// FIXME this function reverses byteorder of u16 to littleEndian, it should not
var ciphersuites = std.mem.bytesAsSlice(u16, record.data[reading .. reading + ciphersuites_n * 2]);
for (ciphersuites) |word| {
std.debug.print("{}\n", .{@intToEnum(enums.CipherSuite, ((0x00ff & word) << 8) | ((0xff00 & word) >> 8))});
}
reading += ciphersuites_n * 2;
// TODO add compressions enum
const compression_n = record.data[reading];
std.debug.print("Proposed {d} compression algorithms:\n", .{compression_n});
reading += 1;
for (record.data[reading .. reading + compression_n]) |byte| {
std.debug.print("0x{X:0>2}\n", .{byte});
}
reading += compression_n;
if (reading == record.data.len) {
std.debug.print("Extensions are not provided\n", .{});
} else {
const extensions_size = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
std.debug.print("Extensions size is {d} bytes\n", .{extensions_size});
reading += 2;
while (true) {
const extension = @intToEnum(enums.ExtensionType, @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]));
reading += 2;
const extensionsize = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
reading += 2;
// TODO implement something to show extension info
std.debug.print("Extension: {}, size is {d} bytes: ", .{ extension, extensionsize });
for (record.data[reading .. reading + extensionsize]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
std.debug.print("\n", .{});
reading += extensionsize;
if (reading == record.data.len) break;
}
}
},
.server_hello => {
const version = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
reading += 2;
std.debug.print("Protocol version is {}\n", .{@intToEnum(enums.Version, version)});
std.debug.print("Server random is 0x", .{});
for (record.data[reading .. reading + 32]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += 32;
std.debug.print("\nSession ID is ", .{});
if (record.data[reading] == 0) {
std.debug.print("not provided", .{});
reading += 1;
} else {
std.debug.print("0x", .{});
for (record.data[reading + 1 .. reading + 1 + record.data[reading]]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += 1 + record.data[reading];
}
const ciphersuite = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
std.debug.print("\nSelected ciphersuite is {}\n", .{@intToEnum(enums.CipherSuite, ciphersuite)});
reading += 2;
// TODO add compressions enum
std.debug.print("Selected compression method is 0x{X:0>2}\n", .{record.data[reading]});
reading += 1;
if (reading == record.data.len) {
std.debug.print("Extensions are not provided\n", .{});
} else {
const extensions_size = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
std.debug.print("Extensions size is {d} bytes\n", .{extensions_size});
reading += 2;
while (true) {
const extension = @intToEnum(enums.ExtensionType, @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]));
reading += 2;
const extensionsize = @intCast(u16, record.data[reading]) << 8 | @intCast(u16, record.data[reading + 1]);
reading += 2;
// TODO implement something to show extension info
std.debug.print("Extension: {}, size is {d} bytes: ", .{ extension, extensionsize });
for (record.data[reading .. reading + extensionsize]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
std.debug.print("\n", .{});
reading += extensionsize;
if (reading == record.data.len) break;
}
}
},
.certificate => {
const combined_size: u64 = @intCast(u64, record.data[reading]) << 16 | @intCast(u64, record.data[reading + 1]) << 8 | record.data[reading + 2];
std.debug.print("All certificates with size headers is {d} bytes\n", .{combined_size});
reading += 3;
var certificate_n: usize = 0;
while (true) {
certificate_n += 1;
const cert_size: u64 = @intCast(u64, record.data[reading]) << 16 | @intCast(u64, record.data[reading + 1]) << 8 | record.data[reading + 2];
std.debug.print("Certificate #{d} is {d} bytes long\n", .{ certificate_n, cert_size });
reading += 3 + cert_size;
if (reading == record.data.len) break;
}
},
.server_key_exchange => {
const curve_type = @intToEnum(enums.ECCurveType, record.data[reading]);
std.debug.print("Curve type is {}\n", .{curve_type});
reading += 1;
const curve = @intToEnum(enums.EllipticCurve, @intCast(u16, record.data[reading]) << 8 | record.data[reading + 1]);
std.debug.print("Selected curve is {}\n", .{curve});
reading += 2;
const keysize = record.data[reading];
std.debug.print("PublicKey size is {} bytes\n", .{keysize});
reading += 1;
// FIXME not sure if parsing this in a right way
var coord_size: usize = record.data[reading] * 8;
reading += 1;
std.debug.print("Public Key X: ", .{});
for (record.data[reading .. reading + coord_size]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += coord_size;
std.debug.print("\nPublic Key Y: ", .{});
for (record.data[reading .. reading + coord_size]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
reading += coord_size;
std.debug.print("\nHashing algorithm is {}\n", .{@intToEnum(enums.HashAlgorithm, record.data[reading])});
std.debug.print("Signature algorithm is {}\n", .{@intToEnum(enums.SignatureAlgorithm, record.data[reading + 1])});
reading += 2;
const signature_size = @intCast(u16, record.data[reading]) << 8 | record.data[reading + 1];
std.debug.print("Signature size is {d} bytes\n", .{signature_size});
reading += 2;
std.debug.print("Signature is 0x", .{});
for (record.data[reading .. reading + signature_size]) |byte| {
std.debug.print("{X:0>2}", .{byte});
}
std.debug.print("\n", .{});
},
.server_hello_done => {},
.certificate_status => {
std.debug.print("certificate_status debug info unimplemented\n", .{});
},
// TODO: implement certificate status info
else => return error.unsupported_handshake_type,
}
},
.alert => {
std.debug.print("Alert type is {}\n", .{@intToEnum(enums.AlertLevel, record.data[0])});
std.debug.print("Alert description: {}\n", .{@intToEnum(enums.AlertDescription, record.data[1])});
},
.change_cipher_spec => {},
.application_data => {},
.heartbeat => {},
else => return error.unsupported_record_type,
}
}
/// Prints slice as hex code to console with note about slice content
pub fn showMem(slice: []u8, note: []const u8) void {
std.log.debug("examining memory \"{s}\" ({d} bytes)", .{ note, slice.len });
var i: usize = 0;
while (i < slice.len) : (i += 1) {
if (i % 32 == 0) {
if (i != 0) std.debug.print("\n", .{});
std.debug.print("{X:0>16}:", .{@ptrToInt(&slice[i])});
}
std.debug.print(" {X:0>2}", .{slice[i]});
}
std.debug.print("\n", .{});
} | src/debug.zig |
const std = @import("std");
const mem = std.mem;
const io = std.io;
const os = std.os;
const assert = std.debug.assert;
const wayland = @import("wayland");
const wl = wayland.client.wl;
const zriver = wayland.client.zriver;
const flags = @import("flags");
const usage =
\\usage: riverctl [options] <command>
\\
\\ -h Print this help message and exit.
\\ -version Print the version number and exit.
\\
\\Complete documentation of the recognized commands may be found in
\\the riverctl(1) man page.
\\
;
const gpa = std.heap.c_allocator;
pub const Globals = struct {
control: ?*zriver.ControlV1 = null,
seat: ?*wl.Seat = null,
};
pub fn main() !void {
_main() catch |err| {
if (std.builtin.mode == .Debug)
return err;
switch (err) {
error.RiverControlNotAdvertised => fatal(
\\The Wayland server does not support river-control-unstable-v1.
\\Do your versions of river and riverctl match?
, .{}),
error.SeatNotAdverstised => fatal(
\\The Wayland server did not advertise any seat.
, .{}),
else => return err,
}
};
}
fn _main() !void {
// This line is here because of https://github.com/ziglang/zig/issues/7807
const argv: [][*:0]const u8 = os.argv;
const result = flags.parse(argv[1..], &[_]flags.Flag{
.{ .name = "-h", .kind = .boolean },
.{ .name = "-version", .kind = .boolean },
}) catch {
try io.getStdErr().writeAll(usage);
os.exit(1);
};
if (result.boolFlag("-h")) {
try io.getStdOut().writeAll(usage);
os.exit(0);
}
if (result.boolFlag("-version")) {
try io.getStdOut().writeAll(@import("build_options").version ++ "\n");
os.exit(0);
}
const display = try wl.Display.connect(null);
const registry = try display.getRegistry();
var globals = Globals{};
registry.setListener(*Globals, registryListener, &globals);
_ = try display.roundtrip();
const control = globals.control orelse return error.RiverControlNotAdvertised;
const seat = globals.seat orelse return error.SeatNotAdverstised;
for (result.args) |arg| control.addArgument(arg);
const callback = try control.runCommand(seat);
callback.setListener(?*c_void, callbackListener, null);
// Loop until our callback is called and we exit.
while (true) _ = try display.dispatch();
}
fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, globals: *Globals) void {
switch (event) {
.global => |global| {
if (std.cstr.cmp(global.interface, wl.Seat.getInterface().name) == 0) {
assert(globals.seat == null); // TODO: support multiple seats
globals.seat = registry.bind(global.name, wl.Seat, 1) catch @panic("out of memory");
} else if (std.cstr.cmp(global.interface, zriver.ControlV1.getInterface().name) == 0) {
globals.control = registry.bind(global.name, zriver.ControlV1, 1) catch @panic("out of memory");
}
},
.global_remove => {},
}
}
fn callbackListener(callback: *zriver.CommandCallbackV1, event: zriver.CommandCallbackV1.Event, _: ?*c_void) void {
switch (event) {
.success => |success| {
if (mem.len(success.output) > 0) {
const stdout = std.io.getStdOut().writer();
stdout.print("{s}\n", .{success.output}) catch @panic("failed to write to stdout");
}
os.exit(0);
},
.failure => |failure| {
// A small hack to provide usage text when river reports an unknown command.
if (std.cstr.cmp(failure.failure_message, "unknown command") == 0) {
std.log.err("unknown command", .{});
io.getStdErr().writeAll(usage) catch {};
os.exit(1);
}
fatal("{s}", .{failure.failure_message});
},
}
}
fn fatal(comptime format: []const u8, args: anytype) noreturn {
std.log.err(format, args);
std.os.exit(1);
} | source/river-0.1.0/riverctl/main.zig |
const std = @import("std");
const vk = @import("vk");
const glfw = @import("glfw");
const imgui = @import("imgui");
const render = @import("render.zig");
const impl_glfw = @import("imgui_impl_glfw.zig");
const impl_vulkan = @import("imgui_impl_vulkan.zig");
const assert = std.debug.assert;
const USE_VULKAN_DEBUG_REPORT = std.debug.runtime_safety and false;
const IMGUI_UNLIMITED_FRAME_RATE = false;
const deviceExtensions = [_]vk.CString{vk.KHR_SWAPCHAIN_EXTENSION_NAME};
// ----------------------- Backend state -------------------------
// @TODO: Move this into swapchain state
var g_MainWindowData = impl_vulkan.Window{};
var g_MinImageCount = @as(u32, 2);
var g_SwapChainRebuild = false;
var g_SwapChainResizeWidth = @as(u32, 0);
var g_SwapChainResizeHeight = @as(u32, 0);
var g_FrameIndex = @as(u32, 0);
var g_SemaphoreIndex = @as(u32, 0);
// All of these are set up by init()
pub var window: *glfw.GLFWwindow = undefined;
pub var vkAllocator: ?*vk.AllocationCallbacks = undefined;
pub var instance: vk.Instance = undefined;
pub var physicalDevice: vk.PhysicalDevice = undefined;
pub var device: vk.Device = undefined;
pub var queueFamily: u32 = undefined;
pub var queue: vk.Queue = undefined;
pub var debugReport: if (USE_VULKAN_DEBUG_REPORT) vk.DebugReportCallbackEXT else void = undefined;
pub var pipelineCache: ?vk.PipelineCache = undefined;
pub var descriptorPool: vk.DescriptorPool = undefined;
pub var surface: vk.SurfaceKHR = undefined;
// ----------------------- Render types -------------------------
pub const Buffer = struct {
buffer: vk.Buffer,
// TODO VMA: better memory management
memory: vk.DeviceMemory,
};
pub const RenderFrame = struct {
frameIndex: u32,
fsd: *impl_vulkan.FrameSemaphores,
fd: *impl_vulkan.Frame,
};
pub const RenderPass = struct {
cb: vk.CommandBuffer,
wait_stage: vk.PipelineStageFlags align(4),
};
pub const RenderUpload = struct {
commandBuffer: vk.CommandBuffer,
};
// ----------------------- Render interface functions -------------------------
pub fn init(allocator: *std.mem.Allocator, inWindow: *glfw.GLFWwindow) !void {
window = inWindow;
// Setup Vulkan
if (glfw.glfwVulkanSupported() == 0)
return error.VulkanNotSupportedByGLFW;
var extensions_count: u32 = 0;
var extensions_buffer = glfw.glfwGetRequiredInstanceExtensions(&extensions_count);
const extensions = extensions_buffer[0..extensions_count];
vkAllocator = null; // @TODO: Better vk allocator
// Create Vulkan Instance
{
var create_info = vk.InstanceCreateInfo{
.enabledExtensionCount = @intCast(u32, extensions.len),
.ppEnabledExtensionNames = extensions.ptr,
};
if (USE_VULKAN_DEBUG_REPORT) {
const layers = [_][*:0]const u8{"VK_LAYER_KHRONOS_validation"};
create_info.enabledLayerCount = @intCast(u32, layers.len);
create_info.ppEnabledLayerNames = &layers;
// Enable debug report extension (we need additional storage, so we duplicate the user array to add our new extension to it)
const extensions_ext = try allocator.alloc([*:0]const u8, extensions.len + 1);
defer allocator.free(extensions_ext);
std.mem.copy([*:0]const u8, extensions_ext[0..extensions.len], extensions);
extensions_ext[extensions.len] = "VK_EXT_debug_report";
create_info.enabledExtensionCount = @intCast(u32, extensions_ext.len);
create_info.ppEnabledExtensionNames = extensions_ext.ptr;
// Create Vulkan Instance
instance = try vk.CreateInstance(create_info, vkAllocator);
} else {
// Create Vulkan Instance without any debug features
instance = try vk.CreateInstance(create_info, vkAllocator);
}
}
errdefer vk.DestroyInstance(instance, vkAllocator);
// Register debug callback
if (USE_VULKAN_DEBUG_REPORT) {
// Get the function pointer (required for any extensions)
var vkCreateDebugReportCallbackEXT = @ptrCast(?@TypeOf(vk.vkCreateDebugReportCallbackEXT), vk.GetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT")).?;
// Setup the debug report callback
var debug_report_ci = vk.DebugReportCallbackCreateInfoEXT{
.flags = .{ .errorBit = true, .warning = true, .performanceWarning = true },
.pfnCallback = debug_report,
.pUserData = null,
};
var err = vkCreateDebugReportCallbackEXT(instance, &debug_report_ci, vkAllocator, &debugReport);
if (@enumToInt(err) < 0) {
return error.CreateDebugCallbackFailed;
}
}
errdefer if (USE_VULKAN_DEBUG_REPORT) {
// Remove the debug report callback
const vkDestroyDebugReportCallbackEXT = @ptrCast(?@TypeOf(vk.vkDestroyDebugReportCallbackEXT), vk.GetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
assert(vkDestroyDebugReportCallbackEXT != null);
vkDestroyDebugReportCallbackEXT.?(instance, debugReport, vkAllocator);
};
// Select GPU
{
const deviceCount = try vk.EnumeratePhysicalDevicesCount(instance);
if (deviceCount == 0) {
return error.FailedToFindGPUsWithVulkanSupport;
}
const devicesBuf = try allocator.alloc(vk.PhysicalDevice, deviceCount);
defer allocator.free(devicesBuf);
const devices = (try vk.EnumeratePhysicalDevices(instance, devicesBuf)).physicalDevices;
physicalDevice = for (devices) |physDevice| {
if (try isDeviceSuitable(allocator, physDevice)) {
break physDevice;
}
} else return error.FailedToFindSuitableGPU;
}
// Select graphics queue family
queueFamily = SelectQueueFamily: {
var count = vk.GetPhysicalDeviceQueueFamilyPropertiesCount(physicalDevice);
var queues = try allocator.alloc(vk.QueueFamilyProperties, count);
defer allocator.free(queues);
_ = vk.GetPhysicalDeviceQueueFamilyProperties(physicalDevice, queues);
for (queues) |queueProps, i| {
if (queueProps.queueFlags.graphics) {
break :SelectQueueFamily @intCast(u32, i);
}
}
return error.FailedToFindGraphicsQueue;
};
// Create Logical Device (with 1 queue)
{
var device_extensions = [_][*:0]const u8{"VK_KHR_swapchain"};
var queue_priority = [_]f32{1.0};
var queue_info = [_]vk.DeviceQueueCreateInfo{
vk.DeviceQueueCreateInfo{
.queueFamilyIndex = queueFamily,
.queueCount = 1,
.pQueuePriorities = &queue_priority,
},
};
var create_info = vk.DeviceCreateInfo{
.queueCreateInfoCount = @intCast(u32, queue_info.len),
.pQueueCreateInfos = &queue_info,
.enabledExtensionCount = @intCast(u32, device_extensions.len),
.ppEnabledExtensionNames = &device_extensions,
};
device = try vk.CreateDevice(physicalDevice, create_info, vkAllocator);
}
errdefer vk.DestroyDevice(device, vkAllocator);
queue = vk.GetDeviceQueue(device, queueFamily, 0);
// Create Descriptor Pool
{
var pool_sizes = [_]vk.DescriptorPoolSize{
vk.DescriptorPoolSize{ .inType = .SAMPLER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .COMBINED_IMAGE_SAMPLER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .SAMPLED_IMAGE, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .STORAGE_IMAGE, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .UNIFORM_TEXEL_BUFFER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .STORAGE_TEXEL_BUFFER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .UNIFORM_BUFFER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .STORAGE_BUFFER, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .UNIFORM_BUFFER_DYNAMIC, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .STORAGE_BUFFER_DYNAMIC, .descriptorCount = 1000 },
vk.DescriptorPoolSize{ .inType = .INPUT_ATTACHMENT, .descriptorCount = 1000 },
};
var pool_info = vk.DescriptorPoolCreateInfo{
.flags = .{ .freeDescriptorSet = true },
.maxSets = 1000 * @intCast(u32, pool_sizes.len),
.poolSizeCount = @intCast(u32, pool_sizes.len),
.pPoolSizes = &pool_sizes,
};
descriptorPool = try vk.CreateDescriptorPool(device, pool_info, vkAllocator);
}
errdefer vk.DestroyDescriptorPool(device, descriptorPool, vkAllocator);
// Create Window Surface
const err = glfw.glfwCreateWindowSurface(instance, window, vkAllocator, &surface);
if (@enumToInt(err) < 0)
return error.CouldntCreateSurface;
// GLFW says this call is necessary to clean up, but it crashes the program
// so leaving it commented out for now. If deinit/reinit is a thing we
// want to support eventually, we should revisit this.
//errdefer vk.DestroySurfaceKHR(instance, surface, vkAllocator);
// Create Framebuffers
{
var w: c_int = 0;
var h: c_int = 0;
glfw.glfwGetFramebufferSize(window, &w, &h);
_ = glfw.glfwSetFramebufferSizeCallback(window, glfw_resize_callback);
const wd = &g_MainWindowData;
wd.Surface = surface;
wd.Allocator = allocator;
var res = try vk.GetPhysicalDeviceSurfaceSupportKHR(physicalDevice, queueFamily, surface);
if (res != vk.TRUE) {
return error.NoWSISupport;
}
// Select Surface Format
const requestSurfaceImageFormat = [_]vk.Format{ .B8G8R8A8_UNORM, .R8G8B8A8_UNORM, .B8G8R8_UNORM, .R8G8B8_UNORM };
const requestSurfaceColorSpace = vk.ColorSpaceKHR.SRGB_NONLINEAR;
wd.SurfaceFormat = try impl_vulkan.SelectSurfaceFormat(physicalDevice, surface, &requestSurfaceImageFormat, requestSurfaceColorSpace, allocator);
// Select Present Mode
if (IMGUI_UNLIMITED_FRAME_RATE) {
var present_modes = [_]vk.PresentModeKHR{ .MAILBOX, .IMMEDIATE, .FIFO };
wd.PresentMode = try impl_vulkan.SelectPresentMode(physicalDevice, surface, &present_modes, allocator);
} else {
var present_modes = [_]vk.PresentModeKHR{.FIFO};
wd.PresentMode = try impl_vulkan.SelectPresentMode(physicalDevice, surface, &present_modes, allocator);
}
// Create SwapChain, RenderPass, Framebuffer, etc.
assert(g_MinImageCount >= 2);
try impl_vulkan.CreateWindow(instance, physicalDevice, device, wd, queueFamily, vkAllocator, @intCast(u32, w), @intCast(u32, h), g_MinImageCount);
}
errdefer impl_vulkan.DestroyWindow(instance, device, &g_MainWindowData, vkAllocator) catch {};
}
pub fn deinit() void {
impl_vulkan.DestroyWindow(instance, device, &g_MainWindowData, vkAllocator) catch {};
// GLFW says this call is necessary to clean up, but it crashes the program
// so leaving it commented out for now. If deinit/reinit is a thing we
// want to support eventually, we should revisit this.
//vk.DestroySurfaceKHR(instance, surface, vkAllocator);
vk.DestroyDescriptorPool(device, descriptorPool, vkAllocator);
if (USE_VULKAN_DEBUG_REPORT) {
// Remove the debug report callback
const vkDestroyDebugReportCallbackEXT = @ptrCast(?@TypeOf(vk.vkDestroyDebugReportCallbackEXT), vk.GetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT"));
assert(vkDestroyDebugReportCallbackEXT != null);
vkDestroyDebugReportCallbackEXT.?(instance, debugReport, vkAllocator);
}
vk.DestroyDevice(device, vkAllocator);
vk.DestroyInstance(instance, vkAllocator);
}
pub fn initImgui(allocator: *std.mem.Allocator) !void {
// Setup Platform/Renderer bindings
var initResult = impl_glfw.InitForVulkan(window, true);
assert(initResult);
const wd = &g_MainWindowData;
var init_info = impl_vulkan.InitInfo{
.Allocator = allocator,
.Instance = instance,
.PhysicalDevice = physicalDevice,
.Device = device,
.QueueFamily = queueFamily,
.Queue = queue,
.PipelineCache = pipelineCache,
.DescriptorPool = descriptorPool,
.VkAllocator = vkAllocator,
.MinImageCount = g_MinImageCount,
.MSAASamples = .{},
.ImageCount = wd.ImageCount,
};
try impl_vulkan.Init(&init_info, wd.RenderPass);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use imgui.PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.txt' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//io.Fonts.AddFontDefault();
//io.Fonts.AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts.AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts.AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts.AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts.AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts.GetGlyphRangesJapanese());
//assert(font != NULL);
// Upload Fonts
// Use any command queue
const command_pool = wd.Frames[0].CommandPool;
const command_buffer = wd.Frames[0].CommandBuffer;
try vk.ResetCommandPool(device, command_pool, .{});
const begin_info = vk.CommandBufferBeginInfo{
.flags = .{ .oneTimeSubmit = true },
};
try vk.BeginCommandBuffer(command_buffer, begin_info);
try impl_vulkan.CreateFontsTexture(command_buffer);
const end_info = vk.SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = arrayPtr(&command_buffer),
};
try vk.EndCommandBuffer(command_buffer);
try vk.QueueSubmit(queue, arrayPtr(&end_info), null);
try vk.DeviceWaitIdle(device);
impl_vulkan.DestroyFontUploadObjects();
}
pub fn deinitImgui() void {
vk.DeviceWaitIdle(device) catch {};
impl_vulkan.Shutdown();
impl_glfw.Shutdown();
}
pub fn beginFrame() !void {
if (g_SwapChainRebuild) {
g_SwapChainRebuild = false;
try impl_vulkan.SetMinImageCount(g_MinImageCount);
try impl_vulkan.CreateWindow(instance, physicalDevice, device, &g_MainWindowData, queueFamily, vkAllocator, g_SwapChainResizeWidth, g_SwapChainResizeHeight, g_MinImageCount);
}
}
pub fn beginImgui() void {
// Start the Dear ImGui frame
impl_vulkan.NewFrame();
impl_glfw.NewFrame();
}
pub fn beginRender() !RenderFrame {
const wd = &g_MainWindowData;
const fsd = &wd.FrameSemaphores[g_SemaphoreIndex];
g_SemaphoreIndex = (g_SemaphoreIndex + 1) % wd.ImageCount; // Now we can use the next set of semaphores
const image_acquired_semaphore = fsd.ImageAcquiredSemaphore;
const render_complete_semaphore = fsd.RenderCompleteSemaphore;
const frameIndex = (try vk.AcquireNextImageKHR(device, wd.Swapchain.?, ~@as(u64, 0), image_acquired_semaphore, null)).imageIndex;
const fd = &wd.Frames[frameIndex];
_ = try vk.WaitForFences(device, arrayPtr(&fd.Fence), vk.TRUE, ~@as(u64, 0)); // wait indefinitely instead of periodically checking
try vk.ResetFences(device, arrayPtr(&fd.Fence));
try vk.ResetCommandPool(device, fd.CommandPool, .{});
return RenderFrame{
.frameIndex = frameIndex,
.fsd = fsd,
.fd = fd,
};
}
pub fn endRender(frame: *RenderFrame) void {
const wd = &g_MainWindowData;
const render_complete_semaphore = frame.fsd.RenderCompleteSemaphore;
var info = vk.PresentInfoKHR{
.waitSemaphoreCount = 1,
.pWaitSemaphores = arrayPtr(&render_complete_semaphore),
.swapchainCount = 1,
.pSwapchains = arrayPtr(&wd.Swapchain.?),
.pImageIndices = arrayPtr(&frame.frameIndex),
};
_ = vk.QueuePresentKHR(queue, info) catch @panic("QueuePresentKHR Failed!"); // TODO device lost
}
pub fn beginColorPass(frame: *RenderFrame, clearColor: imgui.Vec4) !RenderPass {
const fd = frame.fd;
{
var info = vk.CommandBufferBeginInfo{
.flags = .{ .oneTimeSubmit = true },
};
try vk.BeginCommandBuffer(fd.CommandBuffer, info);
}
{
const wd = &g_MainWindowData;
var info = vk.RenderPassBeginInfo{
.renderPass = wd.RenderPass.?,
.framebuffer = fd.Framebuffer,
.renderArea = vk.Rect2D{
.offset = vk.Offset2D{ .x = 0, .y = 0 },
.extent = vk.Extent2D{ .width = wd.Width, .height = wd.Height },
},
.clearValueCount = 1,
.pClearValues = @ptrCast([*]const vk.ClearValue, &clearColor),
};
vk.CmdBeginRenderPass(fd.CommandBuffer, info, .INLINE);
}
return RenderPass{
.cb = fd.CommandBuffer,
.wait_stage = .{ .colorAttachmentOutput = true },
};
}
pub fn endRenderPass(frame: *RenderFrame, pass: *RenderPass) void {
const fd = frame.fd;
const fsd = frame.fsd;
// Submit command buffer
vk.CmdEndRenderPass(fd.CommandBuffer);
vk.EndCommandBuffer(fd.CommandBuffer) catch @panic("EndCommandBuffer failed!");
{
var info = vk.SubmitInfo{
.waitSemaphoreCount = 1,
.pWaitSemaphores = arrayPtr(&fsd.ImageAcquiredSemaphore),
.pWaitDstStageMask = arrayPtr(&pass.wait_stage),
.commandBufferCount = 1,
.pCommandBuffers = arrayPtr(&fd.CommandBuffer),
.signalSemaphoreCount = 1,
.pSignalSemaphores = arrayPtr(&fsd.RenderCompleteSemaphore),
};
vk.QueueSubmit(queue, arrayPtr(&info), fd.Fence) catch @panic("QueueSubmit failed!"); // TODO: device lost
}
}
pub fn beginUpload(frame: *RenderFrame) !RenderUpload {
const fd = frame.fd;
{
var info = vk.CommandBufferBeginInfo{
.flags = .{ .oneTimeSubmit = true },
};
try vk.BeginCommandBuffer(fd.CommandBuffer, info);
}
return RenderUpload{
.commandBuffer = fd.CommandBuffer,
};
}
pub fn uploadCopyBuffer(
frame: *RenderFrame,
upload: *RenderUpload,
source: *Buffer,
sourceOffset: usize,
dest: *Buffer,
destOffset: usize,
len: usize,
) void {
const copyRegion = vk.BufferCopy{
.srcOffset = sourceOffset,
.dstOffset = destOffset,
.size = len,
};
vk.CmdCopyBuffer(upload.commandBuffer, source.buffer, dest.buffer, arrayPtr(©Region));
}
pub fn abortUpload(frame: *RenderFrame, upload: *RenderUpload) void {
vk.ResetCommandBuffer(upload.commandBuffer, .{ .releaseResources = true }) catch {};
}
pub fn endUploadAndWait(frame: *RenderFrame, upload: *RenderUpload) void {
vk.EndCommandBuffer(upload.commandBuffer) catch @panic("EndCommandBuffer failed!");
const submitInfo = vk.SubmitInfo{
.commandBufferCount = 1,
.pCommandBuffers = arrayPtr(&upload.commandBuffer),
};
vk.QueueSubmit(queue, arrayPtr(&submitInfo), null) catch @panic("QueueSubmit failed!");
vk.QueueWaitIdle(queue) catch @panic("QueueWaitIdle failed!");
}
pub fn createGpuBuffer(size: usize, flags: vk.BufferUsageFlags) !Buffer {
return try createVkBuffer(size, flags.with(.{ .transferDst = true }), .{ .deviceLocal = true });
}
pub fn createStagingBuffer(size: usize) !Buffer {
return try createVkBuffer(size, .{ .transferSrc = true }, .{ .hostVisible = true, .hostCoherent = true });
}
pub fn destroyBuffer(buffer: *Buffer) void {
vk.DestroyBuffer(device, buffer.buffer, vkAllocator);
vk.FreeMemory(device, buffer.memory, vkAllocator);
}
pub fn mapBuffer(buffer: *Buffer, offset: usize, length: usize) ![*]u8 {
var result: [*]u8 = undefined;
try vk.MapMemory(device, buffer.memory, offset, length, .{}, @ptrCast(**c_void, &result));
return result;
}
pub fn flushMappedRange(buffer: *Buffer, mappedPtr: [*]u8, offset: usize, length: usize) !void {
const range = vk.MappedMemoryRange{
.memory = buffer.memory,
.offset = offset,
.size = length,
};
try vk.FlushMappedMemoryRanges(device, arrayPtr(&range));
}
pub fn unmapBuffer(buffer: *Buffer, mappedPtr: [*]u8, offset: usize, length: usize) void {
vk.UnmapMemory(device, buffer.memory);
}
pub fn renderImgui(frame: *RenderFrame, pass: *RenderPass) !void {
// Record Imgui Draw Data and draw funcs into command buffer
try impl_vulkan.RenderDrawData(imgui.GetDrawData(), pass.cb);
}
// ----------------------- Backend functions -------------------------
pub fn createVkBuffer(size: usize, usageFlags: vk.BufferUsageFlags, memoryFlags: vk.MemoryPropertyFlags) !Buffer {
const info = vk.BufferCreateInfo{
.size = size,
.usage = usageFlags,
.sharingMode = .EXCLUSIVE,
};
const buffer = try vk.CreateBuffer(device, info, vkAllocator);
errdefer vk.DestroyBuffer(device, buffer, vkAllocator);
const stagingReqs = vk.GetBufferMemoryRequirements(device, buffer);
const stagingAllocInfo = vk.MemoryAllocateInfo{
.allocationSize = stagingReqs.size,
.memoryTypeIndex = getMemoryTypeIndex(stagingReqs.memoryTypeBits, memoryFlags),
};
// TODO VMA: better allocation management
const memory = try vk.AllocateMemory(device, stagingAllocInfo, vkAllocator);
errdefer vk.FreeMemory(device, memory, vkAllocator);
try vk.BindBufferMemory(device, buffer, memory, 0);
return Buffer{
.buffer = buffer,
.memory = memory,
};
}
pub fn getMemoryTypeIndex(memType: u32, properties: vk.MemoryPropertyFlags) u32 {
return impl_vulkan.MemoryType(properties, memType).?;
}
fn isDeviceSuitable(allocator: *std.mem.Allocator, inDevice: vk.PhysicalDevice) !bool {
// @TODO: Proper checks
if (@ptrToInt(allocator) != 0) return true;
return error.OutOfMemory;
//const indices = try findQueueFamilies(allocator, inDevice);
//
//const extensionsSupported = try checkDeviceExtensionSupport(allocator, inDevice);
//
//var swapChainAdequate = false;
//if (extensionsSupported) {
// var swapChainSupport = try querySwapChainSupport(allocator, inDevice);
// defer swapChainSupport.deinit();
// swapChainAdequate = swapChainSupport.formats.len != 0 and swapChainSupport.presentModes.len != 0;
//}
//
//return indices.isComplete() and extensionsSupported and swapChainAdequate;
}
fn checkDeviceExtensionSupport(allocator: *std.mem.Allocator, inDevice: vk.PhysicalDevice) !bool {
var extensionCount = try vk.EnumerateDeviceExtensionPropertiesCount(inDevice, null);
const availableExtensionsBuf = try allocator.alloc(vk.ExtensionProperties, extensionCount);
defer allocator.free(availableExtensionsBuf);
var availableExtensions = (try vk.EnumerateDeviceExtensionProperties(inDevice, null, availableExtensionsBuf)).properties;
var requiredExtensions = std.HashMap([*:0]const u8, void, hash_cstr, eql_cstr).init(allocator);
defer requiredExtensions.deinit();
for (deviceExtensions) |device_ext| {
_ = try requiredExtensions.put(device_ext, {});
}
for (availableExtensions) |extension| {
_ = requiredExtensions.remove(&extension.extensionName);
}
return requiredExtensions.count() == 0;
}
fn glfw_resize_callback(inWindow: ?*glfw.GLFWwindow, w: c_int, h: c_int) callconv(.C) void {
g_SwapChainRebuild = true;
g_SwapChainResizeWidth = @intCast(u32, w);
g_SwapChainResizeHeight = @intCast(u32, h);
}
fn debug_report(flags: vk.DebugReportFlagsEXT.IntType, objectType: vk.DebugReportObjectTypeEXT, object: u64, location: usize, messageCode: i32, pLayerPrefix: ?[*:0]const u8, pMessage: ?[*:0]const u8, pUserData: ?*c_void) callconv(vk.CallConv) vk.Bool32 {
std.debug.warn("[vulkan] ObjectType: {}\nMessage: {s}\n\n", .{ objectType, pMessage });
@panic("VK Error");
//return vk.FALSE;
}
fn hash_cstr(a: [*:0]const u8) u32 {
// FNV 32-bit hash
var h: u32 = 2166136261;
var i: usize = 0;
while (a[i] != 0) : (i += 1) {
h ^= a[i];
h *%= 16777619;
}
return h;
}
fn eql_cstr(a: [*:0]const u8, b: [*:0]const u8) bool {
return std.cstr.cmp(a, b) == 0;
}
/// Takes a pointer type like *T, *const T, *align(4)T, etc,
/// returns the pointer type *[1]T, *const [1]T, *align(4) [1]T, etc.
fn ArrayPtrType(comptime ptrType: type) type {
comptime {
// Check that the input is of type *T
var info = @typeInfo(ptrType);
assert(info == .Pointer);
assert(info.Pointer.size == .One);
assert(info.Pointer.sentinel == null);
// Create the new value type, [1]T
const arrayInfo = std.builtin.TypeInfo{
.Array = .{
.len = 1,
.child = info.Pointer.child,
.sentinel = @as(?info.Pointer.child, null),
},
};
// Patch the type to be *[1]T, preserving other modifiers
const singleArrayType = @Type(arrayInfo);
info.Pointer.child = singleArrayType;
// also need to change the type of the sentinel
// we checked that this is null above so no work needs to be done here.
info.Pointer.sentinel = @as(?singleArrayType, null);
return @Type(info);
}
}
pub fn arrayPtr(ptr: anytype) ArrayPtrType(@TypeOf(ptr)) {
return @as(ArrayPtrType(@TypeOf(ptr)), ptr);
} | src/render_vulkan.zig |
const std = @import("std");
const ArrayList = std.ArrayList;
const print = std.debug.print;
const sort = std.sort;
const testing = std.testing;
const tokenize = std.mem.tokenize;
var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = gpa_impl.allocator();
const input = @embedFile("./input.txt");
pub fn main() anyerror!void {
print("--- Part One ---\n", .{});
print("Result: {d}\n", .{part1()});
print("--- Part Two ---\n", .{});
print("Result: {d}\n", .{part2()});
}
///
/// --- Part One ---
///
fn part1() !u32 {
var ans: u32 = 0;
var input_iter = tokenize(u8, input, "\n");
while (input_iter.next()) |line| {
var stack = ArrayList(u8).init(gpa);
defer stack.deinit();
for (line) |c| {
switch (c) {
'(' => try stack.append(')'),
'[' => try stack.append(']'),
'{' => try stack.append('}'),
'<' => try stack.append('>'),
else => if (stack.items.len == 0 or stack.pop() != c) {
switch (c) {
')' => ans += 3,
']' => ans += 57,
'}' => ans += 1197,
'>' => ans += 25137,
else => unreachable,
}
break;
},
}
}
}
return ans;
}
test "day10.part1" {
try testing.expectEqual(@as(u32, 266301), try part1());
}
///
/// --- Part Two ---
///
fn part2() !u64 {
var scores = ArrayList(u64).init(gpa);
defer scores.deinit();
var input_iter = tokenize(u8, input, "\n");
while (input_iter.next()) |line| {
var stack = ArrayList(u8).init(gpa);
defer stack.deinit();
for (line) |c| {
switch (c) {
'(' => try stack.append(')'),
'[' => try stack.append(']'),
'{' => try stack.append('}'),
'<' => try stack.append('>'),
else => if (stack.items.len == 0 or stack.pop() != c) {
stack.clearAndFree();
break;
},
}
}
var score: u64 = 0;
while (stack.popOrNull()) |c| {
switch (c) {
')' => score = score * 5 + 1,
']' => score = score * 5 + 2,
'}' => score = score * 5 + 3,
'>' => score = score * 5 + 4,
else => unreachable,
}
}
if (score != 0) {
try scores.append(score);
}
}
sort.sort(u64, scores.items, {}, comptime sort.asc(u64));
return scores.items[scores.items.len / 2];
}
test "day10.part2" {
try testing.expectEqual(@as(u64, 3404870164), try part2());
} | src/day10/day10.zig |
const std = @import("std");
const c = @import("internal/c.zig");
const internal = @import("internal/internal.zig");
const log = std.log.scoped(.git);
const git = @import("git.zig");
pub const StatusList = opaque {
pub fn deinit(self: *StatusList) void {
log.debug("StatusList.deinit called", .{});
c.git_status_list_free(@ptrCast(*c.git_status_list, self));
log.debug("status list freed successfully", .{});
}
pub fn entryCount(self: *StatusList) usize {
log.debug("StatusList.entryCount called", .{});
const ret = c.git_status_list_entrycount(@ptrCast(*c.git_status_list, self));
log.debug("status list entry count: {}", .{ret});
return ret;
}
pub fn statusByIndex(self: *StatusList, index: usize) ?*const StatusEntry {
log.debug("StatusList.statusByIndex called, index: {}", .{index});
return @ptrCast(
?*const StatusEntry,
c.git_status_byindex(@ptrCast(*c.git_status_list, self), index),
);
}
/// Get performance data for diffs from a StatusList
pub fn getPerfData(self: *const StatusList) !git.DiffPerfData {
log.debug("StatusList.getPerfData called", .{});
var c_ret = c.git_diff_perfdata{
.version = c.GIT_DIFF_PERFDATA_VERSION,
.stat_calls = 0,
.oid_calculations = 0,
};
try internal.wrapCall("git_status_list_get_perfdata", .{
&c_ret,
@ptrCast(*const c.git_status_list, self),
});
const ret: git.DiffPerfData = .{
.stat_calls = c_ret.stat_calls,
.oid_calculations = c_ret.oid_calculations,
};
log.debug("perf data: {}", .{ret});
return ret;
}
/// A status entry, providing the differences between the file as it exists in HEAD and the index, and providing the
/// differences between the index and the working directory.
pub const StatusEntry = extern struct {
/// The status for this file
status: git.FileStatus,
/// information about the differences between the file in HEAD and the file in the index.
head_to_index: *git.DiffDelta,
/// information about the differences between the file in the index and the file in the working directory.
index_to_workdir: *git.DiffDelta,
test {
try std.testing.expectEqual(@sizeOf(c.git_status_entry), @sizeOf(StatusEntry));
try std.testing.expectEqual(@bitSizeOf(c.git_status_entry), @bitSizeOf(StatusEntry));
}
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
}
};
comptime {
std.testing.refAllDecls(@This());
} | src/status_list.zig |
const std = @import("std");
const mem = std.mem;
const testing = std.testing;
const unicode = std.unicode;
const ascii = @import("ascii.zig");
// Functionality by popular Unicode General Category.
pub const letter = @import("category/letter.zig");
pub const mark = @import("category/mark.zig");
pub const number = @import("category/number.zig");
pub const punct = @import("category/punct.zig");
pub const symbol = @import("category/symbol.zig");
// Display width calculation.
pub const display_width = @import("display_width.zig");
// String segmentation.
pub const CodePoint = @import("segmenter/CodePoint.zig");
pub const CodePointIterator = CodePoint.CodePointIterator;
pub const Grapheme = @import("segmenter/Grapheme.zig");
pub const GraphemeIterator = Grapheme.GraphemeIterator;
pub const Word = @import("segmenter/Word.zig");
pub const WordIterator = Word.WordIterator;
pub const Sentence = @import("segmenter/Sentence.zig");
pub const SentenceIterator = Sentence.SentenceIterator;
pub const ComptimeSentenceIterator = Sentence.ComptimeSentenceIterator;
// Collation
pub const Collator = @import("collator/Collator.zig");
// Normalization
pub const Normalizer = @import("normalizer/Normalizer.zig");
// Auto-Generated
pub const blocks = @import("autogen/blocks.zig");
pub const canonicals = @import("autogen/canonicals.zig");
pub const case_fold_map = @import("autogen/case_folding.zig");
pub const combining_map = @import("autogen/derived_combining_class.zig");
pub const derived_core_properties = @import("autogen/derived_core_properties.zig");
pub const derived_east_asian_width = @import("autogen/derived_east_asian_width.zig");
pub const derived_general_category = @import("autogen/derived_general_category.zig");
pub const derived_normalization_props = @import("autogen/derived_normalization_props.zig");
pub const derived_numeric_type = @import("autogen/derived_numeric_type.zig");
pub const emoji_data = @import("autogen/emoji_data.zig");
pub const grapheme_break_property = @import("autogen/grapheme_break_property.zig");
pub const hangul_map = @import("autogen/hangul_syllable_type.zig");
pub const lower_map = @import("autogen/lower_map.zig");
pub const prop_list = @import("autogen/prop_list.zig");
pub const sentence_break_property = @import("autogen/sentence_break_property.zig");
pub const title_map = @import("autogen/title_map.zig");
pub const upper_map = @import("autogen/upper_map.zig");
pub const word_break_property = @import("autogen/word_break_property.zig");
pub fn isAlphabetic(cp: u21) bool {
return derived_core_properties.isAlphabetic(cp);
}
pub fn isAsciiAlphabetic(cp: u21) bool {
return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z');
}
pub fn isAlphaNum(cp: u21) bool {
return isAlphabetic(cp) or isNumber(cp);
}
pub fn isAsciiAlphaNum(cp: u21) bool {
return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z') or (cp >= '0' and cp <= '9');
}
/// `isCased` returns true if `cp` can be lower, title, or uppercase.
pub fn isCased(cp: u21) bool {
return letter.isCased(cp);
}
/// `isCasedStr` returns true when all code points in `str` are either lower, title, or uppercase.
pub fn isCasedStr(str: []const u8) !bool {
var iter = (try unicode.Utf8View.init(str)).iterator();
return while (iter.nextCodepoint()) |cp| {
if (!isCased(cp)) break false;
} else true;
}
test "ziglyph isCasedStr" {
try testing.expect(try isCasedStr("abc"));
try testing.expect(!try isCasedStr("abc123"));
try testing.expect(!try isCasedStr("123"));
}
/// `isDecimal` detects all Unicode decimal numbers.
pub fn isDecimal(cp: u21) bool {
return number.isDecimal(cp);
}
pub fn isDigit(cp: u21) bool {
return number.isDigit(cp);
}
pub fn isAsciiDigit(cp: u21) bool {
return cp >= '0' and cp <= '9';
}
/// `isGraphic` detects any code point that can be represented graphically, including spaces.
pub fn isGraphic(cp: u21) bool {
return isPrint(cp) or isWhiteSpace(cp);
}
pub fn isAsciiGraphic(cp: u21) bool {
return ascii.isGraph(@intCast(u8, cp));
}
// `isHexDigit` detects hexadecimal code points.
pub fn isHexDigit(cp: u21) bool {
return number.isHexDigit(cp);
}
pub fn isAsciiHexDigit(cp: u21) bool {
return (cp >= 'a' and cp <= 'f') or (cp >= 'A' and cp <= 'F') or (cp >= '0' and cp <= '9');
}
/// `isPrint` detects any code point that can be printed, excluding spaces.
pub fn isPrint(cp: u21) bool {
return isAlphaNum(cp) or isMark(cp) or isPunct(cp) or
isSymbol(cp) or isWhiteSpace(cp);
}
pub fn isAsciiPrint(cp: u21) bool {
return ascii.isPrint(@intCast(u8, cp));
}
/// `isControl` detects control characters.
pub fn isControl(cp: u21) bool {
return derived_general_category.isControl(cp);
}
pub fn isAsciiControl(cp: u21) bool {
return ascii.isCntrl(@intCast(u8, cp));
}
pub fn isLetter(cp: u21) bool {
return letter.isLetter(cp);
}
pub fn isAsciiLetter(cp: u21) bool {
return (cp >= 'A' and cp <= 'Z') or (cp >= 'a' and cp <= 'z');
}
/// `isLower` detects code points that are lowercase.
pub fn isLower(cp: u21) bool {
return letter.isLower(cp);
}
pub fn isAsciiLower(cp: u21) bool {
return cp >= 'a' and cp <= 'z';
}
/// `isLowerStr` returns true when all code points in `s` are lowercase.
pub fn isLowerStr(s: []const u8) !bool {
var iter = (try unicode.Utf8View.init(s)).iterator();
return while (iter.nextCodepoint()) |cp| {
if (isCased(cp) and !isLower(cp)) break false;
} else true;
}
test "ziglyph isLowerStr" {
try testing.expect(try isLowerStr("abc"));
try testing.expect(try isLowerStr("abc123"));
try testing.expect(!try isLowerStr("Abc123"));
}
/// `isMark` detects Unicode marks (combining, spacing, etc.)
pub fn isMark(cp: u21) bool {
return mark.isMark(cp);
}
pub fn isNumber(cp: u21) bool {
return number.isNumber(cp);
}
pub fn isAsciiNumber(cp: u21) bool {
return cp >= '0' and cp <= '9';
}
/// `isPunct` detects punctuation characters. Note some punctuation may be considered as symbols by Unicode.
pub fn isPunct(cp: u21) bool {
return punct.isPunct(cp);
}
pub fn isAsciiPunct(cp: u21) bool {
return ascii.isPunct(@intCast(u8, cp));
}
/// `isWhiteSpace` detects code points that have the Unicode *WhiteSpace* property.
pub fn isWhiteSpace(cp: u21) bool {
return prop_list.isWhiteSpace(cp);
}
pub fn isAsciiWhiteSpace(cp: u21) bool {
return ascii.isSpace(@intCast(u8, cp));
}
// `isSymbol` detects symbols which may include code points commonly considered to be punctuation.
pub fn isSymbol(cp: u21) bool {
return symbol.isSymbol(cp);
}
pub fn isAsciiSymbol(cp: u21) bool {
return ascii.isSymbol(@intCast(u8, cp));
}
/// `isTitle` detects code points in titlecase, which may be different than uppercase.
pub fn isTitle(cp: u21) bool {
return letter.isTitle(cp);
}
/// `isUpper` detects code points in uppercase.
pub fn isUpper(cp: u21) bool {
return letter.isUpper(cp);
}
pub fn isAsciiUpper(cp: u21) bool {
return cp >= 'A' and cp <= 'Z';
}
/// `isUpperStr` returns true when all code points in `str` are uppercase.
pub fn isUpperStr(str: []const u8) !bool {
var iter = (try unicode.Utf8View.init(str)).iterator();
return while (iter.nextCodepoint()) |cp| {
if (isCased(cp) and !isUpper(cp)) break false;
} else true;
}
test "ziglyph isUpperStr" {
try testing.expect(try isUpperStr("ABC"));
try testing.expect(try isUpperStr("ABC123"));
try testing.expect(!try isUpperStr("abc123"));
}
/// `toLower` returns the lowercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toLower(cp: u21) u21 {
return letter.toLower(cp);
}
pub fn toAsciiLower(cp: u21) u21 {
return if (cp >= 'A' and cp <= 'Z') cp ^ 32 else cp;
}
/// `toCaseFoldStr` returns the case folded version of `str`. Caller must free returned memory.
pub fn toCaseFoldStr(allocator: std.mem.Allocator, str: []const u8) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
var buf: [4]u8 = undefined;
var iter = (try unicode.Utf8View.init(str)).iterator();
while (iter.nextCodepoint()) |cp| {
const cf = letter.toCaseFold(cp);
for (cf) |cfcp| {
if (cfcp == 0) break;
const len = try unicode.utf8Encode(cfcp, &buf);
try result.appendSlice(buf[0..len]);
}
}
return result.toOwnedSlice();
}
test "ziglyph toCaseFoldStr" {
var allocator = std.testing.allocator;
const got = try toCaseFoldStr(allocator, "AbC123\u{0390}");
defer allocator.free(got);
try testing.expect(std.mem.eql(u8, "abc123\u{03B9}\u{0308}\u{0301}", got));
}
/// `toLowerStr` returns the lowercase version of `s`. Caller must free returned memory with `allocator`.
pub fn toLowerStr(allocator: std.mem.Allocator, str: []const u8) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
var buf: [4]u8 = undefined;
var iter = (try unicode.Utf8View.init(str)).iterator();
while (iter.nextCodepoint()) |cp| {
const len = try unicode.utf8Encode(toLower(cp), &buf);
try result.appendSlice(buf[0..len]);
}
return result.toOwnedSlice();
}
test "ziglyph toLowerStr" {
var allocator = std.testing.allocator;
const got = try toLowerStr(allocator, "AbC123");
defer allocator.free(got);
try testing.expect(std.mem.eql(u8, "abc123", got));
}
/// `toTitle` returns the titlecase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toTitle(cp: u21) u21 {
return letter.toTitle(cp);
}
/// `toTitleStr` returns the titlecase version of `str`. Caller must free returned memory with `allocator`.
pub fn toTitleStr(allocator: std.mem.Allocator, str: []const u8) ![]u8 {
var words = try WordIterator.init(str);
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
var buf: [4]u8 = undefined;
while (words.next()) |word| {
var code_points = CodePointIterator{ .bytes = word.bytes };
var got_f = false;
while (code_points.next()) |cp| {
var len: usize = 0;
if (!got_f and isCased(cp.scalar)) {
// First cased is titlecase.
len = try unicode.utf8Encode(toTitle(cp.scalar), &buf);
got_f = true;
} else if (isCased(cp.scalar)) {
// Subsequent cased are lowercase.
len = try unicode.utf8Encode(toLower(cp.scalar), &buf);
} else {
// Uncased remain the same.
len = try unicode.utf8Encode(cp.scalar, &buf);
}
try result.appendSlice(buf[0..len]);
}
}
return result.toOwnedSlice();
}
test "ziglyph toTitleStr" {
var allocator = std.testing.allocator;
const got = try toTitleStr(allocator, "the aBc123 broWn. fox");
defer allocator.free(got);
try testing.expectEqualStrings("The Abc123 Brown. Fox", got);
}
/// `toUpper` returns the uppercase code point for the given code point. It returns the same
/// code point given if no mapping exists.
pub fn toUpper(cp: u21) u21 {
return letter.toUpper(cp);
}
pub fn toAsciiUpper(cp: u21) u21 {
return if (cp >= 'a' and cp <= 'z') cp ^ 32 else cp;
}
/// `toUpperStr` returns the uppercase version of `str`. Caller must free returned memory with `allocator`.
pub fn toUpperStr(allocator: std.mem.Allocator, str: []const u8) ![]u8 {
var result = std.ArrayList(u8).init(allocator);
defer result.deinit();
var buf: [4]u8 = undefined;
var iter = (try unicode.Utf8View.init(str)).iterator();
while (iter.nextCodepoint()) |cp| {
const len = try unicode.utf8Encode(toUpper(cp), &buf);
try result.appendSlice(buf[0..len]);
}
return result.toOwnedSlice();
}
test "ziglyph toUpperStr" {
var allocator = std.testing.allocator;
const got = try toUpperStr(allocator, "aBc123");
defer allocator.free(got);
try testing.expect(std.mem.eql(u8, "ABC123", got));
}
test "ziglyph ASCII methods" {
const z = 'F';
try testing.expect(isAsciiAlphabetic(z));
try testing.expect(isAsciiAlphaNum(z));
try testing.expect(isAsciiHexDigit(z));
try testing.expect(isAsciiGraphic(z));
try testing.expect(isAsciiPrint(z));
try testing.expect(isAsciiUpper(z));
try testing.expect(!isAsciiControl(z));
try testing.expect(!isAsciiDigit(z));
try testing.expect(!isAsciiNumber(z));
try testing.expect(!isAsciiLower(z));
try testing.expectEqual(toAsciiLower(z), 'f');
try testing.expectEqual(toAsciiUpper('a'), 'A');
try testing.expect(isAsciiLower(toAsciiLower(z)));
}
test "ziglyph struct" {
const z = 'z';
try testing.expect(isAlphaNum(z));
try testing.expect(!isControl(z));
try testing.expect(!isDecimal(z));
try testing.expect(!isDigit(z));
try testing.expect(!isHexDigit(z));
try testing.expect(isGraphic(z));
try testing.expect(isLetter(z));
try testing.expect(isLower(z));
try testing.expect(!isMark(z));
try testing.expect(!isNumber(z));
try testing.expect(isPrint(z));
try testing.expect(!isPunct(z));
try testing.expect(!isWhiteSpace(z));
try testing.expect(!isSymbol(z));
try testing.expect(!isTitle(z));
try testing.expect(!isUpper(z));
const uz = toUpper(z);
try testing.expect(isUpper(uz));
try testing.expectEqual(uz, 'Z');
const lz = toLower(uz);
try testing.expect(isLower(lz));
try testing.expectEqual(lz, 'z');
const tz = toTitle(lz);
try testing.expect(isUpper(tz));
try testing.expectEqual(tz, 'Z');
}
test "ziglyph isGraphic" {
try testing.expect(isGraphic('A'));
try testing.expect(isGraphic('\u{20E4}'));
try testing.expect(isGraphic('1'));
try testing.expect(isGraphic('?'));
try testing.expect(isGraphic(' '));
try testing.expect(isGraphic('='));
try testing.expect(!isGraphic('\u{0003}'));
}
test "ziglyph isHexDigit" {
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
try testing.expect(isHexDigit(cp));
}
cp = 'A';
while (cp <= 'F') : (cp += 1) {
try testing.expect(isHexDigit(cp));
}
cp = 'a';
while (cp <= 'f') : (cp += 1) {
try testing.expect(isHexDigit(cp));
}
try testing.expect(!isHexDigit('\u{0003}'));
try testing.expect(!isHexDigit('Z'));
}
test "ziglyph isPrint" {
try testing.expect(isPrint('A'));
try testing.expect(isPrint('\u{20E4}'));
try testing.expect(isPrint('1'));
try testing.expect(isPrint('?'));
try testing.expect(isPrint('='));
try testing.expect(isPrint(' '));
try testing.expect(isPrint('\t'));
try testing.expect(!isPrint('\u{0003}'));
}
test "ziglyph isAlphaNum" {
var cp: u21 = '0';
while (cp <= '9') : (cp += 1) {
try testing.expect(isAlphaNum(cp));
}
cp = 'a';
while (cp <= 'z') : (cp += 1) {
try testing.expect(isAlphaNum(cp));
}
cp = 'A';
while (cp <= 'Z') : (cp += 1) {
try testing.expect(isAlphaNum(cp));
}
try testing.expect(!isAlphaNum('='));
}
test "ziglyph isControl" {
try testing.expect(isControl('\t'));
try testing.expect(isControl('\u{0008}'));
try testing.expect(isControl('\u{0012}'));
try testing.expect(isControl('\n'));
try testing.expect(isControl('\r'));
try testing.expect(!isControl('A'));
} | src/ziglyph.zig |
const std = @import("std");
const fs = std.fs;
const clock_speed = 500; // 2Mhz
const memory_size = 0x10000; // number of values a 16-bit integer can hold
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const args = try std.process.argsAlloc(allocator);
defer std.process.argsFree(allocator, args);
var memory = try allocator.alloc(u8, memory_size);
_ = try fs.cwd().readFile(args[1], memory);
defer allocator.free(memory);
// registers, 4th register is pc
var r: [4]u16 = .{undefined, undefined, undefined, 0};
var running : bool = true;
while (running) {
running = try cycle(&r, memory);
std.time.sleep(clock_speed);
}
// std.debug.print("registers: {o}, {o}, {o}, {o}\n", .{r[0], r[1], r[2], r[3]});
}
fn cycle(r : *[4]u16, mem : []u8) !bool {
var loc = mem[r[3]];
var do_src_deref : bool = undefined;
var do_dest_deref : bool = undefined;
var src_reg : u2 = undefined;
var dest_reg : u2 = undefined;
var hold : u16 = undefined;
var s_hold : i16 = undefined;
r[3] +|= 1;
// bit patterns for decoding
const op_bits : u8 = 0b1000_0000;
const reverse_bits : u8 = 0b0100_0000;
const src_deref_bits : u8 = 0b0010_0000;
const src_bits : u8 = 0b0001_1000;
const dest_deref_bits : u8 = 0b0000_0100;
const dest_bits : u8 = 0b0000_0011;
src_reg = @truncate(u2, (loc & src_bits) >> 3);
dest_reg = @truncate(u2, loc & dest_bits);
do_src_deref = (loc & src_deref_bits == src_deref_bits);
do_dest_deref = (loc & dest_deref_bits == dest_deref_bits);
var src : u16 = try load(do_src_deref, src_reg, r, mem);
var dest : u16 = try load(do_dest_deref, dest_reg, r, mem);
if (loc & op_bits == 0) { // Sub
if (loc & reverse_bits == 0) { // Sub
hold = dest -% src;
} else { // SubR
hold = @bitReverse(u16, @bitReverse(u16, dest) -% @bitReverse(u16, src));
}
try store(do_dest_deref, hold, dest_reg, r, mem);
} else { // Leq
if (loc & reverse_bits == 0) { // Leq
s_hold = @bitCast(i16, src);
} else { // LeqR
s_hold = @bitReverse(i16, @bitCast(i16, src));
}
if (s_hold <= 0) {
r[3] = dest;
}
if (r[3] >= 0xfffe) {
return false;
}
}
return true;
}
fn load(do_deref : bool, reg : u2, r : *[4]u16, mem : []u8) !u16 {
var temp : u16 = undefined;
if (do_deref) {
if (r[reg] == 0xffff) {
temp = 0;
} else if (r[reg] == 0xfffe) {
temp = try std.io.getStdIn().reader().readByte();
} else {
//std.debug.print("{x}\n", .{mem[r[reg]]});
temp = @intCast(u16, mem[r[reg]]) + (@intCast(u16, mem[r[reg] + 1]) << 8);
}
if (reg == 3) r[reg] +%= 2; // number of bytes loaded
return temp;
} else {
return r[reg];
}
}
fn store(do_deref : bool, value : u16, reg : u2, r : *[4]u16, mem : []u8) !void {
if (do_deref) {
if (r[reg] == 0xffff) {
try std.io.getStdOut().writer().writeByte(@truncate(u8, std.mem.nativeToLittle(u16, value))); // write LSB to stdout
} else {
mem[r[reg]] = @truncate(u8, value);
mem[r[reg] + 1] = @truncate(u8, value >> 8);
}
if (reg == 3) r[reg] +%= 2; // number of bytes loaded
} else {
r[reg] = value;
}
} | emu/src/main.zig |
const c = @cImport({
@cInclude("lauxlib.h");
@cInclude("lua.h");
@cInclude("lundump.h");
@cInclude("lstate.h");
});
const std = @import("std");
const Allocator = std.mem.Allocator;
// need a non-opaque struct definition to get at the `top` field
const lua_State = extern struct {
// common header
next: ?*anyopaque,
tt: u8,
marked: u8,
// lua_State
status: u8,
top: c.StkId,
// rest is irrelevant for our purposes
};
pub fn loadAndDumpAlloc(allocator: Allocator, chunk: [:0]const u8) ![]const u8 {
_ = allocator;
_ = chunk;
var L: *c.lua_State = open: {
break :open c.lua_open() orelse return error.OutOfMemory;
};
defer c.lua_close(L);
const load_result = c.luaL_loadstring(L, chunk.ptr);
switch (load_result) {
0 => {},
c.LUA_ERRSYNTAX => return error.SyntaxError,
c.LUA_ERRMEM => return error.OutOfMemory,
else => unreachable,
}
std.debug.assert(c.lua_type(L, -1) == c.LUA_TFUNCTION);
// get the proto (this should be equivalent to `toproto(L,-1)` in luac.c)
const concrete_state = @ptrCast(*lua_State, @alignCast(8, L));
const first_free_slot_in_stack = concrete_state.top;
const top_of_stack: *c.lua_TValue = first_free_slot_in_stack - 1;
const gc: *c.GCObject = top_of_stack.value.gc;
const proto = gc.cl.l.p;
var output = std.ArrayList(u8).init(allocator);
errdefer output.deinit();
const strip = true;
const dump_result = c.luaU_dump(
L,
proto,
luaWriterArrayList,
&output,
if (strip) 1 else 0,
);
if (dump_result != 0) {
return error.DumpError;
}
return output.toOwnedSlice();
}
fn luaWriterArrayList(
L: ?*c.lua_State,
p: ?*const anyopaque,
sz: usize,
ud: ?*anyopaque,
) callconv(.C) c_int {
_ = L;
var array_list = @ptrCast(*std.ArrayList(u8), @alignCast(@alignOf(*std.ArrayList(u8)), ud.?));
var slice = @ptrCast([*]const u8, p.?)[0..sz];
array_list.appendSlice(slice) catch return 1;
return 0;
}
test {
const allocator = std.testing.allocator;
const bytecode = try loadAndDumpAlloc(allocator, "print \"hello world\"");
defer allocator.free(bytecode);
const expected_bytecode = "\x1bLuaQ\x00\x01\x04\x08\x04\x08\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x02\x04\x00\x00\x00\x05\x00\x00\x00A@\x00\x00\x1c@\x00\x01\x1e\x00\x80\x00\x02\x00\x00\x00\x04\x06\x00\x00\x00\x00\x00\x00\x00print\x00\x04\x0c\x00\x00\x00\x00\x00\x00\x00hello world\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00";
try std.testing.expectEqualSlices(u8, expected_bytecode, bytecode);
} | test/luac.zig |
const std = @import("std");
const day1 = @import("day1.zig");
const day2 = @import("day2.zig");
const day3 = @import("day3.zig");
const day4 = @import("day4.zig");
const day5 = @import("day5.zig");
const day6 = @import("day6.zig");
const day7 = @import("day7.zig");
const day8 = @import("day8.zig");
const day9 = @import("day9.zig");
const day10 = @import("day10.zig");
const day11 = @import("day11.zig");
const SolutionFn = fn ([]const u8) anyerror!u64;
const Solution = struct { part1: SolutionFn, part2: SolutionFn };
pub fn main() anyerror!void {
const solutions = [_]Solution{ .{ .part1 = day1.part1, .part2 = day1.part2 }, .{ .part1 = day2.part1, .part2 = day2.part2 }, .{ .part1 = day3.part1, .part2 = day3.part2 }, .{ .part1 = day4.part1, .part2 = day4.part2 }, .{ .part1 = day5.part1, .part2 = day5.part2 }, .{ .part1 = day6.part1, .part2 = day6.part2 }, .{ .part1 = day7.part1, .part2 = day7.part2 }, .{ .part1 = day8.part1, .part2 = day8.part2 }, .{ .part1 = day9.part1, .part2 = day9.part2 }, .{ .part1 = day10.part1, .part2 = day10.part2 }, .{ .part1 = day11.part1, .part2 = day11.part2 } };
for (solutions) |solution, i| {
const day = i + 1;
const path = try std.fmt.allocPrint(std.heap.page_allocator, "./data/day{}.txt", .{day});
defer std.heap.page_allocator.free(path);
const input = try std.fs.cwd().readFileAlloc(std.heap.page_allocator, path, 1_000_000);
defer std.heap.page_allocator.free(input);
var start: i128 = std.time.nanoTimestamp();
const part1 = try solution.part1(input);
const part1_time = std.time.nanoTimestamp() - start;
start = std.time.nanoTimestamp();
const part2 = try solution.part2(input);
const part2_time = std.time.nanoTimestamp() - start;
std.debug.print("Day {}\n", .{day});
std.debug.print(" Part 1: {} ({} ns)\n", .{ part1, part1_time });
std.debug.print(" Part 2: {} ({} ns)\n", .{ part2, part2_time });
}
}
test "" {
_ = day1;
_ = day2;
_ = day3;
_ = day4;
_ = day5;
_ = day6;
_ = day7;
_ = day8;
_ = day9;
_ = day10;
_ = day11;
} | zig/src/main.zig |
//--------------------------------------------------------------------------------
// Section: Types (28)
//--------------------------------------------------------------------------------
pub const D2D_COLOR_F = extern struct {
r: f32,
g: f32,
b: f32,
a: f32,
};
pub const D2D1_COLOR_F = extern struct {
r: f32,
g: f32,
b: f32,
a: f32,
};
pub const D2D1_ALPHA_MODE = enum(u32) {
UNKNOWN = 0,
PREMULTIPLIED = 1,
STRAIGHT = 2,
IGNORE = 3,
FORCE_DWORD = 4294967295,
};
pub const D2D1_ALPHA_MODE_UNKNOWN = D2D1_ALPHA_MODE.UNKNOWN;
pub const D2D1_ALPHA_MODE_PREMULTIPLIED = D2D1_ALPHA_MODE.PREMULTIPLIED;
pub const D2D1_ALPHA_MODE_STRAIGHT = D2D1_ALPHA_MODE.STRAIGHT;
pub const D2D1_ALPHA_MODE_IGNORE = D2D1_ALPHA_MODE.IGNORE;
pub const D2D1_ALPHA_MODE_FORCE_DWORD = D2D1_ALPHA_MODE.FORCE_DWORD;
pub const D2D1_PIXEL_FORMAT = extern struct {
format: DXGI_FORMAT,
alphaMode: D2D1_ALPHA_MODE,
};
pub const D2D_POINT_2U = extern struct {
x: u32,
y: u32,
};
pub const D2D_POINT_2F = extern struct {
x: f32,
y: f32,
};
pub const D2D_VECTOR_2F = extern struct {
x: f32,
y: f32,
};
pub const D2D_VECTOR_3F = extern struct {
x: f32,
y: f32,
z: f32,
};
pub const D2D_VECTOR_4F = extern struct {
x: f32,
y: f32,
z: f32,
w: f32,
};
pub const D2D_RECT_F = extern struct {
left: f32,
top: f32,
right: f32,
bottom: f32,
};
pub const D2D_RECT_U = extern struct {
left: u32,
top: u32,
right: u32,
bottom: u32,
};
pub const D2D_SIZE_F = extern struct {
width: f32,
height: f32,
};
pub const D2D_SIZE_U = extern struct {
width: u32,
height: u32,
};
pub const D2D_MATRIX_3X2_F = extern struct {
Anonymous: extern union {
Anonymous1: extern struct {
m11: f32,
m12: f32,
m21: f32,
m22: f32,
dx: f32,
dy: f32,
},
Anonymous2: extern struct {
_11: f32,
_12: f32,
_21: f32,
_22: f32,
_31: f32,
_32: f32,
},
m: [6]f32,
},
};
pub const D2D_MATRIX_4X3_F = extern struct {
Anonymous: extern union {
Anonymous: extern struct {
_11: f32,
_12: f32,
_13: f32,
_21: f32,
_22: f32,
_23: f32,
_31: f32,
_32: f32,
_33: f32,
_41: f32,
_42: f32,
_43: f32,
},
m: [12]f32,
},
};
pub const D2D_MATRIX_4X4_F = extern struct {
Anonymous: extern union {
Anonymous: extern struct {
_11: f32,
_12: f32,
_13: f32,
_14: f32,
_21: f32,
_22: f32,
_23: f32,
_24: f32,
_31: f32,
_32: f32,
_33: f32,
_34: f32,
_41: f32,
_42: f32,
_43: f32,
_44: f32,
},
m: [16]f32,
},
};
pub const D2D_MATRIX_5X4_F = extern struct {
Anonymous: extern union {
Anonymous: extern struct {
_11: f32,
_12: f32,
_13: f32,
_14: f32,
_21: f32,
_22: f32,
_23: f32,
_24: f32,
_31: f32,
_32: f32,
_33: f32,
_34: f32,
_41: f32,
_42: f32,
_43: f32,
_44: f32,
_51: f32,
_52: f32,
_53: f32,
_54: f32,
},
m: [20]f32,
},
};
pub const D2D1_FIGURE_BEGIN = enum(u32) {
FILLED = 0,
HOLLOW = 1,
FORCE_DWORD = 4294967295,
};
pub const D2D1_FIGURE_BEGIN_FILLED = D2D1_FIGURE_BEGIN.FILLED;
pub const D2D1_FIGURE_BEGIN_HOLLOW = D2D1_FIGURE_BEGIN.HOLLOW;
pub const D2D1_FIGURE_BEGIN_FORCE_DWORD = D2D1_FIGURE_BEGIN.FORCE_DWORD;
pub const D2D1_FIGURE_END = enum(u32) {
OPEN = 0,
CLOSED = 1,
FORCE_DWORD = 4294967295,
};
pub const D2D1_FIGURE_END_OPEN = D2D1_FIGURE_END.OPEN;
pub const D2D1_FIGURE_END_CLOSED = D2D1_FIGURE_END.CLOSED;
pub const D2D1_FIGURE_END_FORCE_DWORD = D2D1_FIGURE_END.FORCE_DWORD;
pub const D2D1_BEZIER_SEGMENT = extern struct {
point1: D2D_POINT_2F,
point2: D2D_POINT_2F,
point3: D2D_POINT_2F,
};
pub const D2D1_PATH_SEGMENT = enum(u32) {
NONE = 0,
FORCE_UNSTROKED = 1,
FORCE_ROUND_LINE_JOIN = 2,
FORCE_DWORD = 4294967295,
_,
pub fn initFlags(o: struct {
NONE: u1 = 0,
FORCE_UNSTROKED: u1 = 0,
FORCE_ROUND_LINE_JOIN: u1 = 0,
FORCE_DWORD: u1 = 0,
}) D2D1_PATH_SEGMENT {
return @intToEnum(D2D1_PATH_SEGMENT,
(if (o.NONE == 1) @enumToInt(D2D1_PATH_SEGMENT.NONE) else 0)
| (if (o.FORCE_UNSTROKED == 1) @enumToInt(D2D1_PATH_SEGMENT.FORCE_UNSTROKED) else 0)
| (if (o.FORCE_ROUND_LINE_JOIN == 1) @enumToInt(D2D1_PATH_SEGMENT.FORCE_ROUND_LINE_JOIN) else 0)
| (if (o.FORCE_DWORD == 1) @enumToInt(D2D1_PATH_SEGMENT.FORCE_DWORD) else 0)
);
}
};
pub const D2D1_PATH_SEGMENT_NONE = D2D1_PATH_SEGMENT.NONE;
pub const D2D1_PATH_SEGMENT_FORCE_UNSTROKED = D2D1_PATH_SEGMENT.FORCE_UNSTROKED;
pub const D2D1_PATH_SEGMENT_FORCE_ROUND_LINE_JOIN = D2D1_PATH_SEGMENT.FORCE_ROUND_LINE_JOIN;
pub const D2D1_PATH_SEGMENT_FORCE_DWORD = D2D1_PATH_SEGMENT.FORCE_DWORD;
pub const D2D1_FILL_MODE = enum(u32) {
ALTERNATE = 0,
WINDING = 1,
FORCE_DWORD = 4294967295,
};
pub const D2D1_FILL_MODE_ALTERNATE = D2D1_FILL_MODE.ALTERNATE;
pub const D2D1_FILL_MODE_WINDING = D2D1_FILL_MODE.WINDING;
pub const D2D1_FILL_MODE_FORCE_DWORD = D2D1_FILL_MODE.FORCE_DWORD;
// TODO: this type is limited to platform 'windows6.1'
const IID_ID2D1SimplifiedGeometrySink_Value = Guid.initString("2cd9069e-12e2-11dc-9fed-001143a055f9");
pub const IID_ID2D1SimplifiedGeometrySink = &IID_ID2D1SimplifiedGeometrySink_Value;
pub const ID2D1SimplifiedGeometrySink = extern struct {
pub const VTable = extern struct {
base: IUnknown.VTable,
SetFillMode: fn(
self: *const ID2D1SimplifiedGeometrySink,
fillMode: D2D1_FILL_MODE,
) callconv(@import("std").os.windows.WINAPI) void,
SetSegmentFlags: fn(
self: *const ID2D1SimplifiedGeometrySink,
vertexFlags: D2D1_PATH_SEGMENT,
) callconv(@import("std").os.windows.WINAPI) void,
BeginFigure: fn(
self: *const ID2D1SimplifiedGeometrySink,
startPoint: D2D_POINT_2F,
figureBegin: D2D1_FIGURE_BEGIN,
) callconv(@import("std").os.windows.WINAPI) void,
AddLines: fn(
self: *const ID2D1SimplifiedGeometrySink,
points: [*]const D2D_POINT_2F,
pointsCount: u32,
) callconv(@import("std").os.windows.WINAPI) void,
AddBeziers: fn(
self: *const ID2D1SimplifiedGeometrySink,
beziers: [*]const D2D1_BEZIER_SEGMENT,
beziersCount: u32,
) callconv(@import("std").os.windows.WINAPI) void,
EndFigure: fn(
self: *const ID2D1SimplifiedGeometrySink,
figureEnd: D2D1_FIGURE_END,
) callconv(@import("std").os.windows.WINAPI) void,
Close: fn(
self: *const ID2D1SimplifiedGeometrySink,
) callconv(@import("std").os.windows.WINAPI) HRESULT,
};
vtable: *const VTable,
pub fn MethodMixin(comptime T: type) type { return struct {
pub usingnamespace IUnknown.MethodMixin(T);
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_SetFillMode(self: *const T, fillMode: D2D1_FILL_MODE) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).SetFillMode(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), fillMode);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_SetSegmentFlags(self: *const T, vertexFlags: D2D1_PATH_SEGMENT) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).SetSegmentFlags(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), vertexFlags);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_BeginFigure(self: *const T, startPoint: D2D_POINT_2F, figureBegin: D2D1_FIGURE_BEGIN) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).BeginFigure(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), startPoint, figureBegin);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_AddLines(self: *const T, points: [*]const D2D_POINT_2F, pointsCount: u32) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).AddLines(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), points, pointsCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_AddBeziers(self: *const T, beziers: [*]const D2D1_BEZIER_SEGMENT, beziersCount: u32) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).AddBeziers(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), beziers, beziersCount);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_EndFigure(self: *const T, figureEnd: D2D1_FIGURE_END) callconv(.Inline) void {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).EndFigure(@ptrCast(*const ID2D1SimplifiedGeometrySink, self), figureEnd);
}
// NOTE: method is namespaced with interface name to avoid conflicts for now
pub fn ID2D1SimplifiedGeometrySink_Close(self: *const T) callconv(.Inline) HRESULT {
return @ptrCast(*const ID2D1SimplifiedGeometrySink.VTable, self.vtable).Close(@ptrCast(*const ID2D1SimplifiedGeometrySink, self));
}
};}
pub usingnamespace MethodMixin(@This());
};
pub const D2D1_BORDER_MODE = enum(u32) {
SOFT = 0,
HARD = 1,
FORCE_DWORD = 4294967295,
};
pub const D2D1_BORDER_MODE_SOFT = D2D1_BORDER_MODE.SOFT;
pub const D2D1_BORDER_MODE_HARD = D2D1_BORDER_MODE.HARD;
pub const D2D1_BORDER_MODE_FORCE_DWORD = D2D1_BORDER_MODE.FORCE_DWORD;
pub const D2D1_BLEND_MODE = enum(u32) {
MULTIPLY = 0,
SCREEN = 1,
DARKEN = 2,
LIGHTEN = 3,
DISSOLVE = 4,
COLOR_BURN = 5,
LINEAR_BURN = 6,
DARKER_COLOR = 7,
LIGHTER_COLOR = 8,
COLOR_DODGE = 9,
LINEAR_DODGE = 10,
OVERLAY = 11,
SOFT_LIGHT = 12,
HARD_LIGHT = 13,
VIVID_LIGHT = 14,
LINEAR_LIGHT = 15,
PIN_LIGHT = 16,
HARD_MIX = 17,
DIFFERENCE = 18,
EXCLUSION = 19,
HUE = 20,
SATURATION = 21,
COLOR = 22,
LUMINOSITY = 23,
SUBTRACT = 24,
DIVISION = 25,
FORCE_DWORD = 4294967295,
};
pub const D2D1_BLEND_MODE_MULTIPLY = D2D1_BLEND_MODE.MULTIPLY;
pub const D2D1_BLEND_MODE_SCREEN = D2D1_BLEND_MODE.SCREEN;
pub const D2D1_BLEND_MODE_DARKEN = D2D1_BLEND_MODE.DARKEN;
pub const D2D1_BLEND_MODE_LIGHTEN = D2D1_BLEND_MODE.LIGHTEN;
pub const D2D1_BLEND_MODE_DISSOLVE = D2D1_BLEND_MODE.DISSOLVE;
pub const D2D1_BLEND_MODE_COLOR_BURN = D2D1_BLEND_MODE.COLOR_BURN;
pub const D2D1_BLEND_MODE_LINEAR_BURN = D2D1_BLEND_MODE.LINEAR_BURN;
pub const D2D1_BLEND_MODE_DARKER_COLOR = D2D1_BLEND_MODE.DARKER_COLOR;
pub const D2D1_BLEND_MODE_LIGHTER_COLOR = D2D1_BLEND_MODE.LIGHTER_COLOR;
pub const D2D1_BLEND_MODE_COLOR_DODGE = D2D1_BLEND_MODE.COLOR_DODGE;
pub const D2D1_BLEND_MODE_LINEAR_DODGE = D2D1_BLEND_MODE.LINEAR_DODGE;
pub const D2D1_BLEND_MODE_OVERLAY = D2D1_BLEND_MODE.OVERLAY;
pub const D2D1_BLEND_MODE_SOFT_LIGHT = D2D1_BLEND_MODE.SOFT_LIGHT;
pub const D2D1_BLEND_MODE_HARD_LIGHT = D2D1_BLEND_MODE.HARD_LIGHT;
pub const D2D1_BLEND_MODE_VIVID_LIGHT = D2D1_BLEND_MODE.VIVID_LIGHT;
pub const D2D1_BLEND_MODE_LINEAR_LIGHT = D2D1_BLEND_MODE.LINEAR_LIGHT;
pub const D2D1_BLEND_MODE_PIN_LIGHT = D2D1_BLEND_MODE.PIN_LIGHT;
pub const D2D1_BLEND_MODE_HARD_MIX = D2D1_BLEND_MODE.HARD_MIX;
pub const D2D1_BLEND_MODE_DIFFERENCE = D2D1_BLEND_MODE.DIFFERENCE;
pub const D2D1_BLEND_MODE_EXCLUSION = D2D1_BLEND_MODE.EXCLUSION;
pub const D2D1_BLEND_MODE_HUE = D2D1_BLEND_MODE.HUE;
pub const D2D1_BLEND_MODE_SATURATION = D2D1_BLEND_MODE.SATURATION;
pub const D2D1_BLEND_MODE_COLOR = D2D1_BLEND_MODE.COLOR;
pub const D2D1_BLEND_MODE_LUMINOSITY = D2D1_BLEND_MODE.LUMINOSITY;
pub const D2D1_BLEND_MODE_SUBTRACT = D2D1_BLEND_MODE.SUBTRACT;
pub const D2D1_BLEND_MODE_DIVISION = D2D1_BLEND_MODE.DIVISION;
pub const D2D1_BLEND_MODE_FORCE_DWORD = D2D1_BLEND_MODE.FORCE_DWORD;
pub const D2D1_COLORMATRIX_ALPHA_MODE = enum(u32) {
PREMULTIPLIED = 1,
STRAIGHT = 2,
FORCE_DWORD = 4294967295,
};
pub const D2D1_COLORMATRIX_ALPHA_MODE_PREMULTIPLIED = D2D1_COLORMATRIX_ALPHA_MODE.PREMULTIPLIED;
pub const D2D1_COLORMATRIX_ALPHA_MODE_STRAIGHT = D2D1_COLORMATRIX_ALPHA_MODE.STRAIGHT;
pub const D2D1_COLORMATRIX_ALPHA_MODE_FORCE_DWORD = D2D1_COLORMATRIX_ALPHA_MODE.FORCE_DWORD;
pub const D2D1_TURBULENCE_NOISE = enum(u32) {
FRACTAL_SUM = 0,
TURBULENCE = 1,
FORCE_DWORD = 4294967295,
};
pub const D2D1_TURBULENCE_NOISE_FRACTAL_SUM = D2D1_TURBULENCE_NOISE.FRACTAL_SUM;
pub const D2D1_TURBULENCE_NOISE_TURBULENCE = D2D1_TURBULENCE_NOISE.TURBULENCE;
pub const D2D1_TURBULENCE_NOISE_FORCE_DWORD = D2D1_TURBULENCE_NOISE.FORCE_DWORD;
pub const D2D1_COMPOSITE_MODE = enum(u32) {
SOURCE_OVER = 0,
DESTINATION_OVER = 1,
SOURCE_IN = 2,
DESTINATION_IN = 3,
SOURCE_OUT = 4,
DESTINATION_OUT = 5,
SOURCE_ATOP = 6,
DESTINATION_ATOP = 7,
XOR = 8,
PLUS = 9,
SOURCE_COPY = 10,
BOUNDED_SOURCE_COPY = 11,
MASK_INVERT = 12,
FORCE_DWORD = 4294967295,
};
pub const D2D1_COMPOSITE_MODE_SOURCE_OVER = D2D1_COMPOSITE_MODE.SOURCE_OVER;
pub const D2D1_COMPOSITE_MODE_DESTINATION_OVER = D2D1_COMPOSITE_MODE.DESTINATION_OVER;
pub const D2D1_COMPOSITE_MODE_SOURCE_IN = D2D1_COMPOSITE_MODE.SOURCE_IN;
pub const D2D1_COMPOSITE_MODE_DESTINATION_IN = D2D1_COMPOSITE_MODE.DESTINATION_IN;
pub const D2D1_COMPOSITE_MODE_SOURCE_OUT = D2D1_COMPOSITE_MODE.SOURCE_OUT;
pub const D2D1_COMPOSITE_MODE_DESTINATION_OUT = D2D1_COMPOSITE_MODE.DESTINATION_OUT;
pub const D2D1_COMPOSITE_MODE_SOURCE_ATOP = D2D1_COMPOSITE_MODE.SOURCE_ATOP;
pub const D2D1_COMPOSITE_MODE_DESTINATION_ATOP = D2D1_COMPOSITE_MODE.DESTINATION_ATOP;
pub const D2D1_COMPOSITE_MODE_XOR = D2D1_COMPOSITE_MODE.XOR;
pub const D2D1_COMPOSITE_MODE_PLUS = D2D1_COMPOSITE_MODE.PLUS;
pub const D2D1_COMPOSITE_MODE_SOURCE_COPY = D2D1_COMPOSITE_MODE.SOURCE_COPY;
pub const D2D1_COMPOSITE_MODE_BOUNDED_SOURCE_COPY = D2D1_COMPOSITE_MODE.BOUNDED_SOURCE_COPY;
pub const D2D1_COMPOSITE_MODE_MASK_INVERT = D2D1_COMPOSITE_MODE.MASK_INVERT;
pub const D2D1_COMPOSITE_MODE_FORCE_DWORD = D2D1_COMPOSITE_MODE.FORCE_DWORD;
//--------------------------------------------------------------------------------
// Section: Functions (0)
//--------------------------------------------------------------------------------
//--------------------------------------------------------------------------------
// Section: Unicode Aliases (0)
//--------------------------------------------------------------------------------
const thismodule = @This();
pub usingnamespace switch (@import("../../zig.zig").unicode_mode) {
.ansi => struct {
},
.wide => struct {
},
.unspecified => if (@import("builtin").is_test) struct {
} else struct {
},
};
//--------------------------------------------------------------------------------
// Section: Imports (4)
//--------------------------------------------------------------------------------
const Guid = @import("../../zig.zig").Guid;
const DXGI_FORMAT = @import("../../graphics/dxgi/common.zig").DXGI_FORMAT;
const HRESULT = @import("../../foundation.zig").HRESULT;
const IUnknown = @import("../../system/com.zig").IUnknown;
test {
@setEvalBranchQuota(
@import("std").meta.declarations(@This()).len * 3
);
// reference all the pub declarations
if (!@import("builtin").is_test) return;
inline for (@import("std").meta.declarations(@This())) |decl| {
if (decl.is_pub) {
_ = decl;
}
}
} | win32/graphics/direct2d/common.zig |
const std = @import( "std" );
const min = std.math.min;
const maxInt = std.math.maxInt;
pub usingnamespace @import( "c.zig" );
usingnamespace @import( "util.zig" );
pub const GlzError = error {
GenericFailure,
};
pub fn glzBufferData( target: GLenum, comptime T: type, values: []const T, usage: GLenum ) void {
if ( values.len > 0 ) {
const maxCount = @divTrunc( maxInt( GLsizeiptr ), @sizeOf( T ) );
if ( values.len > maxCount ) {
std.debug.warn( "Pushing fewer values than requested to device: requested = {d}, allowed = {d}\n", .{ values.len, maxCount } );
}
const actualCount = min( values.len, maxCount );
const bytesCount = @intCast( GLsizeiptr, actualCount * @sizeOf( T ) );
const bytesPtr = @ptrCast( *const c_void, values.ptr );
glBufferData( target, bytesCount, bytesPtr, usage );
}
else {
// FIXME: glBufferData with null?
}
}
pub fn glzCreateProgram( vertSource: [*:0]const u8, fragSource: [*:0]const u8 ) !GLuint {
const vertShader = try glzCompileShaderSource( GL_VERTEX_SHADER, vertSource );
defer glDeleteShader( vertShader );
const fragShader = try glzCompileShaderSource( GL_FRAGMENT_SHADER, fragSource );
defer glDeleteShader( fragShader );
const program = glCreateProgram( );
glAttachShader( program, vertShader );
defer glDetachShader( program, vertShader );
glAttachShader( program, fragShader );
defer glDetachShader( program, fragShader );
glLinkProgram( program );
var linkStatus: GLint = 0;
glGetProgramiv( program, GL_LINK_STATUS, &linkStatus );
if ( linkStatus != GL_TRUE ) {
var messageSize: GLint = undefined;
glGetProgramiv( program, GL_INFO_LOG_LENGTH, &messageSize );
const allocator = std.heap.c_allocator;
const message = try allocator.alloc( u8, @intCast( usize, messageSize ) );
defer allocator.free( message );
glGetProgramInfoLog( program, messageSize, null, message.ptr );
std.debug.warn( "Shader linking failed:\n{s}\n", .{ message } );
// TODO: Make message available to caller
return GlzError.GenericFailure;
}
return program;
}
pub fn glzCompileShaderSource( shaderType: GLenum, source: [*:0]const u8 ) !GLuint {
const shader = glCreateShader( shaderType );
glShaderSource( shader, 1, &source, null );
glCompileShader( shader );
var compileStatus: GLint = 0;
glGetShaderiv( shader, GL_COMPILE_STATUS, &compileStatus );
if ( compileStatus != GL_TRUE ) {
var messageSize: GLint = undefined;
glGetShaderiv( shader, GL_INFO_LOG_LENGTH, &messageSize );
const allocator = std.heap.c_allocator;
const message = try allocator.alloc( u8, @intCast( usize, messageSize ) );
defer allocator.free( message );
glGetShaderInfoLog( shader, messageSize, null, message.ptr );
std.debug.warn( "Shader compilation failed:\n{s}\n", .{ message } );
// TODO: Make message available to caller
return GlzError.GenericFailure;
}
return shader;
}
pub fn glzEnablePremultipliedAlphaBlending( ) void {
glBlendEquation( GL_FUNC_ADD );
glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
glEnable( GL_BLEND );
}
pub fn glzDisableBlending( ) void {
glDisable( GL_BLEND );
}
pub fn glzHasCurrentContext( ) bool {
var major: GLint = -1;
glGetIntegerv( GL_MAJOR_VERSION, &major );
return ( major != -1 );
}
pub fn glzUniformInterval1( location: GLint, interval: Interval ) void {
glUniform2f( location,
@floatCast( f32, interval.start ),
@floatCast( f32, interval.span ) );
}
pub fn glzUniformInterval2( location: GLint, interval: [2]Interval ) void {
glUniform4f( location,
@floatCast( f32, interval[0].start ),
@floatCast( f32, interval[1].start ),
@floatCast( f32, interval[0].span ),
@floatCast( f32, interval[1].span ) );
}
pub fn glzGetViewport_PX( ) [2]Interval {
var viewport_PX: [4]GLint = [_]GLint{ -1, -1, -1, -1 };
glGetIntegerv( GL_VIEWPORT, &viewport_PX );
const x = @intToFloat( f64, viewport_PX[0] );
const y = @intToFloat( f64, viewport_PX[1] );
const w = @intToFloat( f64, viewport_PX[2] );
const h = @intToFloat( f64, viewport_PX[3] );
return [_]Interval {
Interval.init( x, w ),
Interval.init( y, h ),
};
} | src/core/glz.zig |
const std = @import("std");
const assert = std.debug.assert;
const tools = @import("tools");
pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 {
//[1518-07-10 23:54] Guard #3167 begins shift
//[1518-04-15 00:20] falls asleep
//[1518-09-30 00:49] wakes up
const Shift = struct {
guardId: ?u32,
tomorrowGuardId: ?u32,
state: [60]bool,
};
var shifts = [1]?Shift{null} ** (31 * 12);
var largestGuardId: ?u32 = null;
{
var it = std.mem.tokenize(u8, input, "\n\r");
while (it.next()) |line| {
var time: []const u8 = undefined;
var awake: bool = undefined;
var guardId: ?u32 = null;
if (tools.match_pattern("[{}] wakes up", line)) |fields| {
time = fields[0].lit;
awake = true;
} else if (tools.match_pattern("[{}] falls asleep", line)) |fields| {
time = fields[0].lit;
awake = false;
} else if (tools.match_pattern("[{}] Guard #{} begins shift", line)) |fields| {
time = fields[0].lit;
guardId = @intCast(u32, fields[1].imm);
} else {
std.debug.print("could not parse '{s}'\n", .{line});
return error.UnsupportedInput;
}
const fields = tools.match_pattern("1518-{}-{} {}:{}", time) orelse unreachable;
const month = @intCast(u32, fields[0].imm);
const day = @intCast(u32, fields[1].imm);
const hour = @intCast(u32, fields[2].imm);
const minutes = @intCast(u32, fields[3].imm);
// std.debug.print("shift: guard={} day={}-{} mn={}\n", .{ guardId.?, month, day, minutes });
if (shifts[month * 31 + day] == null) { // new day?
shifts[month * 31 + day] = Shift{ .guardId = null, .state = [_]bool{true} ** 60, .tomorrowGuardId = null };
}
const shift = &shifts[month * 31 + day].?;
if (guardId) |id| {
if (largestGuardId == null or largestGuardId.? < guardId.?)
largestGuardId = guardId;
if (hour > 12) {
assert(shift.tomorrowGuardId == null);
shift.tomorrowGuardId = id;
} else {
assert(shift.guardId == null);
shift.guardId = id;
}
} else {
// suppose que les données sont cohérentes (ie commence reveillé et de ne reveille pas deux fois de suite, mais desordonéees)
var i = minutes;
while (i < 60) : (i += 1) {
shift.state[i] = !shift.state[i];
}
}
}
// ajustement: met les guardes arrivés en avance sur les bons jours
var lastGuardId: ?u32 = null;
for (shifts) |_, i| {
if (shifts[i]) |*s| {
if (s.guardId == null) {
s.guardId = lastGuardId;
}
if (s.tomorrowGuardId != null) {
lastGuardId = s.tomorrowGuardId;
s.tomorrowGuardId = null;
} else {
lastGuardId = s.guardId;
}
assert(lastGuardId != null);
}
}
}
// part1
const ans1 = ans: {
const guardIdMostAsleep = mostasleep: {
const sleepTimes = try allocator.alloc(u32, largestGuardId.? + 1);
defer allocator.free(sleepTimes);
std.mem.set(u32, sleepTimes, 0);
for (shifts) |shift| {
if (shift) |s| {
for (s.state) |awake| {
if (!awake)
sleepTimes[s.guardId.?] += 1;
}
}
}
var id: usize = undefined;
var longuest: u32 = 0;
for (sleepTimes) |time, i| {
if (time > longuest) {
longuest = time;
id = i;
}
}
assert(longuest > 0);
break :mostasleep id;
};
const minuteMostAsleep = mostasleep: {
var counts = [1]u32{0} ** 60;
for (shifts) |shift| {
if (shift == null or shift.?.guardId.? != guardIdMostAsleep)
continue;
for (shift.?.state) |awake, i| {
if (!awake) counts[i] += 1;
}
}
var best: usize = undefined;
var best_count: u32 = 0;
for (counts) |c, i| {
if (c > best_count) {
best_count = c;
best = i;
}
}
assert(best_count > 0);
break :mostasleep best;
};
break :ans guardIdMostAsleep * minuteMostAsleep;
};
// part2
//var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
//defer arena.deinit();
const ans2 = ans: {
const sleepMinutes = try allocator.alloc([60]u16, (largestGuardId.? + 1));
defer allocator.free(sleepMinutes);
std.mem.set([60]u16, sleepMinutes, [1]u16{0} ** 60);
for (shifts) |shift| {
if (shift) |s| {
for (s.state) |awake, i| {
if (!awake) {
sleepMinutes[s.guardId.?][i] += 1;
}
}
}
}
var bestGuardId: usize = undefined;
var bestMinute: usize = undefined;
var bestNum: u16 = 0;
for (sleepMinutes) |sm, guardId| {
for (sm) |num, minute| {
if (num > bestNum) {
bestNum = num;
bestGuardId = guardId;
bestMinute = minute;
}
}
}
break :ans bestMinute * bestGuardId;
};
return [_][]const u8{
try std.fmt.allocPrint(allocator, "{}", .{ans1}),
try std.fmt.allocPrint(allocator, "{}", .{ans2}),
};
}
pub const main = tools.defaultMain("2018/input_day04.txt", run); | 2018/day04.zig |
const std = @import("std");
const zlm = @import("zlm");
const Piece = @import("piece.zig").Piece;
const ROM = @import("../rom.zig").ROM;
const ROMView = @import("../rom.zig").ROMView;
/// The material (color/texture) of a shape.
const Material = struct {
param: u8,
cmd: u8,
};
/// The data common to all shapes.
const ShapeData = struct {
material: Material,
normal: zlm.Vec3,
};
pub const TextureSpec = struct {
pub const Page = enum { left, right };
rom: ROM,
page: Page,
start: u8,
width: u2,
height: u2,
address: u24,
reversed: bool,
fn dim(comptime char: u8) u2 {
return switch (char) {
'1' => 0,
'2' => 1,
'4' => 2,
'8' => 3,
else => @compileError("invalid dimension"),
};
}
fn init(comptime str: []const u8, rom: ROM) TextureSpec {
comptime const width = dim(str[0]);
comptime std.debug.assert(str[1] == 'x');
comptime const height = dim(str[2]);
comptime const page: Page = switch (str[3]) {
'l' => .left,
'r' => .right,
else => @compileError("invalid page"),
};
comptime const reversed = if (str.len == 5) blk: {
comptime std.debug.assert(str[4] == 'f');
break :blk true;
} else blk: {
comptime std.debug.assert(str.len == 4);
break :blk false;
};
return .{
.rom = rom,
.page = page,
.start = undefined,
.width = width,
.height = height,
.address = undefined,
.reversed = reversed,
};
}
fn initKnown(comptime str: []const u8, rom: ROM, start: u8, address: u24) TextureSpec {
var result = init(str, rom);
result.start = start;
result.address = address;
return result;
}
};
const sine_table = blk: {
var result: [256]i16 = undefined;
for (result) |*p, i| {
p.* = @floatToInt(i16, @sin((@intToFloat(f32, i) / 256) * 2.0 * std.math.pi) * 16384);
}
break :blk result;
};
fn convertPoint(x: i16, y: i16, z: i16) zlm.Vec3 {
return zlm.vec3(
@intToFloat(f32, x) / 256,
@intToFloat(f32, y) / -256,
@intToFloat(f32, z) / 256,
);
}
/// A utility struct to render pieces.
pub fn PieceRenderer(comptime Writer: type) type {
return struct {
/// The piece to render.
piece: Piece,
/// The ROM to read from.
rom: ROM,
/// The view we're currently reading data from.
view: ROMView,
/// The scale of the piece's model.
scale: u4,
/// The pointer to the palette of this piece's model.
palette_ptr: u16,
/// The frame to select vertices from, if animated.
frame: u8,
/// The writer to render to, used by drawShapes.
writer: Writer,
pub fn init(piece: Piece, rom: ROM, writer: Writer, frame: u8) !@This() {
var model_view = rom.view(piece.model_id);
const model_ptr = try model_view.reader().readIntLittle(u24);
model_view.pos += 4;
const scale = try std.math.cast(u4, try model_view.reader().readByte());
model_view.pos += 10;
const palette_ptr = try model_view.reader().readIntLittle(u16);
return @This(){
.piece = piece,
.rom = rom,
.view = rom.view(model_ptr),
.scale = scale,
.palette_ptr = palette_ptr,
.writer = writer,
.frame = frame,
};
}
pub fn go(self: *@This()) !void {
try self.loadPoints();
try self.drawShapes();
}
fn createMaterial(self: *@This()) !Material {
const id = try self.view.reader().readByte();
var view = self.rom.view((0x30000 | @as(u24, self.palette_ptr)) + @as(u24, id) * 2);
return Material{
.param = try view.reader().readByte(),
.cmd = try view.reader().readByte(),
};
}
fn getColorIds(self: @This(), mat: Material) ![10]u8 {
// TODO figure out how many light-sourced colors there are... highest one in-game is $15 but maybe there's some unused...
// TODO look for these pointers
if (mat.cmd < 0x3E) {
// shaded color
return try self.rom.view(0x3A765 + 10 * @as(u24, mat.param)).reader().readBytesNoEof(10);
} else if (mat.cmd == 0x3E) {
// solid color
const color = try self.rom.view(0x3A325 + @as(u24, mat.param)).reader().readByte();
return [_]u8{ color, color, color, color, color, color, color, color, color, color };
} else {
// not a color, likely a broken model
return error.NotAColor;
}
}
fn calcTexture(self: @This(), id: u8, spec: TextureSpec) !TextureSpec {
// TODO are these addresses anywhere in the rom?
var spec_copy = spec;
spec_copy.address = try self.rom.view(0x39D59 + @as(u24, id) * 3).reader().readIntLittle(u24);
spec_copy.start = try self.rom.view(0x39FB1 + @as(u24, id)).reader().readByte();
return spec_copy;
}
fn getTextureSpec(self: @This(), mat: Material) !TextureSpec {
return switch (mat.cmd) {
0x40 => try self.calcTexture(mat.param, TextureSpec.init("2x2l", self.rom)),
0x48 => try self.calcTexture(mat.param, TextureSpec.init("2x2lf", self.rom)),
0x4A => try self.calcTexture(mat.param, TextureSpec.init("4x2l", self.rom)),
0x60 => try self.calcTexture(mat.param, TextureSpec.init("2x2r", self.rom)),
0x68 => try self.calcTexture(mat.param, TextureSpec.init("2x2rf", self.rom)),
0x70 => try self.calcTexture(mat.param, TextureSpec.init("8x1rf", self.rom)),
// This texture is a special one designed to reverse on each render, only used by
// the audience. It appears that the parameter is unused. TODO test that in the debugger
// TODO when we add animations and stuff like that make it actually flip like in-game
0x99 => TextureSpec.initKnown("4x2l", self.rom, 0x10, 0x13E020),
0x9b => try self.getSignTextureFromCodePointer(),
else => error.NotATexture,
};
}
// to reduce the number of models, road signs with different decals share the same model, and their
// texture pointer is determined based on a subroutine.
fn getSignTextureFromCodePointer(self: @This()) !TextureSpec {
// TODO i'll un-hardcode this when i figure out the deeper workings of this code
return switch (self.piece.code_pointer) {
// u-turn left
0x9C5B6 => TextureSpec.initKnown("2x2r", self.rom, 0x10, 0x12C0A0),
// u-turn right
0x9C5BF => TextureSpec.initKnown("2x2rf", self.rom, 0x10, 0x12C0A0),
// 90-degree turn left
0x9C5C8 => TextureSpec.initKnown("2x2r", self.rom, 0x10, 0x12C0E0),
// 90-degree turn right
0x9C5D1 => TextureSpec.initKnown("2x2rf", self.rom, 0x10, 0x12C0E0),
// zig-zag right
0x9C5DA => TextureSpec.initKnown("2x2r", self.rom, 0x10, 0x12C0C0),
// zig-zag left
0x9C5E3 => TextureSpec.initKnown("2x2rf", self.rom, 0x10, 0x12C0C0),
// rock slide
0x9C5EC => TextureSpec.initKnown("2x2l", self.rom, 0x10, 0x13A0C0),
// mule crossing
0x9C5F5 => TextureSpec.initKnown("2x2l", self.rom, 0x10, 0x13A0E0),
// no clue
else => error.UnknownSignTexture,
};
}
fn readPoint(self: *@This()) !zlm.Vec3 {
return convertPoint(
try self.view.reader().readByteSigned(),
try self.view.reader().readByteSigned(),
try self.view.reader().readByteSigned(),
);
}
fn rotatePoint(self: @This(), point: zlm.Vec3) zlm.Vec3 {
// find angle of rotation
const s = @intToFloat(f32, sine_table[self.piece.dir]) / 16384;
const c = @intToFloat(f32, sine_table[self.piece.dir +% 0x40]) / 16384;
// rotate point
return zlm.vec3(point.x * c - point.z * s, point.y, point.x * s + point.z * c);
}
fn transformPoint(self: @This(), point: zlm.Vec3) zlm.Vec3 {
const scaled_point = point.scale(@intToFloat(f32, @as(u32, 1) << self.scale));
const rotated_point = self.rotatePoint(scaled_point);
return rotated_point.add(convertPoint(
self.piece.x,
self.piece.y,
self.piece.z,
));
}
fn jump(self: *@This()) !void {
const amt = try self.view.reader().readIntLittle(u16);
self.view.pos += amt;
self.view.pos -= 1;
}
fn loadPoints(self: *@This()) !void {
const reader = self.view.reader();
while (true) {
switch (try reader.readByte()) {
// standard list
0x04 => {
const count = try reader.readByte();
var i: u8 = 0;
while (i < count) : (i += 1) {
try self.writer.addPoint(self.transformPoint(try self.readPoint()));
}
},
// mirrored list
0x38 => {
const count = try reader.readByte();
var i: u8 = 0;
while (i < count) : (i += 1) {
var p = try self.readPoint();
try self.writer.addPoint(self.transformPoint(p));
p.x = -p.x;
try self.writer.addPoint(self.transformPoint(p));
}
},
// keyframe table
0x1C => {
if (self.frame >= try reader.readByte()) {
return error.FrameOutOfBounds;
}
self.view.pos += 2 * @as(u16, self.frame);
try self.jump();
},
// keyframe break
0x20 => try self.jump(),
// end of vertex list
0x0C => break,
// that should be it
else => return error.UnrecognizedVertexCommand,
}
}
}
fn getNormal(self: *@This()) !zlm.Vec3 {
return (try self.readPoint()).normalize();
}
fn getShapeData(self: *@This()) !ShapeData {
// skip bytes we don't understand yet/don't use
self.view.pos += 2;
const material = try self.createMaterial();
const normal = try self.getNormal();
return ShapeData{
.material = material,
.normal = normal,
};
}
fn addLine(self: *@This(), points: [2]u8, shape_data: ShapeData) !void {
const colors = try self.getColorIds(shape_data.material);
try self.writer.drawLine(points, shape_data.normal, colors);
}
fn addTri(self: *@This(), points: [3]u8, shape_data: ShapeData, texture_allowed: bool) !void {
// some tris are textured (see: the water road in harbor city)
if (texture_allowed) {
if (self.getTextureSpec(shape_data.material)) |spec| {
try self.writer.drawTexturedTri(points, shape_data.normal, spec, .{0, 1, 2});
return;
} else |err| {
if (err != error.NotATexture) return err;
}
}
const colors = try self.getColorIds(shape_data.material);
try self.writer.drawTri(points, shape_data.normal, colors);
}
fn addQuad(self: *@This(), points: [4]u8, shape_data: ShapeData) !void {
var vertices: [6]usize = undefined;
if (self.getTextureSpec(shape_data.material)) |spec| {
try self.writer.drawTexturedTri(points[0..3].*, shape_data.normal, spec, .{0, 1, 2});
try self.writer.drawTexturedTri(.{points[0], points[2], points[3]}, shape_data.normal, spec, .{0, 2, 3});
} else |err| switch (err) {
error.NotATexture => {
const colors = try self.getColorIds(shape_data.material);
try self.writer.drawTri(points[0..3].*, shape_data.normal, colors);
try self.writer.drawTri(.{points[0], points[2], points[3]}, shape_data.normal, colors);
},
else => return err,
}
}
fn drawShapes(self: *@This()) !void {
const reader = self.view.reader();
while (true) {
switch (try reader.readByte()) {
// end of list
0 => break,
// line
2 => {
const shape_data = try self.getShapeData();
const points = try reader.readBytesNoEof(2);
try self.addLine(points, shape_data);
},
// tri
3 => {
const shape_data = try self.getShapeData();
const points = try reader.readBytesNoEof(3);
try self.addTri(points, shape_data, true);
},
// quad
4 => {
const shape_data = try self.getShapeData();
const points = try reader.readBytesNoEof(4);
try self.addQuad(points, shape_data);
},
// n-gon
5...8 => |count| {
const shape_data = try self.getShapeData();
// render an n-gon using a triangle fan
// first point in each triangle is the first point of the polygon
// second and third are shifted along among the rest
var points: [3]u8 = undefined;
points[0] = try reader.readByte();
points[2] = try reader.readByte();
var i: u8 = 0;
while (i < count - 2) : (i += 1) {
points[1] = points[2];
points[2] = try reader.readByte();
// TODO experiment with textured n-gons, see how the game reacts?
try self.addTri(points, shape_data, false);
}
},
// misc. data we either don't use or don't understand
// TODO maybe structure this code more
0x14, 0x3C, 0x40, 0x58, 0x64, 0xFE, 0xFF => {},
0x44, 0x60 => self.view.pos += 2,
0x28 => self.view.pos += 4,
0x5C => self.view.pos += 5,
0x30 => {
const amt = 3 * @as(u16, try reader.readByte());
self.view.pos += amt;
},
// that should be it
else => return error.UnrecognizedShapeCommand,
}
}
}
};
} | src/track/piece_renderer.zig |
const std = @import("std");
test "Leading 0's" {
const cases = [_]u8{
0b10000011,
0b01010000,
0b00101000,
0b00010010,
0b00001100,
0b00000110,
0b00000011,
0b00000001,
};
for (cases) |case, i| testing.expectEqual(leading_zeros(case), @intCast(u3, i));
}
/// Given a byte returns the number of leading zeros. Does not work on 0 due to
/// the u3 restriction. Which is necessary for the compiler to let us bitshift
/// later. Caller is expected to make sure 0 is not passed.
fn leading_zeros(byte: u8) u3 {
if (byte >= 128) return 0;
if (byte >= 64) return 1;
if (byte >= 32) return 2;
if (byte >= 16) return 3;
if (byte >= 8) return 4;
if (byte >= 4) return 5;
if (byte >= 2) return 6;
if (byte >= 1) return 7;
unreachable;
}
/// Encodes a variable width int. Recording the width of the representation and
/// the data stored.
pub const VInt = struct {
width: u4,
data: u64,
};
test "Parsing variable width ints" {
const test_case = struct {
input: []const u8,
output: VInt,
};
const cases = [_]test_case{
.{
.input = &[_]u8{
0b10001011,
},
.output = .{
.width = 1,
.data = 11,
},
},
.{
.input = &[_]u8{
0b01000001,
0b00000010,
},
.output = .{
.width = 2,
.data = 258,
},
},
.{
.input = &[_]u8{
0b00100000,
0b00000000,
0b00001011,
},
.output = .{
.width = 3,
.data = 11,
},
},
};
for (cases) |case| {
std.testing.expectEqual(case.output, parse_vint(case.input));
}
}
/// Given a slice of bytes, read a variable width int. Ignores any bytes past
/// the declared width.
pub fn parse(bytes: []const u8) VInt {
// TODO: We assume VInts max at 8 bytes long.
// This has yet to cause an issue, but I don't think its correct
var buffer: [8]u8 = [1]u8{0} ** 8;
const len: u3 = leading_zeros(bytes[0]);
// offset needs to be a u3 to placate the compiler when we shift later
const offset: u3 = 7 - len;
const width: u4 = @as(u4, 1) + len;
std.mem.copy(u8, buffer[offset..], bytes[0..width]);
buffer[offset] &= ~@shlExact(@as(u8, 1), offset); // Removes the vint marker
const data = std.mem.readInt(u64, &buffer, .Big);
return .{ .data = data, .width = width };
} | src/vint.zig |
const std = @import("std");
const builtin = @import("builtin");
pub fn build(b: *std.build.Builder) !void {
// Standard target options allows the person running `zig build` to choose
// what target to build for. Here we do not override the defaults, which
// means any target is allowed, and the default is native. Other options
// for restricting supported target set are available.
const target = b.standardTargetOptions(.{});
// Standard release options allow the person running `zig build` to select
// between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall.
const mode = b.standardReleaseOptions();
var child = std.ChildProcess.init(&[_][]const u8{"python3", "scripts/generate_version_hpp.py"},std.heap.page_allocator);
try child.spawn();
_ = try child.wait();
const fastpforlib = b.addStaticLibrary("fastpforlib", null);
fastpforlib.addCSourceFiles((try iterateFiles(b, "third_party/fastpforlib")).items, &.{});
_ = try basicSetup(fastpforlib, mode, target);
const fmt = b.addStaticLibrary("fmt", null);
fmt.addCSourceFiles((try iterateFiles(b, "third_party/fmt")).items, &.{});
_ = try basicSetup(fmt, mode, target);
const hyperloglog = b.addStaticLibrary("hyperloglog", null);
hyperloglog.addCSourceFiles((try iterateFiles(b, "third_party/hyperloglog")).items, &.{});
_ = try basicSetup(hyperloglog, mode, target);
const pg_query = b.addStaticLibrary("pg_query", null);
pg_query.addCSourceFiles((try iterateFiles(b, "third_party/libpg_query")).items, &.{});
pg_query.addIncludeDir("third_party/libpg_query/include");
_ = try basicSetup(pg_query, mode, target);
const miniz = b.addStaticLibrary("miniz", null);
miniz.addCSourceFiles((try iterateFiles(b, "third_party/miniz")).items, &.{});
_ = try basicSetup(miniz, mode, target);
const duckdb_re2 = b.addStaticLibrary("duckdb_re2", null);
duckdb_re2.addCSourceFiles((try iterateFiles(b, "third_party/re2")).items, &.{});
_ = try basicSetup(duckdb_re2, mode, target);
const utf8proc = b.addStaticLibrary("utf8proc", null);
utf8proc.addCSourceFiles((try iterateFiles(b, "third_party/utf8proc")).items, &.{});
_ = try basicSetup(utf8proc, mode, target);
const parquet_extension = b.addStaticLibrary("parquet_extension", null);
parquet_extension.addCSourceFiles((try iterateFiles(b, "extension/parquet")).items, &.{});
parquet_extension.addCSourceFiles((try iterateFiles(b, "third_party/parquet")).items, &.{});
parquet_extension.addCSourceFiles((try iterateFiles(b, "third_party/snappy")).items, &.{});
parquet_extension.addCSourceFiles((try iterateFiles(b, "third_party/thrift")).items, &.{});
parquet_extension.addCSourceFiles((try iterateFiles(b, "third_party/zstd")).items, &.{});
parquet_extension.addIncludeDir("extension/parquet/include");
parquet_extension.addIncludeDir("third_party/parquet");
parquet_extension.addIncludeDir("third_party/snappy");
parquet_extension.addIncludeDir("third_party/thrift");
parquet_extension.addIncludeDir("third_party/zstd/include");
_ = try basicSetup(parquet_extension, mode, target);
const icu_extension = b.addStaticLibrary("icu_extension", null);
icu_extension.addCSourceFiles((try iterateFiles(b, "extension/icu")).items, &.{});
icu_extension.addIncludeDir("extension/icu/include");
icu_extension.addIncludeDir("extension/icu/third_party/icu/common");
icu_extension.addIncludeDir("extension/icu/third_party/icu/i18n");
_ = try basicSetup(icu_extension, mode, target);
const httpfs_extension = b.addStaticLibrary("httpfs_extension", null);
httpfs_extension.addCSourceFiles((try iterateFiles(b, "extension/httpfs")).items, &.{});
httpfs_extension.addIncludeDir("extension/httpfs/include");
httpfs_extension.addIncludeDir("third_party/httplib");
httpfs_extension.addIncludeDir("third_party/openssl/include");
httpfs_extension.addIncludeDir("third_party/picohash");
_ = try basicSetup(httpfs_extension, mode, target);
const duckdb_sources = try iterateFiles(b, "src");
const duckdb_static = b.addStaticLibrary("duckdb_static", null);
duckdb_static.addCSourceFiles(duckdb_sources.items, &.{});
duckdb_static.addIncludeDir("extension/httpfs/include");
duckdb_static.addIncludeDir("extension/icu/include");
duckdb_static.addIncludeDir("extension/icu/third_party/icu/common");
duckdb_static.addIncludeDir("extension/icu/third_party/icu/i18n");
duckdb_static.addIncludeDir("extension/parquet/include");
duckdb_static.addIncludeDir("third_party/httplib");
duckdb_static.addIncludeDir("third_party/libpg_query/include");
duckdb_static.defineCMacro("BUILD_HTTPFS_EXTENSION", "ON");
duckdb_static.defineCMacro("BUILD_ICU_EXTENSION", "ON");
duckdb_static.defineCMacro("BUILD_PARQUET_EXTENSION", "TRUE");
duckdb_static.defineCMacro("DUCKDB_MAIN_LIBRARY",null);
duckdb_static.defineCMacro("DUCKDB",null);
duckdb_static.defineCMacro("SQLITE_OMIT_LOAD_EXTENSION","1");
_ = try basicSetup(duckdb_static, mode, target);
const duckdb = b.addSharedLibrary("duckdb",null, .unversioned);
duckdb.addCSourceFiles(duckdb_sources.items, &.{});
duckdb.addIncludeDir("extension/httpfs/include");
duckdb.addIncludeDir("extension/icu/include");
duckdb.addIncludeDir("extension/icu/third_party/icu/common");
duckdb.addIncludeDir("extension/icu/third_party/icu/i18n");
duckdb.addIncludeDir("extension/parquet/include");
duckdb.addIncludeDir("third_party/httplib");
duckdb.addIncludeDir("third_party/libpg_query/include");
duckdb.defineCMacro("BUILD_HTTPFS_EXTENSION", "ON");
duckdb.defineCMacro("BUILD_ICU_EXTENSION", "ON");
duckdb.defineCMacro("BUILD_PARQUET_EXTENSION", "TRUE");
duckdb.defineCMacro("duckdb_EXPORTS",null);
duckdb.defineCMacro("DUCKDB_MAIN_LIBRARY",null);
duckdb.defineCMacro("DUCKDB",null);
if (target.isWindows() or builtin.os.tag == .windows){
duckdb.addObjectFile("third_party/openssl/lib/libcrypto.lib");
duckdb.addObjectFile("third_party/openssl/lib/libssl.lib");
duckdb.addObjectFile("third_party/win64/ws2_32.lib");
duckdb.addObjectFile("third_party/win64/crypt32.lib");
duckdb.addObjectFile("third_party/win64/cryptui.lib");
duckdb.step.dependOn(
&b.addInstallFileWithDir(
.{.path = "third_party/openssl/dll/libssl-3-x64.dll"},
.bin,
"libssl-3-x64.dll",
).step
);
duckdb.step.dependOn(
&b.addInstallFileWithDir(
.{.path = "third_party/openssl/dll/libcrypto-3-x64.dll"},
.bin,
"libcrypto-3-x64.dll",
).step
);
}else{
duckdb.linkSystemLibrary("ssl");
duckdb.linkSystemLibrary("crypto");
}
duckdb.linkLibrary(duckdb_re2);
duckdb.linkLibrary(fastpforlib);
duckdb.linkLibrary(fmt);
duckdb.linkLibrary(hyperloglog);
duckdb.linkLibrary(miniz);
duckdb.linkLibrary(parquet_extension);
duckdb.linkLibrary(pg_query);
duckdb.linkLibrary(utf8proc);
duckdb.linkLibrary(parquet_extension);
duckdb.linkLibrary(icu_extension);
duckdb.linkLibrary(httpfs_extension);
_ = try basicSetup(duckdb, mode, target);
duckdb.linkLibC();
const sqlite3_api_wrapper_static = b.addStaticLibrary("sqlite3_api_wrapper_static", null);
sqlite3_api_wrapper_static.addCSourceFiles(
(try iterateFiles(b, "tools/sqlite3_api_wrapper")).items, &.{});
if (target.isWindows()){
sqlite3_api_wrapper_static.addCSourceFile(
"tools/sqlite3_api_wrapper/sqlite3/os_win.c",
&.{});}
sqlite3_api_wrapper_static.addIncludeDir("extension");
sqlite3_api_wrapper_static.addIncludeDir("extension/httpfs/include");
sqlite3_api_wrapper_static.addIncludeDir("extension/icu/include");
sqlite3_api_wrapper_static.addIncludeDir("extension/icu/third_party/icu/common");
sqlite3_api_wrapper_static.addIncludeDir("extension/icu/third_party/icu/i18n");
sqlite3_api_wrapper_static.addIncludeDir("extension/parquet/include");
sqlite3_api_wrapper_static.addIncludeDir("third_party/libpg_query/include");
sqlite3_api_wrapper_static.addIncludeDir("tools/sqlite3_api_wrapper/include");
sqlite3_api_wrapper_static.addIncludeDir("tools/sqlite3_api_wrapper/sqlite3_udf_api/include");
sqlite3_api_wrapper_static.addIncludeDir("tools/sqlite3_api_wrapper/sqlite3");
sqlite3_api_wrapper_static.defineCMacro("BUILD_HTTPFS_EXTENSION", "ON");
sqlite3_api_wrapper_static.defineCMacro("BUILD_ICU_EXTENSION", "ON");
sqlite3_api_wrapper_static.defineCMacro("BUILD_PARQUET_EXTENSION", "TRUE");
sqlite3_api_wrapper_static.defineCMacro("SQLITE_SHELL_IS_UTF8", null);
sqlite3_api_wrapper_static.linkLibrary(duckdb_static);
sqlite3_api_wrapper_static.linkLibrary(utf8proc);
_ = try basicSetup(sqlite3_api_wrapper_static, mode, target);
sqlite3_api_wrapper_static.linkLibC();
// shell aka DuckDBClient
const shell = b.addExecutable("duckdb", null);
shell.addCSourceFile("tools/shell/shell.c", &.{});
shell.addIncludeDir("extension/httpfs/include");
shell.addIncludeDir("extension/icu/include");
shell.addIncludeDir("extension/parquet/include");
shell.addIncludeDir("third_party/libpg_query/include");
shell.addIncludeDir("third_party/openssl/include");
shell.addIncludeDir("tools/shell/include");
shell.addIncludeDir("tools/sqlite3_api_wrapper/include");
shell.defineCMacro("DUCKDB_BUILD_LIBRARY",null);
shell.defineCMacro("SQLITE_OMIT_LOAD_EXTENSION", "1");
if (target.isWindows() or builtin.os.tag == .windows){
shell.addObjectFile("third_party/openssl/lib/libcrypto.lib");
shell.addObjectFile("third_party/openssl/lib/libssl.lib");
shell.addObjectFile("third_party/win64/ws2_32.lib");
shell.addObjectFile("third_party/win64/crypt32.lib");
shell.addObjectFile("third_party/win64/cryptui.lib");
shell.step.dependOn(
&b.addInstallFileWithDir(
.{.path = "third_party/openssl/dll/libssl-3-x64.dll"},
.bin,
"libssl-3-x64.dll",
).step
);
shell.step.dependOn(
&b.addInstallFileWithDir(
.{.path = "third_party/openssl/dll/libcrypto-3-x64.dll"},
.bin,
"libcrypto-3-x64.dll",
).step
);
}else{
shell.linkSystemLibrary("ssl");
shell.linkSystemLibrary("crypto");
shell.addCSourceFile(
"tools/shell/linenoise.cpp",&.{});
shell.defineCMacro("HAVE_LINENOISE", "1");
}
shell.linkLibrary(duckdb_re2);
shell.linkLibrary(duckdb_static);
shell.linkLibrary(fastpforlib);
shell.linkLibrary(fmt);
shell.linkLibrary(httpfs_extension);
shell.linkLibrary(hyperloglog);
shell.linkLibrary(icu_extension);
shell.linkLibrary(miniz);
shell.linkLibrary(parquet_extension);
shell.linkLibrary(pg_query);
shell.linkLibrary(sqlite3_api_wrapper_static);
shell.linkLibrary(utf8proc);
_ = try basicSetup(shell, mode, target);
shell.linkLibC();
}
fn iterateFiles(b: *std.build.Builder, path: []const u8)!std.ArrayList([]const u8) {
var files = std.ArrayList([]const u8).init(b.allocator);
var dir = try std.fs.cwd().openDir(path, .{ .iterate = true });
var walker = try dir.walk(b.allocator);
defer walker.deinit();
var out: [256] u8 = undefined;
const exclude_files:[]const[]const u8 = &.{
"grammar.cpp","symbols.cpp","duckdb-c.cpp","os_win.c","linenoise.cpp","parquetcli.cpp",
"utf8proc_data.cpp","test_sqlite3_api_wrapper.cpp","test_sqlite3_udf_api_wrapper.cpp",};
const allowed_exts: []const[]const u8 = &.{".c", ".cpp", ".cxx", ".c++", ".cc"};
while (try walker.next()) |entry| {
const ext = std.fs.path.extension(entry.basename);
const include_file = for (allowed_exts) |e| {
if (std.mem.eql(u8, ext, e))
break true;
} else false;
if (include_file) {
const exclude_file = for (exclude_files) |e| {
if (std.mem.eql(u8, entry.basename, e))
break true;
} else false;
if (!exclude_file){
const file = try std.fmt.bufPrint(&out, ("{s}/{s}"), .{path,entry.path});
try files.append(b.dupe(file));
}
}
}
return files;
}
fn basicSetup(in: *std.build.LibExeObjStep, mode: std.builtin.Mode,target: std.zig.CrossTarget)!void {
const include_dirs= [_][]const u8{
"src/include",
"third_party/concurrentqueue",
"third_party/fast_float",
"third_party/fastpforlib",
"third_party/fmt/include",
"third_party/hyperloglog",
"third_party/miniparquet",
"third_party/miniz",
"third_party/pcg",
"third_party/re2",
"third_party/tdigest",
"third_party/utf8proc/include",
};
for (include_dirs) |include_dir|{
in.addIncludeDir(include_dir);
}
in.defineCMacro("DUCKDB_BUILD_LIBRARY",null);
in.linkLibCpp();
in.setBuildMode(mode);
in.force_pic = true;
in.setTarget(target);
in.strip = true;
in.install();
} | build.zig |
const std = @import("std");
usingnamespace (@import("../machine.zig"));
usingnamespace (@import("../util.zig"));
test "AVX-512" {
const m32 = Machine.init(.x86_32);
const m64 = Machine.init(.x64);
const reg = Operand.register;
const pred = Operand.registerPredicate;
const predRm = Operand.rmPredicate;
const sae = Operand.registerSae;
const regRm = Operand.registerRm;
const imm = Operand.immediate;
const memRm = Operand.memoryRmDef;
const memSib = Operand.memorySibDef;
const memRm16 = Operand.memory16Bit;
const memRel = Operand.relMemory;
const mem_void = Operand.memoryRm(.DefaultSeg, .Void, .EAX, 0);
const mem_32 = Operand.memoryRm(.DefaultSeg, .DWORD, .EAX, 0);
const mem_64 = Operand.memoryRm(.DefaultSeg, .QWORD, .EAX, 0);
const rm_mem128 = Operand.memoryRm(.DefaultSeg, .XMM_WORD, .EAX, 0);
const rm_mem256 = Operand.memoryRm(.DefaultSeg, .YMM_WORD, .EAX, 0);
const rm_mem512 = Operand.memoryRm(.DefaultSeg, .ZMM_WORD, .EAX, 0);
const m32bcst = Operand.memoryRm(.DefaultSeg, .DWORD_BCST, .EAX, 0);
const m64bcst = Operand.memoryRm(.DefaultSeg, .QWORD_BCST, .EAX, 0);
debugPrint(false);
// test predicate registers
{
testOp3(m32, .VPADDB, pred(.XMM0, .NoMask, .Merge), reg(.XMM0), reg(.XMM0), "62 f1 7d 08 fc c0");
testOp3(m32, .VPADDB, pred(.XMM0, .NoMask, .Zero), reg(.XMM0), reg(.XMM0), "62 f1 7d 88 fc c0");
testOp3(m32, .VPADDB, pred(.XMM0, .K1, .Zero), reg(.XMM0), reg(.XMM0), "62 f1 7d 89 fc c0");
testOp3(m32, .VPADDB, pred(.XMM0, .K2, .Zero), reg(.XMM0), reg(.XMM0), "62 f1 7d 8a fc c0");
testOp3(m32, .VPADDB, pred(.XMM0, .K3, .Merge), reg(.XMM0), reg(.XMM0), "62 f1 7d 0b fc c0");
testOp3(m32, .VPADDB, pred(.XMM15, .K4, .Merge), reg(.XMM16), reg(.XMM31), AsmError.InvalidMode);
testOp3(m64, .VPADDB, pred(.XMM15, .K5, .Merge), reg(.XMM16), reg(.XMM31), "62 11 7d 05 fc ff");
testOp3(m64, .VPADDB, pred(.XMM15, .K6, .Zero), reg(.XMM16), reg(.XMM31), "62 11 7d 86 fc ff");
testOp3(m64, .VPADDB, pred(.XMM31, .K7, .Zero), reg(.XMM31), reg(.XMM31), "62 01 05 87 fc ff");
testOp3(m64, .VPADDB, pred(.YMM31, .K7, .Zero), reg(.YMM31), reg(.YMM31), "62 01 05 a7 fc ff");
testOp3(m64, .VPADDB, pred(.ZMM31, .NoMask, .Zero), reg(.ZMM31), reg(.ZMM31), "62 01 05 c0 fc ff");
testOp3(m64, .VPADDB, pred(.XMM0, .NoMask, .Merge), reg(.XMM0), reg(.XMM0), "62 f1 7d 08 fc c0");
testOp3(m64, .VPADDB, pred(.YMM0, .NoMask, .Merge), reg(.YMM0), reg(.YMM0), "62 f1 7d 28 fc c0");
testOp3(m64, .VPADDB, pred(.ZMM0, .NoMask, .Merge), reg(.ZMM0), reg(.ZMM0), "62 f1 7d 48 fc c0");
testOp3(m64, .VPADDB, reg(.K7), reg(.XMM16), reg(.XMM31), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, pred(.YMM15, .K7, .Zero), reg(.XMM16), reg(.XMM31), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, pred(.ZMM15, .K7, .Zero), reg(.XMM16), reg(.XMM31), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, pred(.RAX, .K7, .Zero), reg(.XMM16), reg(.XMM31), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, sae(.XMM0, .AE), reg(.XMM0), reg(.XMM0), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, sae(.XMM0, .SAE), reg(.XMM0), reg(.XMM0), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, sae(.XMM0, .RU_SAE), reg(.XMM0), reg(.XMM0), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, reg(.XMM0), pred(.XMM16, .K1, .Merge), reg(.XMM31), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, reg(.XMM0), reg(.XMM0), pred(.XMM31, .K1, .Merge), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, reg(.MM0), reg(.MM0), pred(.MM7, .K1, .Merge), AsmError.InvalidOperand);
testOp3(m64, .VPADDB, reg(.AL), reg(.AH), pred(.BH, .K1, .Merge), AsmError.InvalidOperand);
}
// broadcast test
{
testOp3(m64, .VADDPS, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), m32bcst, "67 62 f1 7c df 58 00");
testOp3(m64, .VADDPS, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), m64bcst, AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), m32bcst, AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), m64bcst, "67 62 f1 fd df 58 00");
testOp3(m64, .VADDPS, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_void, AsmError.InvalidOperand);
testOp3(m64, .VADDPS, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_32, AsmError.InvalidOperand);
testOp3(m64, .VADDPS, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_64, AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_void, AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_32, AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), mem_64, AsmError.InvalidOperand);
}
// test sae/rounding register
{
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), reg(.ZMM0), sae(.ZMM0, .RN_SAE), "62 f1 fd 9f 58 c0");
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), sae(.ZMM0, .SAE), reg(.ZMM0), AsmError.InvalidOperand);
testOp3(m64, .VADDPD, pred(.ZMM0, .K7, .Zero), sae(.ZMM0, .RN_SAE), reg(.ZMM0), AsmError.InvalidOperand);
testOp3(m64, .VADDPD, sae(.ZMM0, .RN_SAE), reg(.ZMM0), pred(.ZMM0, .K7, .Zero), AsmError.InvalidOperand);
testOp3(m64, .VADDPD, sae(.ZMM0, .RN_SAE), reg(.ZMM0), pred(.ZMM0, .K7, .Zero), AsmError.InvalidOperand);
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .AE), imm(0), "62 f1 fd 4f c2 c0 00");
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .SAE), imm(0), "62 f1 fd 5f c2 c0 00");
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .RU_SAE), imm(0), AsmError.InvalidOperand);
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .RN_SAE), imm(0), AsmError.InvalidOperand);
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .RD_SAE), imm(0), AsmError.InvalidOperand);
testOp4(m64, .VCMPPD, pred(.K0, .K7, .Merge), reg(.ZMM0), sae(.ZMM0, .RZ_SAE), imm(0), AsmError.InvalidOperand);
}
// test vsib addressing
{
const vm32xl = Operand.memoryVecSib(.DefaultSeg, .DWORD, 8, .XMM7, .EAX, 0);
const vm32yl = Operand.memoryVecSib(.DefaultSeg, .DWORD, 8, .YMM7, .EAX, 0);
const vm64xl = Operand.memoryVecSib(.DefaultSeg, .QWORD, 8, .XMM7, .EAX, 0);
const vm64yl = Operand.memoryVecSib(.DefaultSeg, .QWORD, 8, .YMM7, .EAX, 0);
const vm32x = Operand.memoryVecSib(.DefaultSeg, .DWORD, 8, .XMM30, .EAX, 0);
const vm32y = Operand.memoryVecSib(.DefaultSeg, .DWORD, 8, .YMM30, .EAX, 0);
const vm32z = Operand.memoryVecSib(.DefaultSeg, .DWORD, 8, .ZMM30, .EAX, 0);
const vm64x = Operand.memoryVecSib(.DefaultSeg, .QWORD, 8, .XMM30, .EAX, 0);
const vm64y = Operand.memoryVecSib(.DefaultSeg, .QWORD, 8, .YMM30, .EAX, 0);
const vm64z = Operand.memoryVecSib(.DefaultSeg, .QWORD, 8, .ZMM30, .EAX, 0);
testOp3(m64, .VGATHERDPD, reg(.XMM1), vm32xl, reg(.XMM2), "67 c4 e2 e9 92 0c f8");
testOp3(m64, .VGATHERDPD, reg(.YMM1), vm32xl, reg(.YMM2), "67 c4 e2 ed 92 0c f8");
testOp3(m64, .VGATHERDPD, reg(.XMM1), vm32x, reg(.XMM2), AsmError.InvalidOperand);
testOp3(m64, .VGATHERDPD, reg(.YMM1), vm32x, reg(.YMM2), AsmError.InvalidOperand);
testOp3(m64, .VGATHERDPD, reg(.XMM1), vm32yl, reg(.XMM2), AsmError.InvalidOperand);
testOp3(m64, .VGATHERDPD, reg(.YMM1), vm32yl, reg(.YMM2), AsmError.InvalidOperand);
testOp3(m64, .VGATHERDPD, reg(.YMM1), vm32z, reg(.YMM2), AsmError.InvalidOperand);
testOp3(m64, .VGATHERDPD, reg(.XMM1), vm64xl, reg(.XMM2), AsmError.InvalidOperand);
testOp2(m64, .VGATHERDPD, pred(.XMM31, .K7, .Zero), vm32x, "67 62 22 fd 87 92 3c f0");
testOp2(m64, .VGATHERDPD, pred(.YMM31, .K7, .Zero), vm32x, "67 62 22 fd a7 92 3c f0");
testOp2(m64, .VGATHERDPD, pred(.ZMM31, .K7, .Zero), vm32y, "67 62 22 fd c7 92 3c f0");
}
// test disp8*N compressed displacement
{
// no displacement
{
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 0), "c5 e9 58 08");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 0), "c5 ed 58 08");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 0), "62 61 d5 00 58 38");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 0), "62 61 d5 20 58 38");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 0), "62 61 d5 40 58 38");
}
// full
{
// vec_len * 1
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * 1), "c5 e9 58 48 10");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * 1), "c5 ed 58 48 20");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * 1), "62 61 d5 00 58 78 01");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * 1), "62 61 d5 20 58 78 01");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * 1), "62 61 d5 40 58 78 01");
// vec_len * -1
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * -1), "c5 e9 58 48 f0");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * -1), "c5 ed 58 48 e0");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * -1), "62 61 d5 00 58 78 ff");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * -1), "62 61 d5 20 58 78 ff");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * -1), "62 61 d5 40 58 78 ff");
// vec_len * 127
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * 127), "c5 e9 58 88 f0 07 00 00");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * 127), "c5 ed 58 88 e0 0f 00 00");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * 127), "62 61 d5 00 58 78 7f");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * 127), "62 61 d5 20 58 78 7f");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * 127), "62 61 d5 40 58 78 7f");
// vec_len * -128
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * -128), "c5 e9 58 88 00 f8 ff ff");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * -128), "c5 ed 58 88 00 f0 ff ff");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * -128), "62 61 d5 00 58 78 80");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * -128), "62 61 d5 20 58 78 80");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * -128), "62 61 d5 40 58 78 80");
// vec_len * 128
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * 128), "c5 e9 58 88 00 08 00 00");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * 128), "c5 ed 58 88 00 10 00 00");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * 128), "62 61 d5 00 58 b8 00 08 00 00");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * 128), "62 61 d5 20 58 b8 00 10 00 00");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * 128), "62 61 d5 40 58 b8 00 20 00 00");
// vec_len * -129
testOp3(m64, .VADDPD, reg(.XMM1), reg(.XMM2), memRm(.XMM_WORD, .RAX, 16 * -129), "c5 e9 58 88 f0 f7 ff ff");
testOp3(m64, .VADDPD, reg(.YMM1), reg(.YMM2), memRm(.YMM_WORD, .RAX, 32 * -129), "c5 ed 58 88 e0 ef ff ff");
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * -129), "62 61 d5 00 58 b8 f0 f7 ff ff");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * -129), "62 61 d5 20 58 b8 e0 ef ff ff");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * -129), "62 61 d5 40 58 b8 c0 df ff ff");
// vec_len * 1 + 1
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * 1 + 1), "62 61 d5 00 58 b8 11 00 00 00");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * 1 + 1), "62 61 d5 20 58 b8 21 00 00 00");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * 1 + 1), "62 61 d5 40 58 b8 41 00 00 00");
// vec_len * 1 - 1
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16 * 1 - 1), "62 61 d5 00 58 b8 0f 00 00 00");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.YMM_WORD, .RAX, 32 * 1 - 1), "62 61 d5 20 58 b8 1f 00 00 00");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.ZMM_WORD, .RAX, 64 * 1 - 1), "62 61 d5 40 58 b8 3f 00 00 00");
// m64_bcst
testOp3(m64, .VADDPD, reg(.XMM31), reg(.XMM21), memRm(.QWORD_BCST, .RAX, 8 * 1), "62 61 d5 10 58 78 01");
testOp3(m64, .VADDPD, reg(.YMM31), reg(.YMM21), memRm(.QWORD_BCST, .RAX, 8 * 1), "62 61 d5 30 58 78 01");
testOp3(m64, .VADDPD, reg(.ZMM31), reg(.ZMM21), memRm(.QWORD_BCST, .RAX, 8 * 1), "62 61 d5 50 58 78 01");
// m32_bcst
testOp3(m64, .VADDPS, reg(.XMM31), reg(.XMM21), memRm(.DWORD_BCST, .RAX, 4 * 1), "62 61 54 10 58 78 01");
testOp3(m64, .VADDPS, reg(.YMM31), reg(.YMM21), memRm(.DWORD_BCST, .RAX, 4 * 1), "62 61 54 30 58 78 01");
testOp3(m64, .VADDPS, reg(.ZMM31), reg(.ZMM21), memRm(.DWORD_BCST, .RAX, 4 * 1), "62 61 54 50 58 78 01");
// vec_len * 1
testOp3(m64, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRel(.DS, .XMM_WORD, .EIP, 16 * 1), "3e 67 62 f1 ed 08 58 0d 10 00 00 00");
testOp3(m64, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRel(.DS, .YMM_WORD, .EIP, 32 * 1), "3e 67 62 f1 ed 28 58 0d 20 00 00 00");
testOp3(m64, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRel(.DS, .ZMM_WORD, .EIP, 64 * 1), "3e 67 62 f1 ed 48 58 0d 40 00 00 00");
// vec_len * 1
testOp3(m64, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memSib(.XMM_WORD, 2, .EAX, .ECX, 16 * 1), "67 62 f1 ed 08 58 4c 41 01");
testOp3(m64, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memSib(.YMM_WORD, 2, .EAX, .ECX, 32 * 1), "67 62 f1 ed 28 58 4c 41 01");
testOp3(m64, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memSib(.ZMM_WORD, 2, .EAX, .ECX, 64 * 1), "67 62 f1 ed 48 58 4c 41 01");
// vec_len * 1
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * 1), "3e 67 62 f1 ed 08 58 48 01");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * 1), "3e 67 62 f1 ed 28 58 48 01");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * 1), "3e 67 62 f1 ed 48 58 48 01");
// vec_len * 1
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * -1), "3e 67 62 f1 ed 08 58 48 ff");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * -1), "3e 67 62 f1 ed 28 58 48 ff");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * -1), "3e 67 62 f1 ed 48 58 48 ff");
// vec_len * 127
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * 127), "3e 67 62 f1 ed 08 58 48 7f");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * 127), "3e 67 62 f1 ed 28 58 48 7f");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * 127), "3e 67 62 f1 ed 48 58 48 7f");
// vec_len * -128
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * -128), "3e 67 62 f1 ed 08 58 48 80");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * -128), "3e 67 62 f1 ed 28 58 48 80");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * -128), "3e 67 62 f1 ed 48 58 48 80");
// vec_len * 128
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * 128), "3e 67 62 f1 ed 08 58 88 00 08");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * 128), "3e 67 62 f1 ed 28 58 88 00 10");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * 128), "3e 67 62 f1 ed 48 58 88 00 20");
// vec_len * -129
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * -129), "3e 67 62 f1 ed 08 58 88 f0 f7");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * -129), "3e 67 62 f1 ed 28 58 88 e0 ef");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * -129), "3e 67 62 f1 ed 48 58 88 c0 df");
// vec_len * 1 - 1
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * 1 - 1), "3e 67 62 f1 ed 08 58 88 0f 00");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * 1 - 1), "3e 67 62 f1 ed 28 58 88 1f 00");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * 1 - 1), "3e 67 62 f1 ed 48 58 88 3f 00");
// vec_len * 1 + 1
testOp3(m32, .VADDPD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm16(.DS, .XMM_WORD, .BX, .SI, 16 * 1 - 1), "3e 67 62 f1 ed 08 58 88 0f 00");
testOp3(m32, .VADDPD, pred(.YMM1, .NoMask, .Merge), reg(.YMM2), memRm16(.DS, .YMM_WORD, .BX, .SI, 32 * 1 - 1), "3e 67 62 f1 ed 28 58 88 1f 00");
testOp3(m32, .VADDPD, pred(.ZMM1, .NoMask, .Merge), reg(.ZMM2), memRm16(.DS, .ZMM_WORD, .BX, .SI, 64 * 1 - 1), "3e 67 62 f1 ed 48 58 88 3f 00");
}
// half
{
// 1
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, 1), "62 f1 7e 08 e6 80 01 00 00 00");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, 1), "62 f1 7e 28 e6 80 01 00 00 00");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.YMM_WORD, .RAX, 1), "62 f1 7e 48 e6 80 01 00 00 00");
// -1
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, -1), "62 f1 7e 08 e6 80 ff ff ff ff");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, -1), "62 f1 7e 28 e6 80 ff ff ff ff");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.YMM_WORD, .RAX, -1), "62 f1 7e 48 e6 80 ff ff ff ff");
// vec_len * 1
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, 8), "62 f1 7e 08 e6 40 01");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, 16), "62 f1 7e 28 e6 40 01");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.YMM_WORD, .RAX, 32), "62 f1 7e 48 e6 40 01");
// vec_len * -1
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, -8), "62 f1 7e 08 e6 40 ff");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.XMM_WORD, .RAX, -16), "62 f1 7e 28 e6 40 ff");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.YMM_WORD, .RAX, -32), "62 f1 7e 48 e6 40 ff");
// m32_bcst
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 0), "62 f1 7e 18 e6 00");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 0), "62 f1 7e 38 e6 00");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 0), "62 f1 7e 58 e6 00");
// m32_bcst
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -1), "62 f1 7e 18 e6 80 ff ff ff ff");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -1), "62 f1 7e 38 e6 80 ff ff ff ff");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -1), "62 f1 7e 58 e6 80 ff ff ff ff");
// m32_bcst
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 4), "62 f1 7e 18 e6 40 01");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 4), "62 f1 7e 38 e6 40 01");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, 4), "62 f1 7e 58 e6 40 01");
// m32_bcst
testOp2(m64, .VCVTDQ2PD, pred(.XMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -4), "62 f1 7e 18 e6 40 ff");
testOp2(m64, .VCVTDQ2PD, pred(.YMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -4), "62 f1 7e 38 e6 40 ff");
testOp2(m64, .VCVTDQ2PD, pred(.ZMM0, .NoMask, .Merge), memRm(.DWORD_BCST, .RAX, -4), "62 f1 7e 58 e6 40 ff");
}
// tuple 1 scalar
{
testOp3(m64, .VADDSD, reg(.XMM1), reg(.XMM2), memRm(.QWORD, .RAX, 0), "c5 eb 58 08");
testOp3(m64, .VADDSS, reg(.XMM1), reg(.XMM2), memRm(.DWORD, .RAX, 0), "c5 ea 58 08");
testOp3(m64, .VADDSD, reg(.XMM1), reg(.XMM2), memRm(.QWORD, .RAX, 0x10), "c5 eb 58 48 10");
testOp3(m64, .VADDSS, reg(.XMM1), reg(.XMM2), memRm(.DWORD, .RAX, 0x10), "c5 ea 58 48 10");
// 8 bit
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, 0), reg(.XMM21), imm(0), "62 e3 7d 08 14 28 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, 1), reg(.XMM21), imm(0), "62 e3 7d 08 14 68 01 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, -1), reg(.XMM21), imm(0), "62 e3 7d 08 14 68 ff 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, 0x10), reg(.XMM21), imm(0), "62 e3 7d 08 14 68 10 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, -0x10), reg(.XMM21), imm(0), "62 e3 7d 08 14 68 f0 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, 0x100), reg(.XMM21), imm(0), "62 e3 7d 08 14 a8 00 01 00 00 00");
testOp3(m64, .VPEXTRB, memRm(.BYTE, .RAX, -0x100), reg(.XMM21), imm(0), "62 e3 7d 08 14 a8 00 ff ff ff 00");
// 16 bit
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, 0), reg(.XMM21), imm(0), "62 e3 7d 08 15 28 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, 1), reg(.XMM21), imm(0), "62 e3 7d 08 15 a8 01 00 00 00 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, -1), reg(.XMM21), imm(0), "62 e3 7d 08 15 a8 ff ff ff ff 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, 2), reg(.XMM21), imm(0), "62 e3 7d 08 15 68 01 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, -2), reg(.XMM21), imm(0), "62 e3 7d 08 15 68 ff 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, 0x80), reg(.XMM21), imm(0), "62 e3 7d 08 15 68 40 00");
testOp3(m64, .VPEXTRW, memRm(.WORD, .RAX, -0x80), reg(.XMM21), imm(0), "62 e3 7d 08 15 68 c0 00");
// 32 bit
testOp3(m64, .VADDSS, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.DWORD, .RAX, 0), "62 f1 6e 08 58 08");
testOp3(m64, .VADDSS, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.DWORD, .RAX, 1), "62 f1 6e 08 58 88 01 00 00 00");
testOp3(m64, .VADDSS, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.DWORD, .RAX, -1), "62 f1 6e 08 58 88 ff ff ff ff");
testOp3(m64, .VADDSS, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.DWORD, .RAX, 4), "62 f1 6e 08 58 48 01");
testOp3(m64, .VADDSS, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.DWORD, .RAX, -4), "62 f1 6e 08 58 48 ff");
// 64 bit
testOp3(m64, .VADDSD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.QWORD, .RAX, 0), "62 f1 ef 08 58 08");
testOp3(m64, .VADDSD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.QWORD, .RAX, 1), "62 f1 ef 08 58 88 01 00 00 00");
testOp3(m64, .VADDSD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.QWORD, .RAX, -1), "62 f1 ef 08 58 88 ff ff ff ff");
testOp3(m64, .VADDSD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.QWORD, .RAX, 8), "62 f1 ef 08 58 48 01");
testOp3(m64, .VADDSD, pred(.XMM1, .NoMask, .Merge), reg(.XMM2), memRm(.QWORD, .RAX, -8), "62 f1 ef 08 58 48 ff");
}
// tuple 1 fixed
{
// VCVTSD2USI reg32, xmml_m64_er
testOp2(m64, .VCVTSD2USI, reg(.EAX), memRm(.QWORD, .RAX, 0), "62 f1 7f 08 79 00");
testOp2(m64, .VCVTSD2USI, reg(.EAX), memRm(.QWORD, .RAX, 1), "62 f1 7f 08 79 80 01 00 00 00");
testOp2(m64, .VCVTSD2USI, reg(.EAX), memRm(.QWORD, .RAX, -1), "62 f1 7f 08 79 80 ff ff ff ff");
testOp2(m64, .VCVTSD2USI, reg(.EAX), memRm(.QWORD, .RAX, 8), "62 f1 7f 08 79 40 01");
testOp2(m64, .VCVTSD2USI, reg(.EAX), memRm(.QWORD, .RAX, -8), "62 f1 7f 08 79 40 ff");
// VCVTSD2USI reg64, xmml_m64_er
testOp2(m64, .VCVTSD2USI, reg(.RAX), memRm(.QWORD, .RAX, 0), "62 f1 ff 08 79 00");
testOp2(m64, .VCVTSD2USI, reg(.RAX), memRm(.QWORD, .RAX, 1), "62 f1 ff 08 79 80 01 00 00 00");
testOp2(m64, .VCVTSD2USI, reg(.RAX), memRm(.QWORD, .RAX, -1), "62 f1 ff 08 79 80 ff ff ff ff");
testOp2(m64, .VCVTSD2USI, reg(.RAX), memRm(.QWORD, .RAX, 8), "62 f1 ff 08 79 40 01");
testOp2(m64, .VCVTSD2USI, reg(.RAX), memRm(.QWORD, .RAX, -8), "62 f1 ff 08 79 40 ff");
// VCVTSS2USI reg32, xmm_m32_er
testOp2(m64, .VCVTSS2USI, reg(.EAX), memRm(.DWORD, .RAX, 0), "62 f1 7e 08 79 00");
testOp2(m64, .VCVTSS2USI, reg(.EAX), memRm(.DWORD, .RAX, 1), "62 f1 7e 08 79 80 01 00 00 00");
testOp2(m64, .VCVTSS2USI, reg(.EAX), memRm(.DWORD, .RAX, -1), "62 f1 7e 08 79 80 ff ff ff ff");
testOp2(m64, .VCVTSS2USI, reg(.EAX), memRm(.DWORD, .RAX, 4), "62 f1 7e 08 79 40 01");
testOp2(m64, .VCVTSS2USI, reg(.EAX), memRm(.DWORD, .RAX, -4), "62 f1 7e 08 79 40 ff");
// VCVTSS2USI reg64, xmm_m32_er
testOp2(m64, .VCVTSS2USI, reg(.RAX), memRm(.DWORD, .RAX, 0), "62 f1 fe 08 79 00");
testOp2(m64, .VCVTSS2USI, reg(.RAX), memRm(.DWORD, .RAX, 1), "62 f1 fe 08 79 80 01 00 00 00");
testOp2(m64, .VCVTSS2USI, reg(.RAX), memRm(.DWORD, .RAX, -1), "62 f1 fe 08 79 80 ff ff ff ff");
testOp2(m64, .VCVTSS2USI, reg(.RAX), memRm(.DWORD, .RAX, 4), "62 f1 fe 08 79 40 01");
testOp2(m64, .VCVTSS2USI, reg(.RAX), memRm(.DWORD, .RAX, -4), "62 f1 fe 08 79 40 ff");
}
// tuple 2
{
// 32 bit: W=0
testOp2(m64, .VBROADCASTF32X2, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, 0), "62 62 7d cf 19 38");
testOp2(m64, .VBROADCASTF32X2, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, 1), "62 62 7d cf 19 b8 01 00 00 00");
testOp2(m64, .VBROADCASTF32X2, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, -1), "62 62 7d cf 19 b8 ff ff ff ff");
testOp2(m64, .VBROADCASTF32X2, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, 8), "62 62 7d cf 19 78 01");
testOp2(m64, .VBROADCASTF32X2, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, -8), "62 62 7d cf 19 78 ff");
// 64 bit: W=1
testOp2(m64, .VBROADCASTF64X2, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 0), "62 62 fd cf 1a 38");
testOp2(m64, .VBROADCASTF64X2, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 1), "62 62 fd cf 1a b8 01 00 00 00");
testOp2(m64, .VBROADCASTF64X2, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, -1), "62 62 fd cf 1a b8 ff ff ff ff");
testOp2(m64, .VBROADCASTF64X2, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 16), "62 62 fd cf 1a 78 01");
testOp2(m64, .VBROADCASTF64X2, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, -16), "62 62 fd cf 1a 78 ff");
}
// tuple 4
{
// 32 bit: W=0
testOp2(m64, .VBROADCASTF32X4, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 0), "62 62 7d cf 1a 38");
testOp2(m64, .VBROADCASTF32X4, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 1), "62 62 7d cf 1a b8 01 00 00 00");
testOp2(m64, .VBROADCASTF32X4, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, -1), "62 62 7d cf 1a b8 ff ff ff ff");
testOp2(m64, .VBROADCASTF32X4, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 16), "62 62 7d cf 1a 78 01");
testOp2(m64, .VBROADCASTF32X4, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, -16), "62 62 7d cf 1a 78 ff");
// 64 bit: W=1
testOp2(m64, .VBROADCASTF64X4, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 0), "62 62 fd cf 1b 38");
testOp2(m64, .VBROADCASTF64X4, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 1), "62 62 fd cf 1b b8 01 00 00 00");
testOp2(m64, .VBROADCASTF64X4, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, -1), "62 62 fd cf 1b b8 ff ff ff ff");
testOp2(m64, .VBROADCASTF64X4, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 32), "62 62 fd cf 1b 78 01");
testOp2(m64, .VBROADCASTF64X4, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, -32), "62 62 fd cf 1b 78 ff");
}
// tuple 8
{
// 32 bit: W=0
testOp2(m64, .VBROADCASTF32X8, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 0), "62 62 7d cf 1b 38");
testOp2(m64, .VBROADCASTF32X8, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 1), "62 62 7d cf 1b b8 01 00 00 00");
testOp2(m64, .VBROADCASTF32X8, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, -1), "62 62 7d cf 1b b8 ff ff ff ff");
testOp2(m64, .VBROADCASTF32X8, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 32), "62 62 7d cf 1b 78 01");
testOp2(m64, .VBROADCASTF32X8, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, -32), "62 62 7d cf 1b 78 ff");
}
// full mem
{
testOp2(m64, .VPABSB, pred(.XMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 1), "62 62 7d 8f 1c b8 01 00 00 00");
testOp2(m64, .VPABSB, pred(.YMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 1), "62 62 7d af 1c b8 01 00 00 00");
testOp2(m64, .VPABSB, pred(.ZMM31, .K7, .Zero), memRm(.ZMM_WORD, .RAX, 1), "62 62 7d cf 1c b8 01 00 00 00");
//
testOp2(m64, .VPABSB, pred(.XMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 16), "62 62 7d 8f 1c 78 01");
testOp2(m64, .VPABSB, pred(.YMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 32), "62 62 7d af 1c 78 01");
testOp2(m64, .VPABSB, pred(.ZMM31, .K7, .Zero), memRm(.ZMM_WORD, .RAX, 64), "62 62 7d cf 1c 78 01");
}
// half mem
{
testOp2(m64, .VPMOVSXBW, pred(.XMM31, .K7, .Zero), memRm(.QWORD, .RAX, 1), "62 62 7d 8f 20 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBW, pred(.YMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 1), "62 62 7d af 20 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBW, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 1), "62 62 7d cf 20 b8 01 00 00 00");
//
testOp2(m64, .VPMOVSXBW, pred(.XMM31, .K7, .Zero), memRm(.QWORD, .RAX, 8), "62 62 7d 8f 20 78 01");
testOp2(m64, .VPMOVSXBW, pred(.YMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 16), "62 62 7d af 20 78 01");
testOp2(m64, .VPMOVSXBW, pred(.ZMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 32), "62 62 7d cf 20 78 01");
}
// quarter mem
{
testOp2(m64, .VPMOVSXBD, pred(.XMM31, .K7, .Zero), memRm(.DWORD, .RAX, 1), "62 62 7d 8f 21 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBD, pred(.YMM31, .K7, .Zero), memRm(.QWORD, .RAX, 1), "62 62 7d af 21 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBD, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 1), "62 62 7d cf 21 b8 01 00 00 00");
//
testOp2(m64, .VPMOVSXBD, pred(.XMM31, .K7, .Zero), memRm(.DWORD, .RAX, 4), "62 62 7d 8f 21 78 01");
testOp2(m64, .VPMOVSXBD, pred(.YMM31, .K7, .Zero), memRm(.QWORD, .RAX, 8), "62 62 7d af 21 78 01");
testOp2(m64, .VPMOVSXBD, pred(.ZMM31, .K7, .Zero), memRm(.XMM_WORD, .RAX, 16), "62 62 7d cf 21 78 01");
}
// eigth mem
{
testOp2(m64, .VPMOVSXBQ, pred(.XMM31, .K7, .Zero), memRm(.WORD, .RAX, 1), "62 62 7d 8f 22 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBQ, pred(.YMM31, .K7, .Zero), memRm(.DWORD, .RAX, 1), "62 62 7d af 22 b8 01 00 00 00");
testOp2(m64, .VPMOVSXBQ, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, 1), "62 62 7d cf 22 b8 01 00 00 00");
//
testOp2(m64, .VPMOVSXBQ, pred(.XMM31, .K7, .Zero), memRm(.WORD, .RAX, 2), "62 62 7d 8f 22 78 01");
testOp2(m64, .VPMOVSXBQ, pred(.YMM31, .K7, .Zero), memRm(.DWORD, .RAX, 4), "62 62 7d af 22 78 01");
testOp2(m64, .VPMOVSXBQ, pred(.ZMM31, .K7, .Zero), memRm(.QWORD, .RAX, 8), "62 62 7d cf 22 78 01");
}
// mem 128
{
testOp3(m64, .VPSLLW, pred(.XMM31, .K7, .Zero), reg(.XMM21), memRm(.XMM_WORD, .RAX, 1), "62 61 55 87 f1 b8 01 00 00 00");
testOp3(m64, .VPSLLW, pred(.YMM31, .K7, .Zero), reg(.YMM21), memRm(.XMM_WORD, .RAX, 1), "62 61 55 a7 f1 b8 01 00 00 00");
testOp3(m64, .VPSLLW, pred(.ZMM31, .K7, .Zero), reg(.ZMM21), memRm(.XMM_WORD, .RAX, 1), "62 61 55 c7 f1 b8 01 00 00 00");
//
testOp3(m64, .VPSLLW, pred(.XMM31, .K7, .Zero), reg(.XMM21), memRm(.XMM_WORD, .RAX, 16), "62 61 55 87 f1 78 01");
testOp3(m64, .VPSLLW, pred(.YMM31, .K7, .Zero), reg(.YMM21), memRm(.XMM_WORD, .RAX, 16), "62 61 55 a7 f1 78 01");
testOp3(m64, .VPSLLW, pred(.ZMM31, .K7, .Zero), reg(.ZMM21), memRm(.XMM_WORD, .RAX, 16), "62 61 55 c7 f1 78 01");
}
// MOVDDUP
{
testOp2(m64, .VMOVDDUP, pred(.XMM31, .K7, .Zero), memRm(.QWORD, .RAX, 1), "62 61 ff 8f 12 b8 01 00 00 00");
testOp2(m64, .VMOVDDUP, pred(.YMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 1), "62 61 ff af 12 b8 01 00 00 00");
testOp2(m64, .VMOVDDUP, pred(.ZMM31, .K7, .Zero), memRm(.ZMM_WORD, .RAX, 1), "62 61 ff cf 12 b8 01 00 00 00");
//
testOp2(m64, .VMOVDDUP, pred(.XMM31, .K7, .Zero), memRm(.QWORD, .RAX, 8), "62 61 ff 8f 12 78 01");
testOp2(m64, .VMOVDDUP, pred(.YMM31, .K7, .Zero), memRm(.YMM_WORD, .RAX, 32), "62 61 ff af 12 78 01");
testOp2(m64, .VMOVDDUP, pred(.ZMM31, .K7, .Zero), memRm(.ZMM_WORD, .RAX, 64), "62 61 ff cf 12 78 01");
}
}
} | src/x86/tests/avx_512.zig |
const std = @import("std");
const builtin = @import("builtin");
const fmt = std.fmt;
const util = @import("util.zig");
const platform = @import("platform.zig");
const Cookie = util.Cookie;
const c = @cImport({
@cInclude("wasm3/source/m3_env.h");
});
pub const Error = error{
Unknown,
CantCreateEnv,
CantCreateRuntime,
NoMoreModules,
InvalidAlignment,
InvalidType,
InvalidNumArgs,
Exit,
Abort,
OutOfBounds,
NoSuchFunction,
};
pub const WasmPtr = extern struct { offset: u32 };
// These types should be used for pointers because WASM memory can be unaligned
pub const u32_ptr = *align(1) u32;
pub const i32_ptr = *align(1) i32;
pub const u64_ptr = *align(1) u64;
pub const i64_ptr = *align(1) i64;
pub const u32_ptr_many = [*]align(1) u32;
pub const i32_ptr_many = [*]align(1) i32;
pub const u64_ptr_many = [*]align(1) u64;
pub const i64_ptr_many = [*]align(1) i64;
const errorConversionPair = struct { a: c.M3Result, b: Error };
var errorConversionTable_back: [256]errorConversionPair = undefined;
var errorConversionTable_len: usize = 0;
var errorConversionTable: ?[]errorConversionPair = null;
inline fn errorConversionTableAddEntry(a: c.M3Result, b: Error) void {
errorConversionTable_back[errorConversionTable_len] = .{ .a = a, .b = b };
errorConversionTable_len += 1;
}
fn initErrorConversionTable() void {
const e = errorConversionTableAddEntry;
e(c.m3Err_argumentCountMismatch, Error.InvalidNumArgs);
e(c.m3Err_trapExit, Error.Exit);
e(c.m3Err_trapAbort, Error.Abort);
e(c.m3Err_trapOutOfBoundsMemoryAccess, Error.OutOfBounds);
e(c.m3Err_functionLookupFailed, Error.NoSuchFunction);
errorConversionTable = errorConversionTable_back[0..errorConversionTable_len];
}
fn m3ResultToError(m3res: c.M3Result, comptime T: type) !T {
if (m3res == null) {
comptime if (T == void) {
return;
} else {
return undefined;
};
}
if (errorConversionTable == null) initErrorConversionTable();
for (errorConversionTable.?) |entry| {
if (m3res == entry.a) return entry.b;
}
if (builtin.mode == .Debug) platform.earlyprintf("Warning: can't convert to Zig error: {}\n", .{std.mem.spanZ(m3res)});
return Error.Unknown;
}
fn errorToM3Result(err: ?anyerror) c.M3Result {
if (err == null) return null;
if (errorConversionTable == null) initErrorConversionTable();
for (errorConversionTable.?) |entry| {
if (err.? == entry.b) return entry.a;
}
return c.m3Err_trapAbort;
}
inline fn boundsCheck(obj: anytype, off: usize, len: usize) !void {
if (obj.len <= off or obj.len <= (off + len)) return Error.OutOfBounds;
}
pub const RuntimeStack = struct {
stack: [*]u64,
pub inline fn init(ptr: [*]u64) RuntimeStack {
return RuntimeStack{ .stack = ptr };
}
pub inline fn set(self: RuntimeStack, index: usize, val: anytype) void {
switch (@TypeOf(val)) {
u64, u32 => self.stack[index] = @intCast(u64, val),
i64, i32 => self.stack[index] = @intCast(u64, val),
else => @compileError("Invalid type"),
}
}
pub inline fn get(self: RuntimeStack, comptime T: type, index: usize) T {
return switch (T) {
u64 => self.stack[index],
usize => @truncate(usize, self.stack[index] & 0xFFFFFFFF),
i64 => @intCast(i64, self.stack[index]),
u32 => @truncate(u32, self.stack[index] & 0xFFFFFFFF),
i32 => @truncate(i32, self.stack[index] & 0xFFFFFFFF),
f64 => (@ptrCast([*]align(1) f64, self.stack))[index],
else => @compileError("Invalid type"),
};
}
};
fn zigToWasmType(comptime T: type) u8 {
return switch (T) {
u64, i64 => 'I',
u32, i32 => 'i',
f64 => 'F',
f32 => 'f',
void, u0 => 'v',
WasmPtr => '*',
else => switch (@typeInfo(T)) {
.Pointer => '*',
.Enum => |enm| zigToWasmType(enm.tag_type),
else => @compileError("Invalid type"),
},
};
}
fn zigToWasmTypeMulti(comptime T: type, out: []u8) usize {
switch (@typeInfo(T)) {
.Pointer => |ptr| {
switch (ptr.size) {
.Slice => {
out[0] = '*';
out[1] = 'i';
return 2;
},
else => {
out[0] = '*';
return 1;
},
}
},
else => {
out[0] = zigToWasmType(T);
return 1;
},
}
unreachable;
}
pub const ZigFunction = fn (ctx: ZigFunctionCtx) anyerror!void;
pub const ZigFunctionEx = struct {
name: [*c]const u8,
sig: [*c]const u8,
call: ZigFunction,
cookie: Cookie = null,
_orig: fn () void,
pub fn init(name: [*c]const u8, f: anytype) ZigFunctionEx {
comptime var rawftype = @TypeOf(f);
comptime var ftype = @typeInfo(rawftype);
comptime var fninfo = ftype.Fn;
comptime var atype = @typeInfo(fninfo.args[1].arg_type.?);
comptime var sig: [atype.Struct.fields.len * 2 + 2 + 1 + 1]u8 = undefined;
var anonFn = struct {
pub fn anon(ctx: ZigFunctionCtx) anyerror!void {
const args = try ctx.args(fninfo.args[1].arg_type.?);
const me = @ptrCast(*ZigFunctionEx, @alignCast(@alignOf(ZigFunctionEx), ctx.trampoline));
var res = @call(.{}, @ptrCast(rawftype, me._orig), .{ ctx, args }) catch |err| return err;
if (@typeInfo(fninfo.return_type.?).ErrorUnion.payload == void) return else ctx.ret(res);
}
}.anon;
var ret = ZigFunctionEx{ .name = name, .sig = &sig, .call = anonFn, ._orig = @ptrCast(fn () void, f) };
comptime {
sig[0] = zigToWasmType(@typeInfo(fninfo.return_type.?).ErrorUnion.payload); // TODO: real thing
sig[1] = '(';
var i: usize = 2;
inline for (atype.Struct.fields) |arg| {
i += zigToWasmTypeMulti(arg.field_type, sig[i..sig.len]);
}
sig[i] = ')';
sig[i + 1] = 0;
}
return ret;
}
pub inline fn lenInitMany(comptime prefix: []const u8, comptime typ: type) comptime usize {
comptime {
var t = @typeInfo(typ);
var i = 0;
for (t.Struct.decls) |decl| {
if (std.mem.startsWith(u8, decl.name, prefix))
i += switch (decl.data) {
.Fn => 1,
else => 0,
};
}
return i;
}
}
pub inline fn initMany(comptime prefix: []const u8, comptime s: type) [lenInitMany(prefix, s)]ZigFunctionEx {
comptime {
var ret: [lenInitMany(prefix, s)]ZigFunctionEx = undefined;
var t = @typeInfo(s);
var i = 0;
for (t.Struct.decls) |decl| {
if (std.mem.startsWith(u8, decl.name, prefix)) {
switch (decl.data) {
.Fn => {
var name: [decl.name.len - prefix.len + 1:0]u8 = undefined;
std.mem.copy(u8, name[0..], decl.name[prefix.len..]);
name[name.len - 1] = 0;
ret[i] = init(name[0..], @field(s, decl.name));
i += 1;
},
else => {},
}
}
}
return ret;
}
}
};
pub const ZigFunctionCtx = struct {
runtime: Runtime,
sp: RuntimeStack,
memory: []u8,
trampoline: ?*c_void,
cookie: Cookie = null,
pub inline fn args(self: ZigFunctionCtx, comptime T: type) !T {
var out: T = undefined;
comptime var tinfo = @typeInfo(T);
comptime var i: usize = 0;
inline for (tinfo.Struct.fields) |field| {
switch (field.field_type) {
u64, i64, u32, i32, f64, f32 => {
@field(out, field.name) = self.sp.get(field.field_type, i);
i += 1;
},
else => {
switch (@typeInfo(field.field_type)) {
.Pointer => |ptr| {
switch (ptr.size) {
.One, .Many => {
try boundsCheck(self.memory, self.sp.get(usize, i), @sizeOf(ptr.child));
@field(out, field.name) = @ptrCast(field.field_type, @alignCast(ptr.alignment, &self.memory[self.sp.get(usize, i)]));
i += 1;
},
.Slice => {
try boundsCheck(self.memory, self.sp.get(usize, i), self.sp.get(usize, i + 1));
var rawptr = @ptrCast([*]align(1) ptr.child, @alignCast(1, &self.memory[self.sp.get(usize, i)]));
var len = self.sp.get(usize, i + 1);
@field(out, field.name) = rawptr[0..len];
i += 2;
},
else => @compileError("Invalid pointer type"),
}
},
.Enum => |enm| {
// TODO: check if value is valid
@field(out, field.name) = @intToEnum(field.field_type, self.sp.get(enm.tag_type, i));
i += 1;
},
else => @compileError("Invalid type"),
}
},
}
}
return out;
}
pub inline fn ret(self: ZigFunctionCtx, val: anytype) void {
self.sp.set(0, val);
}
};
pub const NativeModule = struct {
allocator: *std.mem.Allocator,
functions: []ZigFunctionEx,
pub fn init(allocator: *std.mem.Allocator, comptime prefix: []const u8, impl: type, cookie: anytype) !NativeModule {
var ret = NativeModule{ .allocator = allocator, .functions = try allocator.dupe(ZigFunctionEx, ZigFunctionEx.initMany(prefix, impl)[0..]) };
for (ret.functions) |_, i| {
ret.functions[i].cookie = util.asCookie(cookie);
}
return ret;
}
pub fn link(self: NativeModule, namespace: [:0]const u8, module: Module) void {
for (self.functions) |_, i| {
_ = module.linkRawZigFunctionEx(namespace, &self.functions[i]) catch null;
}
}
pub fn deinit(self: NativeModule) void {
self.allocator.free(self.functions);
}
};
pub const Module = struct {
module: c.IM3Module,
pub fn init(modPtr: c.IM3Module) Module {
return Module{ .module = modPtr };
}
pub inline fn name(self: Module) []const u8 {
return std.mem.spanZ(self.name);
}
pub inline fn raw(self: Module) c.IM3Module {
return self.module;
}
pub fn linkRawFunction(self: Module, modName: [*c]const u8, fName: [*c]const u8, sig: [*c]const u8, rawcall: c.M3RawCall) !void {
return m3ResultToError(c.m3_LinkRawFunction(self.module, modName, fName, sig, rawcall), void);
}
pub fn linkRawFunctionEx(self: Module, modName: [*c]const u8, fName: [*c]const u8, sig: [*c]const u8, rawcall: c.M3RawCallEx, cookie: *c_void) !void {
return m3ResultToError(c.m3_LinkRawFunctionEx(self.module, modName, fName, sig, rawcall, cookie), void);
}
fn linkZigFunctionHelper(runtime: c.IM3Runtime, sp: [*c]u64, mem: ?*c_void, cookie: ?*c_void) callconv(.C) ?*c_void {
var f: ZigFunction = @intToPtr(ZigFunction, @ptrToInt(cookie));
var bogusRt = Runtime{ .runtime = runtime, .environ = undefined };
var mem_slice = @ptrCast([*]u8, mem)[0 .. @intCast(usize, runtime.*.memory.numPages) * 65536];
f(ZigFunctionCtx{ .runtime = bogusRt, .sp = RuntimeStack.init(sp), .memory = mem_slice }) catch |err| return @intToPtr(*c_void, @ptrToInt(errorToM3Result(err)));
return null;
}
pub inline fn linkRawZigFunction(self: Module, modName: [*c]const u8, fName: [*c]const u8, sig: [*c]const u8, f: ZigFunction) !void {
return self.linkRawFunctionEx(modName, fName, sig, Module.linkZigFunctionHelper, @intToPtr(*c_void, @ptrToInt(f))); // use stupid casting hack
}
fn linkZigFunctionHelperEx(runtime: c.IM3Runtime, sp: [*c]u64, mem: ?*c_void, cookie: ?*c_void) callconv(.C) ?*c_void {
var f: *ZigFunctionEx = @intToPtr(*ZigFunctionEx, @ptrToInt(cookie));
var bogusRt = Runtime{ .runtime = runtime, .environ = undefined };
var mem_slice = @ptrCast([*]u8, mem)[0 .. @intCast(usize, runtime.*.memory.numPages) * 65536];
f.call(ZigFunctionCtx{ .runtime = bogusRt, .sp = RuntimeStack.init(sp), .memory = mem_slice, .cookie = f.cookie, .trampoline = f }) catch |err| return @intToPtr(*c_void, @ptrToInt(errorToM3Result(err)));
return null;
}
pub inline fn linkRawZigFunctionEx(self: Module, modName: [*c]const u8, f: *const ZigFunctionEx) !void {
return self.linkRawFunctionEx(modName, f.name, f.sig, Module.linkZigFunctionHelperEx, @intToPtr(*c_void, @ptrToInt(f))); // use stupid casting hack
}
pub fn destroy(self: Module) void {
c.m3_FreeModule(self.module);
}
pub fn next(self: Module) !Module {
if (self.module.next == null) return Errors.NoMoreModules;
return Module.init(self.module.next);
}
};
pub const Function = struct {
func: ?*c.M3Function,
runtime: Runtime,
pub fn init(func: c.IM3Function, runtime: Runtime) Function {
return Function{ .func = func, .runtime = runtime };
}
pub fn name(self: Function) []const u8 {
return std.mem.spanZ(self.func.?.name);
}
pub fn numArgs(self: Function) u8 {
return @truncate(u8, self.func.?.funcType.*.numArgs);
}
pub fn callVoid(self: Function, comptime T: type) !T {
var res = c.m3_Call(self.func);
if (res != null) return m3ResultToError(res, T);
comptime if (T == void) return;
return self.runtime.stack().get(T, 0);
}
pub fn callWithArgs(self: Function, comptime T: type, args: [*c]const [*c]const u8, argc: usize) !T {
var res = c.m3_CallWithArgs(self.func, @intCast(u32, argc), args);
if (res != null) return m3ResultToError(res, T);
comptime if (T == void) return;
return self.runtime.stack().get(T, 0);
}
pub fn call(self: Function, comptime T: type, args: anytype) !T {
comptime var tInfo = @typeInfo(@TypeOf(args));
var trueArgs: [tInfo.Struct.fields.len][32]u8 = undefined;
var cArgs: [tInfo.Struct.fields.len + 1][*c]u8 = undefined;
inline for (tInfo.Struct.fields) |field, i| {
switch (@typeInfo(field.field_type)) {
.ComptimeInt, .Int => try fmt.bufPrint(trueArgs[i][0..], "{d}\x00", .{@field(args, field.name)}),
.ComptimeFloat => {
{
var rtFloat: f64 = @field(args, field.name);
_ = try fmt.bufPrint(trueArgs[i][0..], "{d}\x00", .{@ptrCast([*]u64, &rtFloat)[0]});
}
},
.Float => switch (@typeInfo(field.field_type).Float.bits) {
64 => _ = try fmt.bufPrint(trueArgs[i][0..], "{d}\x00", .{@ptrCast([*]u64, &@field(args, field.name))[0]}),
32 => _ = try fmt.bufPrint(trueArgs[i][0..], "{d}\x00", .{@ptrCast([*]u32, &@field(args, field.name))[0]}),
else => @compileError("Invalid float type"),
},
else => @compileError("Invalid argument type"),
}
cArgs[i] = &trueArgs[i];
}
cArgs[tInfo.Struct.fields.len] = @intToPtr([*c]u8, 0);
return self.callWithArgs(T, &cArgs, tInfo.Struct.fields.len);
}
};
pub const Runtime = struct {
environ: c.IM3Environment,
runtime: ?*c.M3Runtime,
pub fn init(stackBytes: usize) !Runtime {
var ret: Runtime = undefined;
ret.environ = c.m3_NewEnvironment();
if (ret.environ == null) return Error.CantCreateEnv;
errdefer c.m3_FreeEnvironment(ret.environ);
ret.runtime = c.m3_NewRuntime(ret.environ, @intCast(u32, stackBytes), null);
if (ret.runtime == null) return Error.CantCreateRuntime;
errdefer c.m3_FreeRuntime(ret.environ);
return ret;
}
pub fn parseAndLoadModule(self: Runtime, data: []const u8) !Module {
var modPtr: c.IM3Module = undefined;
var res = c.m3_ParseModule(self.environ, &modPtr, data.ptr, @intCast(u32, data.len));
if (res != null) return m3ResultToError(res, Module);
errdefer {
c.m3_FreeModule(modPtr);
}
res = c.m3_LoadModule(self.runtime, modPtr);
if (res != null) return m3ResultToError(res, Module);
return Module.init(modPtr);
}
pub fn findFunction(self: Runtime, name: [*c]const u8) !Function {
var rawf: c.IM3Function = undefined;
var res = c.m3_FindFunction(&rawf, self.runtime, name);
if (res != null) return m3ResultToError(res, Function);
return Function.init(rawf, self);
}
pub inline fn stack(self: Runtime) RuntimeStack {
var rawstack = @ptrCast([*]u64, @alignCast(@alignOf([*]u64), self.runtime.?.stack));
return RuntimeStack.init(rawstack);
}
pub fn deinit(self: Runtime) void {
c.m3_FreeRuntime(self.runtime);
c.m3_FreeEnvironment(self.environ);
}
}; | kernel/wasm3.zig |
const std = @import("std");
const builtin = @import("builtin");
const meta = std.meta;
const testing = std.testing;
const TypeInfo = std.builtin.TypeInfo;
const cudaz_options = @import("cudaz_options");
pub const cu = @import("cuda_cimports.zig").cu;
pub const cuda_errors = @import("cuda_errors.zig");
pub const check = cuda_errors.check;
pub const Error = cuda_errors.Error;
const attributes = @import("attributes.zig");
pub const Attribute = attributes.Attribute;
pub const getAttr = attributes.getAttr;
pub const algorithms = @import("algorithms.zig");
const log = std.log.scoped(.Cuda);
pub const Dim3 = struct {
x: c_uint = 1,
y: c_uint = 1,
z: c_uint = 1,
pub fn init(x: usize, y: usize, z: usize) Dim3 {
return .{
.x = @intCast(c_uint, x),
.y = @intCast(c_uint, y),
.z = @intCast(c_uint, z),
};
}
pub fn dim3(self: *const Dim3) cu.dim3 {
return cu.dim3{ .x = self.x, .y = self.y, .z = self.z };
}
};
/// Represents how kernel are execut
pub const Grid = struct {
blocks: Dim3 = .{},
threads: Dim3 = .{},
pub fn init1D(len: usize, threads: usize) Grid {
return init3D(len, 1, 1, threads, 1, 1);
}
pub fn init2D(cols: usize, rows: usize, threads_x: usize, threads_y: usize) Grid {
return init3D(cols, rows, 1, threads_x, threads_y, 1);
}
pub fn init3D(
cols: usize,
rows: usize,
depth: usize,
threads_x: usize,
threads_y: usize,
threads_z: usize,
) Grid {
var t_x = if (threads_x == 0) cols else threads_x;
var t_y = if (threads_y == 0) rows else threads_y;
var t_z = if (threads_z == 0) depth else threads_z;
return Grid{
.blocks = Dim3.init(
std.math.divCeil(usize, cols, t_x) catch unreachable,
std.math.divCeil(usize, rows, t_y) catch unreachable,
std.math.divCeil(usize, depth, t_z) catch unreachable,
),
.threads = Dim3.init(t_x, t_y, t_z),
};
}
pub fn threadsPerBlock(self: *const Grid) usize {
return self.threads.x * self.threads.y * self.threads.z;
}
pub fn sharedMem(self: *const Grid, comptime ty: type, per_thread: usize) usize {
return self.threadsPerBlock() * @sizeOf(ty) * per_thread;
}
};
pub const Stream = struct {
device: cu.CUdevice,
_stream: *cu.CUstream_st,
pub fn init(device: u3) !Stream {
const cu_dev = try initDevice(device);
_ = try getCtx(device, cu_dev);
var stream: cu.CUstream = undefined;
check(cu.cuStreamCreate(&stream, cu.CU_STREAM_DEFAULT)) catch |err| switch (err) {
error.NotSupported => return error.NotSupported,
else => unreachable,
};
return Stream{ .device = cu_dev, ._stream = stream.? };
}
pub fn deinit(self: *Stream) void {
// Don't handle CUDA errors here
_ = self.synchronize();
_ = cu.cuStreamDestroy(self._stream);
self._stream = undefined;
}
// TODO: can this OOM ? Or will the error be raised later ?
pub fn alloc(self: *const Stream, comptime DestType: type, size: usize) ![]DestType {
var int_ptr: cu.CUdeviceptr = undefined;
const byte_size = size * @sizeOf(DestType);
check(cu.cuMemAllocAsync(&int_ptr, byte_size, self._stream)) catch |err| {
switch (err) {
error.OutOfMemory => {
var free_mem: usize = undefined;
var total_mem: usize = undefined;
const mb = 1024 * 1024;
check(cu.cuMemGetInfo(&free_mem, &total_mem)) catch return err;
log.err(
"Cuda OutOfMemory: tried to allocate {d:.1}Mb, free {d:.1}Mb, total {d:.1}Mb",
.{ byte_size / mb, free_mem / mb, total_mem / mb },
);
return err;
},
else => unreachable,
}
};
var ptr = @intToPtr([*]DestType, int_ptr);
return ptr[0..size];
}
pub fn free(self: *const Stream, device_ptr: anytype) void {
var raw_ptr: *anyopaque = if (meta.trait.isSlice(@TypeOf(device_ptr)))
@ptrCast(*anyopaque, device_ptr.ptr)
else
@ptrCast(*anyopaque, device_ptr);
_ = cu.cuMemFreeAsync(@ptrToInt(raw_ptr), self._stream);
}
pub fn memcpyHtoD(self: *const Stream, comptime DestType: type, d_target: []DestType, h_source: []const DestType) void {
std.debug.assert(h_source.len == d_target.len);
check(cu.cuMemcpyHtoDAsync(
@ptrToInt(d_target.ptr),
@ptrCast(*const anyopaque, h_source.ptr),
h_source.len * @sizeOf(DestType),
self._stream,
)) catch unreachable;
}
pub fn memcpyDtoH(self: *const Stream, comptime DestType: type, h_target: []DestType, d_source: []const DestType) void {
std.debug.assert(d_source.len == h_target.len);
check(cu.cuMemcpyDtoHAsync(
@ptrCast(*anyopaque, h_target.ptr),
@ptrToInt(d_source.ptr),
d_source.len * @sizeOf(DestType),
self._stream,
)) catch unreachable;
}
pub fn allocAndCopy(self: *const Stream, comptime DestType: type, h_source: []const DestType) ![]DestType {
var ptr = try self.alloc(DestType, h_source.len);
self.memcpyHtoD(DestType, ptr, h_source);
return ptr;
}
pub fn allocAndCopyResult(
self: *const Stream,
comptime DestType: type,
host_allocator: std.mem.Allocator,
d_source: []const DestType,
) ![]DestType {
var h_tgt = try host_allocator.alloc(DestType, d_source.len);
try self.memcpyDtoH(DestType, h_tgt, d_source);
return h_tgt;
}
pub fn memset(self: *const Stream, comptime DestType: type, slice: []DestType, value: DestType) void {
var d_ptr = @ptrToInt(slice.ptr);
var n = slice.len;
var memset_res = switch (@sizeOf(DestType)) {
1 => cu.cuMemsetD8Async(d_ptr, @bitCast(u8, value), n, self._stream),
2 => cu.cuMemsetD16Async(d_ptr, @bitCast(u16, value), n, self._stream),
4 => cu.cuMemsetD32Async(d_ptr, @bitCast(u32, value), n, self._stream),
else => @compileError("memset doesn't support type: " ++ @typeName(DestType)),
};
check(memset_res) catch unreachable;
}
pub inline fn launch(self: *const Stream, f: cu.CUfunction, grid: Grid, args: anytype) !void {
try self.launchWithSharedMem(f, grid, 0, args);
}
pub fn launchWithSharedMem(self: *const Stream, f: cu.CUfunction, grid: Grid, shared_mem: usize, args: anytype) !void {
// Create an array of pointers pointing to the given args.
const fields: []const TypeInfo.StructField = meta.fields(@TypeOf(args));
var args_ptrs: [fields.len:0]usize = undefined;
inline for (fields) |field, i| {
args_ptrs[i] = @ptrToInt(&@field(args, field.name));
}
const res = cu.cuLaunchKernel(
f,
grid.blocks.x,
grid.blocks.y,
grid.blocks.z,
grid.threads.x,
grid.threads.y,
grid.threads.z,
@intCast(c_uint, shared_mem),
self._stream,
@ptrCast([*c]?*anyopaque, &args_ptrs),
null,
);
try check(res);
// TODO use callback API to keep the asynchronous scheduling
}
pub fn synchronize(self: *const Stream) void {
check(cu.cuStreamSynchronize(self._stream)) catch unreachable;
}
pub fn format(
self: *const Stream,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = fmt;
_ = options;
try std.fmt.format(writer, "CuStream(device={}, stream={*})", .{ self.device, self._stream });
}
// TODO: I'd like to have an async method that suspends until the stream is over.
// Currently the best way too achieve something like this is to `suspend {} stream.synchronize();`
// once the stream is scheduled, and then `resume` once you are ready to wait
// for the blocking `synchronize` call.
// Ideally we would have an event loop that poll streams to check
// if they are over.
pub fn done(self: *Stream) bool {
const res = cu.cuStreamQuery(self._stream);
return res != cu.CUDA_ERROR_NOT_READY;
}
};
// TODO: return a device pointer
pub fn alloc(comptime DestType: type, size: usize) ![]DestType {
var int_ptr: cu.CUdeviceptr = undefined;
const byte_size = size * @sizeOf(DestType);
check(cu.cuMemAlloc(&int_ptr, byte_size)) catch |err| {
switch (err) {
error.OutOfMemory => {
var free_mem: usize = undefined;
var total_mem: usize = undefined;
const mb = 1024 * 1024;
check(cu.cuMemGetInfo(&free_mem, &total_mem)) catch return err;
log.err(
"Cuda OutOfMemory: tried to allocate {d:.1}Mb, free {d:.1}Mb, total {d:.1}Mb",
.{ byte_size / mb, free_mem / mb, total_mem / mb },
);
return err;
},
else => unreachable,
}
};
var ptr = @intToPtr([*]DestType, int_ptr);
return ptr[0..size];
}
// TODO: move all this to stream using async variants
pub fn free(device_ptr: anytype) void {
var raw_ptr: *anyopaque = if (meta.trait.isSlice(@TypeOf(device_ptr)))
@ptrCast(*anyopaque, device_ptr.ptr)
else
@ptrCast(*anyopaque, device_ptr);
_ = cu.cuMemFree(@ptrToInt(raw_ptr));
}
pub fn memset(comptime DestType: type, slice: []DestType, value: DestType) !void {
var d_ptr = @ptrToInt(slice.ptr);
var n = slice.len;
var memset_res = switch (@sizeOf(DestType)) {
1 => cu.cuMemsetD8(d_ptr, @bitCast(u8, value), n),
2 => cu.cuMemsetD16(d_ptr, @bitCast(u16, value), n),
4 => cu.cuMemsetD32(d_ptr, @bitCast(u32, value), n),
else => @compileError("memset doesn't support type: " ++ @typeName(DestType)),
};
try check(memset_res);
}
pub fn memsetD8(comptime DestType: type, slice: []DestType, value: u8) !void {
var d_ptr = @ptrToInt(slice.ptr);
var n = slice.len * @sizeOf(DestType);
try check(cu.cuMemsetD8(d_ptr, value, n));
}
pub fn allocAndCopy(comptime DestType: type, h_source: []const DestType) ![]DestType {
var ptr = try alloc(DestType, h_source.len);
try memcpyHtoD(DestType, ptr, h_source);
return ptr;
}
pub fn allocAndCopyResult(
comptime DestType: type,
host_allocator: std.mem.Allocator,
d_source: []const DestType,
) ![]DestType {
var h_tgt = try host_allocator.alloc(DestType, d_source.len);
try memcpyDtoH(DestType, h_tgt, d_source);
return h_tgt;
}
pub fn readResult(comptime DestType: type, d_source: *const DestType) !DestType {
var h_res: [1]DestType = undefined;
try check(cu.cuMemcpyDtoH(
@ptrCast(*anyopaque, &h_res),
@ptrToInt(d_source),
@sizeOf(DestType),
));
return h_res[0];
}
pub fn memcpyHtoD(comptime DestType: type, d_target: []DestType, h_source: []const DestType) !void {
std.debug.assert(h_source.len == d_target.len);
try check(cu.cuMemcpyHtoD(
@ptrToInt(d_target.ptr),
@ptrCast(*const anyopaque, h_source.ptr),
h_source.len * @sizeOf(DestType),
));
}
pub fn memcpyDtoH(comptime DestType: type, h_target: []DestType, d_source: []const DestType) !void {
std.debug.assert(d_source.len == h_target.len);
try check(cu.cuMemcpyDtoH(
@ptrCast(*anyopaque, h_target.ptr),
@ptrToInt(d_source.ptr),
d_source.len * @sizeOf(DestType),
));
}
pub fn push(value: anytype) !*@TypeOf(value) {
const DestType = @TypeOf(value);
var d_ptr = try alloc(DestType, 1);
try check(cu.cuMemcpyHtoD(
@ptrToInt(d_ptr.ptr),
@ptrCast(*const anyopaque, &value),
@sizeOf(DestType),
));
return @ptrCast(*DestType, d_ptr.ptr);
}
/// Time gpu event.
/// `deinit` is called when `elapsed` is called.
/// Note: we don't check errors, you'll receive Nan if any error happens.
/// start and stop are asynchronous, only elapsed is blocking and will wait
/// for the underlying operations to be over.
pub const GpuTimer = struct {
_start: cu.CUevent,
_stop: cu.CUevent,
// Here we take a pointer to the Zig struct.
// This way we can detect if we try to use a timer on a deleted stream
stream: *const Stream,
_elapsed: f32 = std.math.nan_f32,
pub fn start(stream: *const Stream) GpuTimer {
// The cuEvent are implicitly reffering to the current context.
// We don't know if the current context is the same than the stream context.
// Typically I'm not sure what happens with 2 streams on 2 gpus.
// We might need to restore the stream context before creating the events.
var timer = GpuTimer{ ._start = undefined, ._stop = undefined, .stream = stream };
_ = cu.cuEventCreate(&timer._start, 0);
_ = cu.cuEventCreate(&timer._stop, 0);
_ = cu.cuEventRecord(timer._start, stream._stream);
return timer;
}
pub fn deinit(self: *GpuTimer) void {
// Double deinit is allowed
if (self._stop == null) return;
_ = cu.cuEventDestroy(self._start);
self._start = null;
_ = cu.cuEventDestroy(self._stop);
self._stop = null;
}
pub fn stop(self: *GpuTimer) void {
_ = cu.cuEventRecord(self._stop, self.stream._stream);
}
/// Return the elapsed time in milliseconds.
/// Resolution is around 0.5 microseconds.
pub fn elapsed(self: *GpuTimer) f32 {
if (!std.math.isNan(self._elapsed)) return self._elapsed;
var _elapsed = std.math.nan_f32;
// _ = cu.cuEventSynchronize(self._stop);
_ = cu.cuEventElapsedTime(&_elapsed, self._start, self._stop);
self.deinit();
self._elapsed = _elapsed;
if (_elapsed < 1e-3) log.warn("Cuda events only have 0.5 microseconds of resolution, so this might not be precise", .{});
return _elapsed;
}
};
pub fn main() anyerror!void {
var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){};
const gpa = &general_purpose_allocator.allocator;
const args = try std.process.argsAlloc(gpa);
defer std.process.argsFree(gpa, args);
log.info("All your codebase are belong to us.", .{});
log.info("cuda: {}", .{cu.cuInit});
log.info("cuInit: {}", .{cu.cuInit(0)});
}
test "cuda version" {
log.warn("Cuda version: {d}", .{cu.CUDA_VERSION});
try testing.expect(cu.CUDA_VERSION > 11000);
try testing.expectEqual(cu.cuInit(0), cu.CUDA_SUCCESS);
}
var _device = [_]cu.CUdevice{-1} ** 8;
pub fn initDevice(device: u3) !cu.CUdevice {
var cu_dev = &_device[device];
if (cu_dev.* == -1) {
try check(cu.cuInit(0));
try check(cu.cuDeviceGet(cu_dev, device));
}
return cu_dev.*;
}
/// Returns the ctx for the given device
/// Given that we already assume one program == one module,
/// we can also assume one program == one context per GPU.
/// From Nvidia doc:
/// A host thread may have only one device context current at a time.
// TODO: who is responsible for destroying the context ?
// we should use cuCtxAttach and cuCtxDetach in stream init/deinit
var _ctx = [1]cu.CUcontext{null} ** 8;
fn getCtx(device: u3, cu_dev: cu.CUdevice) !cu.CUcontext {
var cu_ctx = &_ctx[device];
if (cu_ctx.* == null) {
try check(cu.cuCtxCreate(cu_ctx, 0, cu_dev));
}
return cu_ctx.*;
}
var _default_module: cu.CUmodule = null;
pub const kernel_ptx_content = if (cudaz_options.portable) @embedFile(cudaz_options.kernel_ptx_path) else [0:0]u8{};
fn defaultModule() cu.CUmodule {
if (_default_module != null) return _default_module;
const file = cudaz_options.kernel_ptx_path;
if (kernel_ptx_content.len == 0) {
log.warn("Loading Cuda module from local file {s}", .{file});
// Note: I tried to make this a path relative to the executable but failed because
// the main executable and the test executable are in different folder
// but refer to the same .ptx file.
check(cu.cuModuleLoad(&_default_module, file)) catch |err| {
std.debug.panic("Couldn't load cuda module: {s}: {}", .{ file, err });
};
} else {
log.info("Loading Cuda module from embedded file.", .{});
check(cu.cuModuleLoadData(&_default_module, kernel_ptx_content)) catch |err| {
std.debug.panic("Couldn't load embedded cuda module. Originally file was at {s}: {}", .{ file, err });
};
}
if (_default_module == null) {
std.debug.panic("Couldn't find module.", .{});
}
return _default_module;
}
/// Create a function with the correct signature for a cuda Kernel.
/// The kernel must come from the default .cu file
pub inline fn Function(comptime name: [:0]const u8) type {
return FnStruct(name, @field(cu, name));
}
pub fn FnStruct(comptime name: []const u8, comptime func: anytype) type {
return struct {
const Self = @This();
const CpuFn = func;
pub const Args = meta.ArgsTuple(@TypeOf(Self.CpuFn));
f: cu.CUfunction,
pub fn init() !Self {
var f: cu.CUfunction = undefined;
var code = cu.cuModuleGetFunction(&f, defaultModule(), @ptrCast([*c]const u8, name));
if (code != cu.CUDA_SUCCESS) log.err("Couldn't load function {s}", .{name});
try check(code);
var res = Self{ .f = f };
log.info("Loaded function {}@{}", .{ res, f });
return res;
}
// TODO: deinit -> CUDestroy
// Note: I'm not fond of having the primary launch be on the Function object,
// but it works best with Zig type inference
pub inline fn launch(self: *const Self, stream: *const Stream, grid: Grid, args: Args) !void {
if (args.len != @typeInfo(Args).Struct.fields.len) {
@compileError("Expected more arguments");
}
try self.launchWithSharedMem(stream, grid, 0, args);
}
pub fn launchWithSharedMem(self: *const Self, stream: *const Stream, grid: Grid, shared_mem: usize, args: Args) !void {
// TODO: this seems error prone, could we make the type of the shared buffer
// part of the function signature ?
try stream.launchWithSharedMem(self.f, grid, shared_mem, args);
}
pub fn debugCpuCall(grid: Grid, point: Grid, args: Args) void {
cu.threadIdx = point.threads.dim3();
cu.blockDim = grid.threads.dim3();
cu.blockIdx = point.blocks.dim3();
cu.gridDim = grid.blocks.dim3();
_ = @call(.{}, CpuFn, args);
}
pub fn format(
self: *const Self,
comptime fmt: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
_ = self;
_ = fmt;
_ = options;
try std.fmt.format(writer, "{s}(", .{name});
inline for (@typeInfo(Args).Struct.fields) |arg| {
const ArgT = arg.field_type;
try std.fmt.format(writer, "{}, ", .{ArgT});
}
try std.fmt.format(writer, ")", .{});
}
};
}
test "can read function signature from .cu files" {
log.warn("My kernel: {s}", .{@TypeOf(cu.rgba_to_greyscale)});
}
test "we use only one context per GPU" {
var default_ctx: cu.CUcontext = undefined;
try check(cu.cuCtxGetCurrent(&default_ctx));
std.log.warn("default_ctx: {any}", .{std.mem.asBytes(&default_ctx).*});
var stream = try Stream.init(0);
var stream_ctx: cu.CUcontext = undefined;
try check(cu.cuStreamGetCtx(stream._stream, &stream_ctx));
std.log.warn("stream_ctx: {any}", .{std.mem.asBytes(&stream_ctx).*});
// try testing.expectEqual(default_ctx, stream_ctx);
// Create a new stream
var stream2 = try Stream.init(0);
var stream2_ctx: cu.CUcontext = undefined;
try check(cu.cuStreamGetCtx(stream2._stream, &stream2_ctx));
std.log.warn("stream2_ctx: {any}", .{std.mem.asBytes(&stream2_ctx).*});
try testing.expectEqual(stream_ctx, stream2_ctx);
}
test "rgba_to_greyscale" {
var stream = try Stream.init(0);
defer stream.deinit();
log.warn("cuda: {}", .{stream});
const rgba_to_greyscale = try Function("rgba_to_greyscale").init();
const numRows: u32 = 10;
const numCols: u32 = 20;
const d_rgbaImage = try alloc([4]u8, numRows * numCols);
// try memset([4]u8, d_rgbaImage, [4]u8{ 0xaa, 0, 0, 255 });
const d_greyImage = try alloc(u8, numRows * numCols);
try memset(u8, d_greyImage, 0);
try stream.launch(
rgba_to_greyscale.f,
.{ .blocks = Dim3.init(numRows, numCols, 1) },
.{ d_rgbaImage, d_greyImage, numRows, numCols },
);
stream.synchronize();
}
test "safe kernel" {
const rgba_to_greyscale = try Function("rgba_to_greyscale").init();
var stream = try Stream.init(0);
defer stream.deinit();
const numRows: u32 = 10;
const numCols: u32 = 20;
var d_rgbaImage = try alloc(cu.uchar3, numRows * numCols);
// memset(cu.uchar3, d_rgbaImage, 0xaa);
const d_greyImage = try alloc(u8, numRows * numCols);
try memset(u8, d_greyImage, 0);
stream.synchronize();
log.warn("stream: {}, fn: {}", .{ stream, rgba_to_greyscale.f });
try rgba_to_greyscale.launch(
&stream,
.{ .blocks = Dim3.init(numCols, numRows, 1) },
// TODO: we should accept slices
.{ d_rgbaImage.ptr, d_greyImage.ptr, numRows, numCols },
);
}
test "cuda alloc" {
var stream = try Stream.init(0);
defer stream.deinit();
const d_greyImage = try alloc(u8, 128);
try memset(u8, d_greyImage, 0);
defer free(d_greyImage);
}
test "run the kernel on CPU" {
// This isn't very ergonomic, but it's possible !
// Also ironically it can't run in parallel because of the usage of the
// globals blockIdx and threadIdx.
// I think it could be useful to detect out of bound errors that Cuda
// tend to ignore.
const rgba_to_greyscale = Function("rgba_to_greyscale");
const rgbImage = [_]cu.uchar3{
.{ .x = 0x2D, .y = 0x24, .z = 0x1F },
.{ .x = 0xEB, .y = 0x82, .z = 0x48 },
};
var gray = [_]u8{ 0, 0 };
rgba_to_greyscale.debugCpuCall(
Grid.init1D(2, 1),
.{ .blocks = Dim3.init(0, 0, 0), .threads = Dim3.init(0, 0, 0) },
.{ &rgbImage, &gray, 1, 2 },
);
rgba_to_greyscale.debugCpuCall(
Grid.init1D(2, 1),
.{ .blocks = Dim3.init(0, 0, 0), .threads = Dim3.init(1, 0, 0) },
.{ &rgbImage, &gray, 1, 2 },
);
try testing.expectEqual([_]u8{ 38, 154 }, gray);
}
test "GpuTimer" {
const rgba_to_greyscale = try Function("rgba_to_greyscale").init();
var stream = try Stream.init(0);
defer stream.deinit();
const numRows: u32 = 10;
const numCols: u32 = 20;
var d_rgbaImage = try alloc(cu.uchar3, numRows * numCols);
// memset(cu.uchar3, d_rgbaImage, 0xaa);
const d_greyImage = try alloc(u8, numRows * numCols);
try memset(u8, d_greyImage, 0);
log.warn("stream: {}, fn: {}", .{ stream, rgba_to_greyscale.f });
var timer = GpuTimer.start(&stream);
try rgba_to_greyscale.launch(
&stream,
.{ .blocks = Dim3.init(numCols, numRows, 1) },
.{ d_rgbaImage.ptr, d_greyImage.ptr, numRows, numCols },
);
timer.stop();
stream.synchronize();
log.warn("rgba_to_greyscale took: {}", .{timer.elapsed()});
try testing.expect(timer.elapsed() > 0);
}
pub fn Kernels(comptime module: type) type {
// @compileLog(@typeName(module));
const decls = @typeInfo(module).Struct.decls;
var kernels: [decls.len]TypeInfo.StructField = undefined;
comptime var kernels_count = 0;
inline for (decls) |decl| {
if (decl.data != .Fn or !decl.data.Fn.is_export) continue;
kernels[kernels_count] = .{
.name = decl.name,
.field_type = FnStruct(decl.name, decl.data.Fn.fn_type),
.default_value = null,
.is_comptime = false,
.alignment = @alignOf(cu.CUfunction),
};
kernels_count += 1;
}
// @compileLog(kernels_count);
return @Type(TypeInfo{
.Struct = TypeInfo.Struct{
.is_tuple = false,
.layout = .Auto,
.decls = &[_]TypeInfo.Declaration{},
.fields = kernels[0..kernels_count],
},
});
}
pub fn loadKernels(comptime module: type) Kernels(module) {
const KernelType = Kernels(module);
var kernels: KernelType = undefined;
inline for (std.meta.fields(KernelType)) |field| {
@field(kernels, field.name) = field.field_type.init() catch unreachable;
}
return kernels;
} | cudaz/src/cuda.zig |
const std = @import("std");
const upaya = @import("upaya");
const data = @import("map.zig");
// var simple_map = @import("runtime_map.zig").Map.init(state.map);
// simple_map.saveAsJson("/Users/desaro/Desktop/hi.json");
// var buf = aya.mem.SdlBufferStream.init("/Users/desaro/Desktop/hi.json", .write);
// try std.json.stringify(simple_map, .{ .whitespace = .{} }, buf.writer());
// simple_map.deinit();
pub const Map = struct {
w: usize,
h: usize,
tile_size: usize,
tile_spacing: usize,
image: []const u8,
data: []u8,
ruleset: RuleSet,
pre_rulesets: []RuleSet,
tags: []Tag,
objects: []Object,
animations: []Animation,
pub fn init(orig: data.Map) Map {
var map = .{
.w = orig.w,
.h = orig.h,
.tile_size = orig.tile_size,
.tile_spacing = orig.tile_spacing,
.image = upaya.mem.allocator.dupe(u8, orig.image) catch unreachable,
.data = upaya.mem.allocator.alloc(u8, orig.w * orig.h) catch unreachable,
.ruleset = RuleSet.init(orig.ruleset),
.pre_rulesets = upaya.mem.allocator.alloc(RuleSet, orig.pre_rulesets.items.len) catch unreachable,
.tags = upaya.mem.allocator.alloc(Tag, orig.tags.items.len) catch unreachable,
.objects = upaya.mem.allocator.alloc(Object, orig.objects.items.len) catch unreachable,
.animations = upaya.mem.allocator.alloc(Animation, orig.animations.items.len) catch unreachable,
};
for (orig.pre_rulesets.items) |ruleset, i| {
map.pre_rulesets[i] = RuleSet.init(ruleset);
}
for (orig.tags.items) |tag, i| {
map.tags[i] = Tag.init(tag);
}
for (orig.objects.items) |obj, i| {
map.objects[i] = Object.init(obj);
}
for (orig.animations.items) |anim, i| {
map.animations[i] = Animation.init(anim);
}
return map;
}
pub fn deinit(self: Map) void {
upaya.mem.allocator.free(self.image);
upaya.mem.allocator.free(self.data);
self.ruleset.deinit();
for (self.pre_rulesets) |ruleset| {
ruleset.deinit();
}
upaya.mem.allocator.free(self.pre_rulesets);
for (self.tags) |tag| {
tag.deinit();
}
upaya.mem.allocator.free(self.tags);
for (self.objects) |obj| {
obj.deinit();
}
upaya.mem.allocator.free(self.objects);
for (self.animations) |anim| {
anim.deinit();
}
upaya.mem.allocator.free(self.animations);
}
pub fn saveAsJson(self: Map, file: []const u8) void {
var handle = try std.fs.cwd().createFile(file, .{});
defer handle.close();
std.json.stringify(self, .{ .whitespace = .{} }, handle.writer()) catch unreachable;
}
};
pub const RuleSet = struct {
seed: u64 = 0,
repeat: u8 = 20,
rules: []Rule,
pub fn init(orig: data.RuleSet) RuleSet {
var ruleset = RuleSet{ .seed = orig.seed, .repeat = orig.repeat, .rules = upaya.mem.allocator.alloc(Rule, orig.rules.items.len) catch unreachable };
for (orig.rules.items) |rule, i| {
ruleset.rules[i] = Rule.init(rule);
}
return ruleset;
}
pub fn deinit(self: RuleSet) void {
upaya.mem.allocator.free(self.rules);
}
};
pub const Rule = struct {
name: []const u8,
rule_tiles: []RuleTile,
chance: u8,
result_tiles: []u8,
group: u8,
pub fn init(orig: data.Rule) Rule {
var rule = Rule{
.name = upaya.mem.allocator.dupe(u8, &orig.name) catch unreachable,
.rule_tiles = upaya.mem.allocator.alloc(RuleTile, orig.rule_tiles.len) catch unreachable,
.chance = orig.chance,
.result_tiles = upaya.mem.allocator.dupe(u8, orig.result_tiles.items[0..orig.result_tiles.len]) catch unreachable,
.group = orig.group,
};
var i: usize = 0;
while (i < orig.rule_tiles.len) : (i += 1) {
const rt = orig.rule_tiles[i];
rule.rule_tiles[i] = .{ .tile = rt.tile, .state = @intToEnum(RuleTile.RuleState, @enumToInt(rt.state)) };
}
return rule;
}
pub fn deinit(self: Rule) void {
upaya.mem.allocator.free(self.name);
upaya.mem.allocator.free(self.rule_tiles);
upaya.mem.allocator.free(self.result_tiles);
}
};
pub const RuleTile = struct {
tile: usize,
state: RuleState,
pub const RuleState = enum(u4) {
none,
negated,
required,
pub fn jsonStringify(value: RuleState, options: std.json.StringifyOptions, out_stream: anytype) !void {
// try out_stream.writeAll("[\"something special\",");
try std.json.stringify(@enumToInt(value), options, out_stream);
// try out_stream.writeByte(']');
}
};
};
pub const Tag = struct {
name: []const u8,
tiles: []u8,
pub fn init(orig: data.Tag) Tag {
return .{ .name = upaya.mem.allocator.dupe(u8, &orig.name) catch unreachable, .tiles = upaya.mem.allocator.dupe(u8, orig.tiles.items[0..orig.tiles.len]) catch unreachable };
}
pub fn deinit(self: Tag) void {
upaya.mem.allocator.free(self.name);
upaya.mem.allocator.free(self.tiles);
}
};
pub const Object = struct {
id: u8 = 0,
name: []const u8,
x: usize = 0,
y: usize = 0,
props: []Prop,
pub const Prop = struct {
name: []const u8,
value: PropValue,
pub fn init(orig: data.Object.Prop) Prop {
var prop = Prop{ .name = upaya.mem.allocator.dupe(u8, &orig.name) catch unreachable, .value = undefined };
switch (orig.value) {
.string => |str| prop.value = .{ .string = upaya.mem.allocator.dupe(u8, &str) catch unreachable },
.int => |int| prop.value = .{ .int = int },
.float => |float| prop.value = .{ .float = float },
.link => |link| prop.value = .{ .link = link },
}
return prop;
}
pub fn deinit(self: Prop) void {
upaya.mem.allocator.free(self.name);
switch (self.value) {
.string => |str| {
upaya.mem.allocator.free(str);
},
else => {},
}
}
};
pub const PropValue = union(enum) {
string: []const u8,
int: i32,
float: f32,
link: u8,
};
pub fn init(orig: data.Object) Object {
var obj = Object{ .id = orig.id, .name = upaya.mem.allocator.dupe(u8, &orig.name) catch unreachable, .x = orig.x, .y = orig.y, .props = upaya.mem.allocator.alloc(Prop, orig.props.items.len) catch unreachable };
for (orig.props.items) |prop, i| {
obj.props[i] = Prop.init(prop);
}
return obj;
}
pub fn deinit(self: Object) void {
for (self.props) |prop| {
prop.deinit();
}
upaya.mem.allocator.free(self.props);
}
};
pub const Animation = struct {
tile: u8,
rate: u16,
tiles: []u8,
pub fn init(orig: data.Animation) Animation {
return .{ .tile = orig.tile, .rate = orig.rate, .tiles = upaya.mem.allocator.dupe(u8, orig.tiles.items[0..orig.tiles.len]) catch unreachable };
}
pub fn deinit(self: Animation) void {
upaya.mem.allocator.free(self.tiles);
}
}; | tilescript/runtime_map.zig |
const std = @import("std");
const bench = @import("root");
pub fn setup(gpa: std.mem.Allocator, options: *bench.Options) !void {
_ = gpa;
_ = options;
}
pub fn run(gpa: std.mem.Allocator, context: void) !void {
_ = context;
// Benchmarks ported from https://github.com/martinus/map_benchmark
const lower32bit = 0x00000000FFFFFFFF;
const upper32bit = 0xFFFFFFFF00000000;
const num_inserts = 2000;
const find_per_insert = 50_000;
randomFind(gpa, 4, lower32bit, num_inserts, find_per_insert, 0);
randomFind(gpa, 4, upper32bit, num_inserts, find_per_insert, 0);
randomFind(gpa, 3, lower32bit, num_inserts, find_per_insert, 24919456);
randomFind(gpa, 3, upper32bit, num_inserts, find_per_insert, 24919456);
randomFind(gpa, 2, lower32bit, num_inserts, find_per_insert, 49838914);
randomFind(gpa, 2, upper32bit, num_inserts, find_per_insert, 49838914);
randomFind(gpa, 1, lower32bit, num_inserts, find_per_insert, 74758370);
randomFind(gpa, 1, upper32bit, num_inserts, find_per_insert, 74758370);
randomFind(gpa, 0, lower32bit, num_inserts, find_per_insert, 99677826);
randomFind(gpa, 0, upper32bit, num_inserts, find_per_insert, 99677826);
}
fn randomFind(gpa: std.mem.Allocator, num_rand: u32, mask: u64, num_insert: u64, find_per_insert: u64, expected: u64) void {
const total = 4;
const find_per_iter = find_per_insert * total;
var rng = Sfc64.init(123);
var num_found: u64 = 0;
var insert_random = [_]bool{false} ** 4;
for (insert_random[0..num_rand]) |*b| b.* = true;
var other_rng = Sfc64.init(987654321);
const state = other_rng;
var find_rng = state;
{
var map = std.AutoHashMap(u64, u64).init(gpa);
var i: u64 = 0;
var find_count: u64 = 0;
while (i < num_insert) {
// insert NumTotal entries: some random, some sequential.
std.rand.Random.shuffle(rng.random(), bool, insert_random[0..]);
for (insert_random) |isRandomToInsert| {
const val = other_rng.next();
if (isRandomToInsert) {
_ = map.put(rng.next() & mask, 1) catch unreachable;
} else {
_ = map.put(val & mask, 1) catch unreachable;
}
i += 1;
}
var j: u64 = 0;
while (j < find_per_iter) : (j += 1) {
find_count += 1;
if (find_count > i) {
find_count = 0;
find_rng = state;
}
const key = find_rng.next() & mask;
if (map.get(key)) |val| num_found += val;
}
}
if (expected != num_found) @panic("bad result");
}
}
// Copy of std.rand.Sfc64 with a public next() function. The random API is
// slower than just calling next() and these benchmarks only require getting
// consecutive u64's.
pub const Sfc64 = struct {
a: u64 = undefined,
b: u64 = undefined,
c: u64 = undefined,
counter: u64 = undefined,
const Random = std.rand.Random;
const math = std.math;
const Rotation = 24;
const RightShift = 11;
const LeftShift = 3;
pub fn init(init_s: u64) Sfc64 {
var x = Sfc64{};
x.seed(init_s);
return x;
}
pub fn random(self: *Sfc64) Random {
return Random.init(self, fill);
}
pub fn next(self: *Sfc64) u64 {
const tmp = self.a +% self.b +% self.counter;
self.counter += 1;
self.a = self.b ^ (self.b >> RightShift);
self.b = self.c +% (self.c << LeftShift);
self.c = math.rotl(u64, self.c, Rotation) +% tmp;
return tmp;
}
fn seed(self: *Sfc64, init_s: u64) void {
self.a = init_s;
self.b = init_s;
self.c = init_s;
self.counter = 1;
var i: u32 = 0;
while (i < 12) : (i += 1) {
_ = self.next();
}
}
pub fn fill(self: *Sfc64, buf: []u8) void {
var i: usize = 0;
const aligned_len = buf.len - (buf.len & 7);
// Complete 8 byte segments.
while (i < aligned_len) : (i += 8) {
var n = self.next();
comptime var j: usize = 0;
inline while (j < 8) : (j += 1) {
buf[i + j] = @truncate(u8, n);
n >>= 8;
}
}
// Remaining. (cuts the stream)
if (i != buf.len) {
var n = self.next();
while (i < buf.len) : (i += 1) {
buf[i] = @truncate(u8, n);
n >>= 8;
}
}
}
}; | benchmarks/std-hash-map/random-find.zig |
const std = @import("std");
const ast = @import("ast.zig");
const gc = @import("gc.zig");
const Interpreter = @import("interpreter.zig").Interpreter;
const intrinsics = @import("intrinsics.zig");
/// Interpreter driver program
pub fn main() !void {
var interpreter = try Interpreter.init();
defer interpreter.deinit();
// Load the standard library
{
var args = std.ArrayList(*ast.Expr).init(gc.allocator);
defer args.deinit();
// Use path of bio binary for standard library path
const pwd = try std.fs.selfExeDirPathAlloc(gc.allocator);
defer gc.allocator.free(pwd);
const stdpath = try std.fs.path.join(gc.allocator, &[_][]const u8{ pwd, "std.lisp" });
defer gc.allocator.free(stdpath);
var stdlib = try ast.makeListExpr(&.{ &intrinsics.expr_atom_quote, try ast.makeAtomByDuplicating(stdpath) });
try args.append(stdlib);
_ = try intrinsics.stdImport(&interpreter, interpreter.env, args.items);
}
// Check if "run <file>" was passed
{
const process_args = try std.process.argsAlloc(gc.allocator);
defer std.process.argsFree(gc.allocator, process_args);
if (process_args.len > 1) {
if (std.mem.eql(u8, process_args[1], "run") and process_args.len > 2) {
const load_expr = try std.fmt.allocPrint(gc.allocator, "(import \"{s}\")", .{process_args[2]});
defer gc.allocator.free(load_expr);
_ = try interpreter.eval(interpreter.env, try interpreter.parse(load_expr));
return;
}
}
}
// Start REPL
interpreter.readEvalPrint() catch |err| {
try interpreter.printError(err);
};
}
// This invokes a test suite written in Bio. The tests will assert on error, which is why we check the exit code.
test "Evaluate standard library and test.lisp" {
var interpreter = try Interpreter.init();
defer interpreter.deinit();
_ = try interpreter.eval(interpreter.env, try interpreter.parse("(begin (import \"std.lisp\") (import \"test.lisp\"))"));
try std.testing.expectEqual(interpreter.exit_code, null);
}
// Leak detection during tests
test "Finalize" {
_ = gc.gpa.deinit();
} | src/main.zig |
const std = @import("std");
const Type = @import("types.zig").Type;
const testing = std.testing;
const allocator = std.heap.page_allocator;
pub const Status = extern union {
byte: Type.Byte,
bits: Bits,
pub const Name = enum {
Carry = 0,
Zero = 1,
Interrupt = 2,
Decimal = 3,
Break = 4,
UNUSED = 5,
Overflow = 6,
Negative = 7,
};
const Bits = packed struct {
C: Type.Bit,
Z: Type.Bit,
I: Type.Bit,
D: Type.Bit,
B: Type.Bit,
U: Type.Bit,
V: Type.Bit,
N: Type.Bit,
};
pub fn init() Status {
return Status.initFromByte(0);
}
pub fn initFromByte(byte: Type.Byte) Status {
var self = Status{
.byte = byte,
};
return self;
}
pub fn show(self: Status) void {
const out = std.io.getStdOut().outStream();
out.print("C={d} Z={d} I={d} D={d} B={d} V={d} N={d}\n", .{ self.bits.C, self.bits.Z, self.bits.I, self.bits.D, self.bits.B, self.bits.V, self.bits.N }) catch unreachable;
}
pub fn getBitByName(self: Status, name: Name) Type.Bit {
const shift = @enumToInt(name);
const mask = @as(Type.Byte, 1) << shift;
return if ((self.byte & mask) > 0) 1 else 0;
}
pub fn setBitByName(self: *Status, name: Name, bit: Type.Bit) void {
const shift = @enumToInt(name);
const mask = @as(Type.Byte, 1) << shift;
if (bit == 1) {
self.byte |= mask;
} else {
self.byte &= ~mask;
}
}
pub fn clear(self: *Status) void {
self.byte = 0;
}
};
test "create zero PS" {
var PS = Status.init();
testing.expect(PS.byte == 0);
testing.expect(PS.bits.C == 0);
PS.setBitByName(Status.Name.Carry, 1);
PS.bits.N = 1;
testing.expect(PS.getBitByName(Status.Name.Carry) == 1);
testing.expect(PS.bits.C == 1);
// PS.show();
PS.bits.C = 0;
testing.expect(PS.getBitByName(Status.Name.Carry) == 0);
testing.expect(PS.bits.C == 0);
}
test "create PS with initial byte value" {
const byte: Type.Byte = 0b10000000;
var PS = Status.initFromByte(byte);
testing.expect(PS.byte == byte);
testing.expect(PS.bits.C == 0);
testing.expect(PS.bits.N == 1);
testing.expect(PS.getBitByName(Status.Name.Negative) == 1);
testing.expect(PS.getBitByName(Status.Name.Carry) == 0);
}
test "create PS with initial bit values" {
var PS = Status.init();
PS.bits.C = 1;
PS.bits.V = 1;
PS.bits.N = 1;
// PS.show();
testing.expect(PS.byte == 0b11000001);
testing.expect(PS.getBitByName(Status.Name.Carry) == 1);
testing.expect(PS.getBitByName(Status.Name.Overflow) == 1);
testing.expect(PS.getBitByName(Status.Name.Negative) == 1);
testing.expect(PS.getBitByName(Status.Name.Zero) == 0);
testing.expect(PS.getBitByName(Status.Name.Interrupt) == 0);
testing.expect(PS.getBitByName(Status.Name.Decimal) == 0);
testing.expect(PS.getBitByName(Status.Name.Break) == 0);
testing.expect(PS.byte == 0b11000001);
} | src/status.zig |
const std = @import("std");
const aoc = @import("aoc-lib.zig");
fn get(bm: *aoc.ByteMap, x: usize, y: usize) usize {
var mw = bm.width();
var mh = bm.height();
var v = bm.getXY(x % mw, y % mh) - '0';
v += @intCast(u8, x / mw);
v += @intCast(u8, y / mh);
while (v > 9) : (v -= 9) {}
return @as(usize, v);
}
fn add(bm: *aoc.ByteMap, q: []std.ArrayList([2]usize), dist: []usize, x: usize, y: usize, d: usize, w: usize) !void {
var nd = d + get(bm, x, y);
var di = x + y * w;
if (dist[di] <= nd) {
return;
}
dist[di] = nd;
try q[nd].append([2]usize{ x, y });
}
pub fn parts(alloc: std.mem.Allocator, inp: []const u8) ![2]usize {
var bm = try aoc.ByteMap.init(alloc, inp);
defer bm.deinit();
return [2]usize{ try solve(alloc, bm, 1), try solve(alloc, bm, 5) };
}
pub fn solve(alloc: std.mem.Allocator, bm: *aoc.ByteMap, dim: usize) !usize {
var w = bm.width();
var h = bm.height();
w *= dim;
h *= dim;
var size = w * h;
var dist = try alloc.alloc(usize, size);
defer alloc.free(dist);
std.mem.set(usize, dist[0..], aoc.maxInt(usize));
var qsize = (w + h) * 9;
var q = try alloc.alloc(std.ArrayList([2]usize), qsize);
var i: usize = 0;
while (i < qsize) : (i += 1) {
q[i] = std.ArrayList([2]usize).init(alloc);
}
defer {
i = 0;
while (i < qsize) : (i += 1) {
q[i].deinit();
}
alloc.free(q);
}
try q[0].append([2]usize{ 0, 0 });
dist[0] = 0;
var qi: usize = 0;
while (qi < q.len) : (qi += 1) {
var j: usize = 0;
while (j < q[qi].items.len) : (j += 1) {
var xy: [2]usize = q[qi].items[j];
var x = xy[0];
var y = xy[1];
var vi = x + y * w;
var d = dist[vi];
if (x == w - 1 and y == h - 1) {
return d;
}
// try aoc.print("{}: {},{} = {}\n", .{ vi, x, y, d });
if (x > 0) {
try add(bm, q, dist, x - 1, y, d, w);
}
if (x < w - 1) {
try add(bm, q, dist, x + 1, y, d, w);
}
if (y > 0) {
try add(bm, q, dist, x, y - 1, d, w);
}
if (y < h - 1) {
try add(bm, q, dist, x, y + 1, d, w);
}
}
}
return 0;
}
test "parts" {
var t1 = try parts(aoc.talloc, aoc.test1file);
try aoc.assertEq(@as(usize, 40), t1[0]);
var r = try parts(aoc.talloc, aoc.inputfile);
try aoc.assertEq(@as(usize, 595), r[0]);
try aoc.assertEq(@as(usize, 315), t1[1]);
try aoc.assertEq(@as(usize, 2914), r[1]);
}
var buf: [16 * 1024 * 1024]u8 = undefined;
fn day15(inp: []const u8, bench: bool) anyerror!void {
var alloc = std.heap.FixedBufferAllocator.init(&buf);
var p = try parts(alloc.allocator(), inp);
if (!bench) {
try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] });
}
}
pub fn main() anyerror!void {
try aoc.benchme(aoc.input(), day15);
} | 2021/15/aoc.zig |
const kernel = @import("../../kernel.zig");
const x86_64 = @import("../x86_64.zig");
const Physical = kernel.Physical;
const Virtual = kernel.Virtual;
const TODO = kernel.TODO;
const log = kernel.log.scoped(.Paging_x86_64);
const PML4Table = [512]PML4E;
const PDPTable = [512]PDPTE;
const PDTable = [512]PDE;
const PTable = [512]PTE;
pub var should_log = false;
pub fn init(stivale_pmrs: []x86_64.Stivale2.Struct.PMRs.PMR) void {
log.debug("About to dereference memory regions", .{});
var bootloader_address_space = kernel.address_space;
kernel.address_space = kernel.Virtual.AddressSpace.new() orelse unreachable;
kernel.zero(kernel.address_space.arch.get_pml4().access([*]u8)[0..@sizeOf(PML4Table)]);
// Map the kernel and do some tests
{
for (stivale_pmrs) |pmr| {
const section_virtual_address = Virtual.Address.new(pmr.address);
const kernel_section_virtual_region = Virtual.Memory.Region.new(section_virtual_address, pmr.size);
const section_physical_address = bootloader_address_space.translate_address(section_virtual_address) orelse @panic("address not translated");
kernel_section_virtual_region.map(&kernel.address_space, section_physical_address, blk: {
var flags = kernel.Virtual.AddressSpace.Flags.empty();
const permissions = pmr.permissions;
const executable = permissions & x86_64.Stivale2.Struct.PMRs.PMR.executable != 0;
const readable = permissions & x86_64.Stivale2.Struct.PMRs.PMR.readable != 0;
//const writable = permissions & x86_64.Stivale2.Struct.PMRs.PMR.writable != 0;
if (!executable) {
flags.or_flag(.execute_disable);
}
kernel.assert(@src(), readable);
//if (writable) {
flags.or_flag(.read_write);
//}
break :blk flags;
});
}
}
for (kernel.Physical.Memory.map.usable) |region| {
region.descriptor.map(&kernel.address_space, region.descriptor.address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .read_write, .user }));
}
log.debug("Mapped usable", .{});
for (kernel.Physical.Memory.map.reclaimable) |region| {
region.descriptor.map(&kernel.address_space, region.descriptor.address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .read_write, .user }));
}
log.debug("Mapped reclaimable", .{});
for (kernel.Physical.Memory.map.framebuffer) |region| {
region.map(&kernel.address_space, region.address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .read_write, .user }));
}
log.debug("Mapped framebuffer", .{});
//for (kernel.Physical.Memory.map.reserved) |region| {
//region.map(&kernel.address_space, region.address.to_higher_half_virtual_address(), kernel.Virtual.AddressSpace.Flags.empty());
//}
kernel.address_space.make_current();
// Update physical pointers to virtual ones
kernel.Physical.Memory.map.usable.ptr = @intToPtr(@TypeOf(kernel.Physical.Memory.map.usable.ptr), @ptrToInt(kernel.Physical.Memory.map.usable.ptr) + kernel.higher_half_direct_map.value);
kernel.Physical.Memory.map.reclaimable.ptr = @intToPtr(@TypeOf(kernel.Physical.Memory.map.reclaimable.ptr), @ptrToInt(kernel.Physical.Memory.map.reclaimable.ptr) + kernel.higher_half_direct_map.value);
kernel.Physical.Memory.map.framebuffer.ptr = @intToPtr(@TypeOf(kernel.Physical.Memory.map.framebuffer.ptr), @ptrToInt(kernel.Physical.Memory.map.framebuffer.ptr) + kernel.higher_half_direct_map.value);
kernel.Physical.Memory.map.reserved.ptr = @intToPtr(@TypeOf(kernel.Physical.Memory.map.reserved.ptr), @ptrToInt(kernel.Physical.Memory.map.reserved.ptr) + kernel.higher_half_direct_map.value);
kernel.Physical.Memory.map.kernel_and_modules.ptr = @intToPtr(@TypeOf(kernel.Physical.Memory.map.kernel_and_modules.ptr), @ptrToInt(kernel.Physical.Memory.map.kernel_and_modules.ptr) + kernel.higher_half_direct_map.value);
kernel.Virtual.initialized = true;
log.debug("Memory mapping initialized!", .{});
for (kernel.Physical.Memory.map.reclaimable) |*region| {
const bitset = region.get_bitset();
const bitset_size = bitset.len * @sizeOf(kernel.Physical.Memory.Map.Entry.BitsetBaseType);
region.allocated_size = kernel.align_forward(bitset_size, kernel.arch.page_size);
region.setup_bitset();
}
const old_reclaimable = kernel.Physical.Memory.map.reclaimable.len;
kernel.Physical.Memory.map.usable.len += old_reclaimable;
kernel.Physical.Memory.map.reclaimable.len = 0;
log.debug("Reclaimed reclaimable physical memory. Counting with {} more regions", .{old_reclaimable});
var insertion_result = false;
insertion_result = kernel.address_space.free_regions_by_address.insert(&kernel.memory_region.item_address, &kernel.memory_region, kernel.memory_region.address.value, .panic);
kernel.assert(@src(), insertion_result);
insertion_result = kernel.address_space.free_regions_by_size.insert(&kernel.memory_region.item_size, &kernel.memory_region, kernel.memory_region.size, .allow);
kernel.assert(@src(), insertion_result);
log.debug("Set root for Virtual Memory Manager tree", .{});
log.debug("Tree address (free/addr): 0x{x}", .{@ptrToInt(&kernel.address_space.free_regions_by_address)});
log.debug("Tree address (free/size): 0x{x}", .{@ptrToInt(&kernel.address_space.free_regions_by_size)});
log.debug("Tree address (used): 0x{x}", .{@ptrToInt(&kernel.address_space.used_regions)});
for (Physical.Memory.map.usable) |physical_entry| {
kernel.address_space.integrate_mapped_physical_entry(physical_entry, physical_entry.descriptor.address.to_higher_half_virtual_address()) catch @panic("unable to integrate physical region into vmm");
}
log.debug("Finished the integration of usable regions into the kernel address space successfully!", .{});
for (Physical.Memory.map.framebuffer) |physical_region| {
kernel.address_space.integrate_mapped_physical_region(physical_region, physical_region.address.to_higher_half_virtual_address()) catch @panic("unable to integrate physical region into vmm");
}
log.debug("Finished the integration of framebuffer regions into the kernel address space successfully!", .{});
for (Physical.Memory.map.usable) |physical_entry| {
log.debug("(0x{x},\t0x{x}) - 0x{x}", .{ physical_entry.descriptor.address.value, physical_entry.descriptor.address.value + physical_entry.descriptor.size, physical_entry.descriptor.address.value + physical_entry.allocated_size });
}
log.debug("Paging initialized", .{});
}
pub const AddressSpace = struct {
cr3: u64 = 0,
const Indices = [kernel.enum_values(PageIndex).len]u16;
pub inline fn new() ?AddressSpace {
const page_count = kernel.bytes_to_pages(@sizeOf(PML4Table), true);
const cr3_physical_address = kernel.Physical.Memory.allocate_pages(page_count) orelse return null;
return AddressSpace{
.cr3 = cr3_physical_address.value,
};
}
pub inline fn from_current() AddressSpace {
return AddressSpace{
.cr3 = x86_64.cr3.read_raw(),
};
}
pub inline fn from_context(context: anytype) AddressSpace {
// This is taking a u64 instead of a physical address to easily put here the value of the CR3 register
comptime kernel.assert_unsafe(@TypeOf(context) == u64);
const cr3 = context;
return AddressSpace{
.cr3 = cr3,
};
}
pub fn get_pml4(address_space: AddressSpace) Physical.Address {
return Physical.Address.new(address_space.cr3);
}
pub fn map_kernel_address_space_higher_half(address_space: AddressSpace) void {
const used_memory_before = kernel.Physical.Memory.map.get_used_memory();
const cr3 = address_space.cr3;
// TODO: proper address
const cr3_physical_address = kernel.Physical.Address.new(cr3);
const cr3_virtual_address = cr3_physical_address.to_higher_half_virtual_address();
kernel.address_space.map(cr3_physical_address, cr3_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .read_write, .user }));
const pml4 = cr3_virtual_address.access(*PML4Table);
kernel.zero_slice(pml4[0..0x100]);
kernel.copy(PML4E, pml4[0x100..], kernel.Physical.Address.new(kernel.address_space.arch.cr3).access_higher_half(*PML4Table)[0x100..]);
const used_memory_after = kernel.Physical.Memory.map.get_used_memory();
const memory_overhead = used_memory_after - used_memory_before;
log.debug("USER CR3: 0x{x}", .{cr3_physical_address.value});
log.debug("Kernel used memory: {}", .{used_memory_after});
log.debug("Kernel mapping memory overhead: {}", .{memory_overhead});
}
pub fn map(arch_address_space: *AddressSpace, physical_address: Physical.Address, virtual_address: Virtual.Address, flags: kernel.Virtual.AddressSpace.Flags) void {
if (should_log) log.debug("Init mapping", .{});
kernel.assert(@src(), virtual_address.is_page_aligned());
kernel.assert(@src(), physical_address.is_page_aligned());
const indices = compute_indices(virtual_address);
var pdp: *volatile PDPTable = undefined;
{
var pml4 = arch_address_space.get_pml4().access(*PML4Table);
var pml4_entry = &pml4[indices[@enumToInt(PageIndex.PML4)]];
var pml4_entry_value = pml4_entry.value;
if (pml4_entry_value.contains(.present)) {
pdp = get_address_from_entry_bits(pml4_entry_value.bits).access(@TypeOf(pdp));
} else {
const pdp_allocation = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(@sizeOf(PDPTable), true)) orelse @panic("unable to alloc pdp");
pdp = pdp_allocation.access(@TypeOf(pdp));
pdp.* = kernel.zeroes(PDPTable);
pml4_entry_value.or_flag(.present);
pml4_entry_value.or_flag(.read_write);
pml4_entry_value.or_flag(.user);
pml4_entry_value.bits = set_entry_in_address_bits(pml4_entry_value.bits, pdp_allocation);
pml4_entry.value = pml4_entry_value;
}
}
if (should_log) log.debug("PDP", .{});
var pd: *volatile PDTable = undefined;
{
var pdp_entry = &pdp[indices[@enumToInt(PageIndex.PDP)]];
var pdp_entry_value = pdp_entry.value;
if (pdp_entry_value.contains(.present)) {
pd = get_address_from_entry_bits(pdp_entry_value.bits).access(@TypeOf(pd));
} else {
const pd_allocation = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(@sizeOf(PDTable), true)) orelse @panic("unable to alloc pd");
pd = pd_allocation.access(@TypeOf(pd));
pd.* = kernel.zeroes(PDTable);
pdp_entry_value.or_flag(.present);
pdp_entry_value.or_flag(.read_write);
pdp_entry_value.or_flag(.user);
pdp_entry_value.bits = set_entry_in_address_bits(pdp_entry_value.bits, pd_allocation);
pdp_entry.value = pdp_entry_value;
}
}
var pt: *volatile PTable = undefined;
{
var pd_entry = &pd[indices[@enumToInt(PageIndex.PD)]];
var pd_entry_value = pd_entry.value;
if (pd_entry_value.contains(.present)) {
pt = get_address_from_entry_bits(pd_entry_value.bits).access(@TypeOf(pt));
} else {
const pt_allocation = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(@sizeOf(PTable), true)) orelse @panic("unable to alloc pt");
pt = pt_allocation.access(@TypeOf(pt));
pt.* = kernel.zeroes(PTable);
pd_entry_value.or_flag(.present);
pd_entry_value.or_flag(.read_write);
pd_entry_value.or_flag(.user);
pd_entry_value.bits = set_entry_in_address_bits(pd_entry_value.bits, pt_allocation);
pd_entry.value = pd_entry_value;
}
}
pt[indices[@enumToInt(PageIndex.PT)]] = blk: {
var pte = PTE{
.value = PTE.Flags.empty(),
};
if (flags.contains(.read_write)) {
pte.value.or_flag(.read_write);
}
if (flags.contains(.user)) {
pte.value.or_flag(.user);
}
pte.value.or_flag(.present);
pte.value.bits = set_entry_in_address_bits(pte.value.bits, physical_address);
break :blk pte;
};
if (should_log) log.debug("Ended mapping", .{});
}
pub fn translate_address(address_space: *AddressSpace, virtual_address: Virtual.Address) ?Physical.Address {
kernel.assert(@src(), virtual_address.is_page_aligned());
const indices = compute_indices(virtual_address);
var pdp: *volatile PDPTable = undefined;
{
//log.debug("CR3: 0x{x}", .{address_space.cr3});
var pml4 = address_space.get_pml4().access(*PML4Table);
const pml4_entry = &pml4[indices[@enumToInt(PageIndex.PML4)]];
var pml4_entry_value = pml4_entry.value;
if (!pml4_entry_value.contains(.present)) return null;
//log.debug("PML4 present", .{});
pdp = get_address_from_entry_bits(pml4_entry_value.bits).access(@TypeOf(pdp));
}
if (should_log) log.debug("PDP", .{});
var pd: *volatile PDTable = undefined;
{
var pdp_entry = &pdp[indices[@enumToInt(PageIndex.PDP)]];
var pdp_entry_value = pdp_entry.value;
if (!pdp_entry_value.contains(.present)) return null;
//log.debug("PDP present", .{});
pd = get_address_from_entry_bits(pdp_entry_value.bits).access(@TypeOf(pd));
}
if (should_log) log.debug("PD", .{});
var pt: *volatile PTable = undefined;
{
var pd_entry = &pd[indices[@enumToInt(PageIndex.PD)]];
var pd_entry_value = pd_entry.value;
if (!pd_entry_value.contains(.present)) return null;
//log.debug("PD present", .{});
pt = get_address_from_entry_bits(pd_entry_value.bits).access(@TypeOf(pt));
}
if (should_log) log.debug("PT", .{});
const pte = pt[indices[@enumToInt(PageIndex.PT)]];
if (!pte.value.contains(.present)) return null;
return get_address_from_entry_bits(pte.value.bits);
}
fn compute_indices(virtual_address: Virtual.Address) Indices {
var indices: Indices = undefined;
var va = virtual_address.value;
va = va >> 12;
indices[3] = @truncate(u9, va);
va = va >> 9;
indices[2] = @truncate(u9, va);
va = va >> 9;
indices[1] = @truncate(u9, va);
va = va >> 9;
indices[0] = @truncate(u9, va);
return indices;
}
pub fn make_current(address_space: *AddressSpace) void {
log.debug("Applying address space: 0x{x}", .{address_space.cr3});
x86_64.cr3.write_raw(address_space.cr3);
log.debug("Applied address space: 0x{x}", .{address_space.cr3});
}
};
const address_mask: u64 = 0x000000fffffff000;
fn set_entry_in_address_bits(old_entry_value: u64, new_address: Physical.Address) u64 {
kernel.assert(@src(), kernel.Physical.Address.max_bit == 40);
kernel.assert(@src(), new_address.is_page_aligned());
const address_masked = new_address.value & address_mask;
const old_entry_value_masked = old_entry_value & ~address_masked;
const result = address_masked | old_entry_value_masked;
return result;
}
fn get_address_from_entry_bits(entry_bits: u64) Physical.Address {
kernel.assert(@src(), kernel.Physical.Address.max_bit == 40);
const address = entry_bits & address_mask;
kernel.assert(@src(), kernel.is_aligned(address, kernel.arch.page_size));
return Physical.Address.new(address);
}
const PageIndex = enum(u3) {
PML4 = 0,
PDP = 1,
PD = 2,
PT = 3,
};
const PML4E = struct {
value: Flags,
const Flags = kernel.Bitflag(true, enum(u64) {
present = 0,
read_write = 1,
user = 2,
page_level_write_through = 3,
page_level_cache_disable = 4,
accessed = 5,
hlat_restart = 11,
execute_disable = 63, // IA32_EFER.NXE must be 1
});
};
const PDPTE = struct {
value: Flags,
const Flags = kernel.Bitflag(true, enum(u64) {
present = 0,
read_write = 1,
user = 2,
page_level_write_through = 3,
page_level_cache_disable = 4,
accessed = 5,
page_size = 7, // must be 0
hlat_restart = 11,
execute_disable = 63, // IA32_EFER.NXE must be 1
});
};
const PDE = struct {
value: Flags,
const Flags = kernel.Bitflag(true, enum(u64) {
present = 0,
read_write = 1,
user = 2,
page_level_write_through = 3,
page_level_cache_disable = 4,
accessed = 5,
page_size = 7, // must be 0
hlat_restart = 11,
execute_disable = 63, // IA32_EFER.NXE must be 1
});
};
const PTE = struct {
value: Flags,
const Flags = kernel.Bitflag(true, enum(u64) {
present = 0,
read_write = 1,
user = 2,
page_level_write_through = 3,
page_level_cache_disable = 4,
accessed = 5,
dirty = 6,
pat = 7, // must be 0
global = 8,
hlat_restart = 11,
// TODO: protection key
execute_disable = 63, // IA32_EFER.NXE must be 1
});
};
pub const HandlePageFaultFlags = kernel.Bitflag(false, enum(u32) {
write = 0,
supervisor = 1,
});
pub const HandlePageFaultError = error{};
pub fn handle_page_fault(virtual_address: Virtual.Address, flags: HandlePageFaultFlags) !void {
log.debug("Handling page fault", .{});
if (flags.contains(.supervisor)) {
if (virtual_address.belongs_to_region(kernel.memory_region)) {} else {
@panic("can't map to unknown region");
}
} else {
@panic("can't handle page fault for user mode");
}
log.debug("why are we here");
unreachable;
} | src/kernel/arch/x86_64/paging.zig |
pub const XK_BackSpace = 0xff08;
pub const XK_Tab = 0xff09;
pub const XK_Return = 0xff0d;
pub const XK_Pause = 0xff13;
pub const XK_Scroll_Lock = 0xff14;
pub const XK_Escape = 0xff1b;
pub const XK_Delete = 0xffff;
pub const XK_Home = 0xff50;
pub const XK_Left = 0xff51;
pub const XK_Up = 0xff52;
pub const XK_Right = 0xff53;
pub const XK_Down = 0xff54;
pub const XK_Page_Up = 0xff55;
pub const XK_Page_Down = 0xff56;
pub const XK_End = 0xff57;
pub const XK_Print = 0xff61;
pub const XK_Insert = 0xff63;
pub const XK_Menu = 0xff67;
pub const XK_Mode_switch = 0xff7e;
pub const XK_Num_Lock = 0xff7f;
pub const XK_KP_Enter = 0xff8d;
pub const XK_KP_Home = 0xff95;
pub const XK_KP_Left = 0xff96;
pub const XK_KP_Up = 0xff97;
pub const XK_KP_Right = 0xff98;
pub const XK_KP_Down = 0xff99;
pub const XK_KP_Page_Up = 0xff9a;
pub const XK_KP_Page_Down = 0xff9b;
pub const XK_KP_End = 0xff9c;
pub const XK_KP_Begin = 0xff9d;
pub const XK_KP_Insert = 0xff9e;
pub const XK_KP_Delete = 0xff9f;
pub const XK_KP_Equal = 0xffbd;
pub const XK_KP_Multiply = 0xffaa;
pub const XK_KP_Add = 0xffab;
pub const XK_KP_Subtract = 0xffad;
pub const XK_KP_Decimal = 0xffae;
pub const XK_KP_Divide = 0xffaf;
pub const XK_KP_0 = 0xffb0;
pub const XK_KP_1 = 0xffb1;
pub const XK_KP_2 = 0xffb2;
pub const XK_KP_3 = 0xffb3;
pub const XK_KP_4 = 0xffb4;
pub const XK_KP_5 = 0xffb5;
pub const XK_KP_6 = 0xffb6;
pub const XK_KP_7 = 0xffb7;
pub const XK_KP_8 = 0xffb8;
pub const XK_KP_9 = 0xffb9;
pub const XK_F1 = 0xffbe;
pub const XK_F2 = 0xffbf;
pub const XK_F3 = 0xffc0;
pub const XK_F4 = 0xffc1;
pub const XK_F5 = 0xffc2;
pub const XK_F6 = 0xffc3;
pub const XK_F7 = 0xffc4;
pub const XK_F8 = 0xffc5;
pub const XK_F9 = 0xffc6;
pub const XK_F10 = 0xffc7;
pub const XK_F11 = 0xffc8;
pub const XK_F12 = 0xffc9;
pub const XK_F13 = 0xffca;
pub const XK_F14 = 0xffcb;
pub const XK_F15 = 0xffcc;
pub const XK_F16 = 0xffcd;
pub const XK_F17 = 0xffce;
pub const XK_F18 = 0xffcf;
pub const XK_F19 = 0xffd0;
pub const XK_F20 = 0xffd1;
pub const XK_F21 = 0xffd2;
pub const XK_F22 = 0xffd3;
pub const XK_F23 = 0xffd4;
pub const XK_F24 = 0xffd5;
pub const XK_F25 = 0xffd6;
pub const XK_Shift_L = 0xffe1;
pub const XK_Shift_R = 0xffe2;
pub const XK_Control_L = 0xffe3;
pub const XK_Control_R = 0xffe4;
pub const XK_Caps_Lock = 0xffe5;
pub const XK_Shift_Lock = 0xffe6;
pub const XK_Meta_L = 0xffe7;
pub const XK_Meta_R = 0xffe8;
pub const XK_Alt_L = 0xffe9;
pub const XK_Alt_R = 0xffea;
pub const XK_Super_L = 0xffeb;
pub const XK_Super_R = 0xffec;
pub const XK_space = 0x0020;
pub const XK_apostrophe = 0x0027;
pub const XK_comma = 0x002c;
pub const XK_minus = 0x002d;
pub const XK_period = 0x002e;
pub const XK_slash = 0x002f;
pub const XK_0 = 0x0030;
pub const XK_1 = 0x0031;
pub const XK_2 = 0x0032;
pub const XK_3 = 0x0033;
pub const XK_4 = 0x0034;
pub const XK_5 = 0x0035;
pub const XK_6 = 0x0036;
pub const XK_7 = 0x0037;
pub const XK_8 = 0x0038;
pub const XK_9 = 0x0039;
pub const XK_semicolon = 0x003b;
pub const XK_equal = 0x003d;
pub const XK_bracketleft = 0x005b;
pub const XK_backslash = 0x005c;
pub const XK_bracketright = 0x005d;
pub const XK_grave = 0x0060;
pub const XK_a = 0x0061;
pub const XK_b = 0x0062;
pub const XK_c = 0x0063;
pub const XK_d = 0x0064;
pub const XK_e = 0x0065;
pub const XK_f = 0x0066;
pub const XK_g = 0x0067;
pub const XK_h = 0x0068;
pub const XK_i = 0x0069;
pub const XK_j = 0x006a;
pub const XK_k = 0x006b;
pub const XK_l = 0x006c;
pub const XK_m = 0x006d;
pub const XK_n = 0x006e;
pub const XK_o = 0x006f;
pub const XK_p = 0x0070;
pub const XK_q = 0x0071;
pub const XK_r = 0x0072;
pub const XK_s = 0x0073;
pub const XK_t = 0x0074;
pub const XK_u = 0x0075;
pub const XK_v = 0x0076;
pub const XK_w = 0x0077;
pub const XK_x = 0x0078;
pub const XK_y = 0x0079;
pub const XK_z = 0x007a; | src/xcb/keys.zig |
const std = @import("std");
const zang = @import("zang");
const wav = @import("wav");
const example = @import("example_song.zig");
const TOTAL_TIME = 19 * example.AUDIO_SAMPLE_RATE;
const bytes_per_sample = switch (example.AUDIO_FORMAT) {
.signed8 => 1,
.signed16_lsb => 2,
};
var g_outputs:
[example.MainModule.num_outputs][example.AUDIO_BUFFER_SIZE]f32
= undefined;
var g_temps:
[example.MainModule.num_temps][example.AUDIO_BUFFER_SIZE]f32
= undefined;
var g_big_buffer:
[TOTAL_TIME * bytes_per_sample * example.MainModule.num_outputs]u8
= undefined;
pub fn main() !void {
var main_module = example.MainModule.init();
var start: usize = 0;
while (start < TOTAL_TIME) {
const len = std.math.min(example.AUDIO_BUFFER_SIZE, TOTAL_TIME - start);
const span = zang.Span {
.start = 0,
.end = len,
};
var outputs: [example.MainModule.num_outputs][]f32 = undefined;
var temps: [example.MainModule.num_temps][]f32 = undefined;
var i: usize = undefined;
i = 0; while (i < example.MainModule.num_outputs) : (i += 1) {
outputs[i] = g_outputs[i][0..];
zang.zero(span, outputs[i]);
}
i = 0; while (i < example.MainModule.num_temps) : (i += 1) {
temps[i] = g_temps[i][0..];
}
main_module.paint(span, outputs, temps);
i = 0; while (i < example.MainModule.num_outputs) : (i += 1) {
const m = bytes_per_sample * example.MainModule.num_outputs;
zang.mixDown(
g_big_buffer[start * m .. (start + len) * m],
outputs[i][span.start .. span.end],
example.AUDIO_FORMAT,
example.MainModule.num_outputs,
i,
0.25,
);
}
start += len;
}
if (example.AUDIO_FORMAT == .signed8) {
// convert from signed to unsigned 8-bit
for (g_big_buffer) |*byte| {
const signed_byte = @bitCast(i8, byte.*);
byte.* = @intCast(u8, i16(signed_byte) + 128);
}
}
const file = try std.fs.cwd().createFile("out.wav", .{});
defer file.close();
var stream = file.outStream();
const Saver = wav.Saver(@TypeOf(stream));
try Saver.save(&stream, .{
.num_channels = example.MainModule.num_outputs,
.sample_rate = example.AUDIO_SAMPLE_RATE,
.format = switch (example.AUDIO_FORMAT) {
.signed8 => .unsigned8,
.signed16_lsb => .signed16_lsb,
},
.data = g_big_buffer[0..],
});
} | examples/write_wav.zig |
const std = @import("std");
const pactl = @import("./pactl.zig");
const ArgsOption = enum {
Volume, Muted, Status, Help, None
};
const Args = struct {
option: ArgsOption,
id: ?pactl.SinkId,
pub fn init(allocator: *std.mem.Allocator, iterator: *std.process.ArgIterator) anyerror!Args {
_ = iterator.skip(); // Skip program name
var option = ArgsOption.None;
if (iterator.next(allocator)) |given_option| {
if (std.mem.eql(u8, "volume", given_option catch "")) {
option = ArgsOption.Volume;
} else if (std.mem.eql(u8, "muted", given_option catch "")) {
option = ArgsOption.Muted;
} else if (std.mem.eql(u8, "status", given_option catch "")) {
option = ArgsOption.Status;
}
}
var id: ?pactl.SinkId = null;
if (iterator.next(allocator)) |given_id| {
const given_id_for_real_now = try given_id;
id = pactl.SinkId{ .value = given_id_for_real_now };
}
return Args{ .option = option, .id = id };
}
};
const help =
\\Usage: pactl-analyzer <command> [sink-name]
\\A simple tool that parses chosen values from the output of `pactl list sinks`.
\\
\\Commands:
\\ help Prints this message
\\ volume Prints the volume formatted as %
\\ muted Prints the muted status
\\ status Prints the sink status (volume, muted or none)
\\
\\
;
pub fn main() anyerror!void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
var arena = std.heap.ArenaAllocator.init(&gpa.allocator);
defer arena.deinit();
const args = try Args.init(&arena.allocator, &std.process.args());
var env_map = try std.process.getEnvMap(&arena.allocator);
try env_map.set("LANG", "C");
const info_result = try std.ChildProcess.exec(.{
.allocator = &arena.allocator,
.argv = &[_][]const u8{ "pactl", "info" },
.env_map = &env_map,
});
const list_result = try std.ChildProcess.exec(.{
.allocator = &arena.allocator,
.argv = &[_][]const u8{ "pactl", "list", "sinks" },
.env_map = &env_map,
});
const sink_id = args.id orelse try pactl.get_default_sink_id(info_result.stdout);
const sink = pactl.get_sink(try pactl.get_all_sinks(&arena.allocator, list_result.stdout), sink_id);
const stdout = std.io.getStdOut().writer();
switch (args.option) {
ArgsOption.Help => try stdout.print("{}", .{help}),
ArgsOption.Volume => try stdout.print("{}%\n", .{(sink.?).volume}),
ArgsOption.Muted => try stdout.print("{}\n", .{(sink.?).muted}),
ArgsOption.Status => {
if (sink) |v| {
if (v.muted) {
try stdout.print("MUTED\n", .{});
} else {
try stdout.print("{}%\n", .{(sink.?).volume});
}
} else {
try stdout.print("NONE\n", .{});
}
},
ArgsOption.None => {
try stdout.print("{}", .{help});
std.process.exit(1);
},
}
} | src/main.zig |
const std = @import("std");
const format = @import("format.zig");
const value = @import("value.zig");
const expect = std.testing.expect;
const Format = format.Format;
pub const DecodeError = error{
EmptyInput,
TruncatedInput,
ReservedFormat,
ReservedFormatInInput,
InvalidMapKeyType,
InvalidType,
InvalidNumberSize,
NilFormatWithNonOptionalType,
} || error{OutOfMemory};
pub const Decoder = struct {
allocator: *std.mem.Allocator,
strictNumberSize: bool = true,
allowUnknownStructFields: bool = false,
pub fn decode(self: *Decoder, comptime T: type, buf: []const u8) DecodeError!T {
if (buf.len == 0) {
return error.EmptyInput;
}
const fmt = format.from_u8(buf[0]);
return switch (@typeInfo(T)) {
.Null => switch (fmt) {
Format.nil => null,
else => error.InvalidType,
},
.Bool => switch (fmt) {
Format.bool_true => true,
Format.bool_false => false,
else => error.InvalidType,
},
.Int => |intInfo| switch (intInfo.is_signed) {
true => readIntAny(T, buf, self.strictNumberSize),
false => readUintAny(T, buf, self.strictNumberSize),
},
.Float => readFloatAny(T, buf, self.strictNumberSize),
.Optional => |optionalInfo| switch (fmt) {
Format.nil => null,
else => try self.decode(optionalInfo.child, buf),
},
.Array => |arrayInfo| switch (arrayInfo.child) {
u8 => readStrOrBinAny(self.allocator, buf),
else => self.decodeArrayAny(arrayInfo.child, buf),
},
.Pointer => |pointerInfo| switch (pointerInfo.size) {
.One => switch (pointerInfo.child) {
u8 => readStrOrBinAny(self.allocator, buf),
else => self.decode(pointerInfo.child, buf),
},
.Slice => switch (pointerInfo.child) {
u8 => readStrOrBinAny(self.allocator, buf),
else => self.decode(pointerInfo.child, buf),
},
else => error.UnsupportedType,
},
else => switch (fmt) {
Format.nil => error.NilFormatWithNonOptionalType,
Format.never_used => error.ReservedFormatInInput,
else => unreachable,
},
};
}
fn decodeArrayAny(comptime T: type, buf: []const u8) DecodeError!T {
unreachable;
}
};
pub fn decode(comptime T: type, allocator: *std.mem.Allocator, buf: []const u8) DecodeError!T {
var decoder = Decoder{
.allocator = allocator,
};
return decoder.decode(T, buf);
}
fn readStrOrBinAny(
allocator: *std.mem.Allocator,
buf: []const u8,
) DecodeError![]u8 {
var str = try readStrOrBinAnyConst(allocator, buf);
var out = try allocator.alloc(u8, str.len);
std.mem.copy(u8, out, str);
return out;
}
fn readStrOrBinAnyConst(
allocator: *std.mem.Allocator,
buf: []const u8,
) DecodeError![]const u8 {
return switch (format.from_u8(buf[0])) {
Format.fix_str => |len| readFixStr(buf[1..], len),
Format.str8 => readStr8(buf[1..]),
Format.str16 => readStr16(buf[1..]),
Format.str32 => readStr32(buf[1..]),
Format.bin8 => readBin8(buf[1..]),
Format.bin16 => readBin16(buf[1..]),
Format.bin32 => readBin32(buf[1..]),
else => error.InvalidType,
};
}
fn readFloatAny(comptime T: type, buf: []const u8, strictSize: bool) DecodeError!T {
const bits = @typeInfo(T).Float.bits;
const fmt = format.from_u8(buf[0]);
var fbuf = buf[1..];
// first check if we are actually decoding a float
switch (fmt) {
Format.float32 => {},
Format.float64 => {},
else => return error.InvalidType,
}
return switch (bits) {
32 => switch (fmt) {
Format.float32 => readFloat32(T, fbuf),
else => error.InvalidNumberSize,
},
64 => switch (strictSize) {
true => switch (fmt) {
Format.float64 => readFloat64(T, fbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.float32 => readFloat32(T, fbuf),
Format.float64 => readFloat64(T, fbuf),
else => error.InvalidNumberSize,
},
},
else => error.InvalidType,
};
}
fn readIntAny(comptime T: type, buf: []const u8, strictSize: bool) DecodeError!T {
const bits = @typeInfo(T).Int.bits;
const fmt = format.from_u8(buf[0]);
var intbuf = buf[1..];
// first check if we are actually decoding a int
switch (fmt) {
Format.negative_fix_int => {},
Format.int8 => {},
Format.int16 => {},
Format.int32 => {},
Format.int64 => {},
else => return error.InvalidType,
}
return switch (bits) {
8 => switch (fmt) {
Format.negative_fix_int => |val| val,
Format.int8 => readInt8(T, intbuf),
else => error.InvalidNumberSize,
},
16 => switch (strictSize) {
true => switch (fmt) {
Format.int16 => readInt16(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.negative_fix_int => |val| @intCast(i16, val),
Format.int8 => readInt8(T, intbuf),
Format.int16 => readInt16(T, intbuf),
else => error.InvalidNumberSize,
},
},
32 => switch (strictSize) {
true => switch (fmt) {
Format.int32 => readInt32(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.negative_fix_int => |val| @intCast(i32, val),
Format.int8 => readInt8(T, intbuf),
Format.int16 => readInt16(T, intbuf),
Format.int32 => readInt32(T, intbuf),
else => error.InvalidNumberSize,
},
},
64 => switch (strictSize) {
true => switch (fmt) {
Format.int64 => readInt64(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.negative_fix_int => |val| @intCast(i64, val),
Format.int8 => readInt8(T, intbuf),
Format.int16 => readInt16(T, intbuf),
Format.int32 => readInt32(T, intbuf),
Format.int64 => readInt64(T, intbuf),
else => error.InvalidNumberSize,
},
},
else => error.InvalidType,
};
}
fn readUintAny(comptime T: type, buf: []const u8, strictSize: bool) DecodeError!T {
const bits = @typeInfo(T).Int.bits;
const fmt = format.from_u8(buf[0]);
var intbuf = buf[1..];
// first check if we are actually decoding a uint
switch (fmt) {
Format.positive_fix_int => {},
Format.uint8 => {},
Format.uint16 => {},
Format.uint32 => {},
Format.uint64 => {},
else => return error.InvalidType,
}
return switch (bits) {
8 => switch (fmt) {
Format.positive_fix_int => |val| val,
Format.uint8 => readUint8(T, intbuf),
else => error.InvalidNumberSize,
},
16 => switch (strictSize) {
true => switch (fmt) {
Format.uint16 => readUint16(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.positive_fix_int => |val| @intCast(u16, val),
Format.uint8 => readUint8(T, intbuf),
Format.uint16 => readUint16(T, intbuf),
else => error.InvalidNumberSize,
},
},
32 => switch (strictSize) {
true => switch (fmt) {
Format.uint32 => readInt32(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.positive_fix_int => |val| @intCast(u32, val),
Format.uint8 => readUint8(T, intbuf),
Format.uint16 => readUint16(T, intbuf),
Format.uint32 => readUint32(T, intbuf),
else => error.InvalidNumberSize,
},
},
64 => switch (strictSize) {
true => switch (fmt) {
Format.uint64 => readUint64(T, intbuf),
else => error.InvalidNumberSize,
},
false => switch (fmt) {
Format.positive_fix_int => |val| @intCast(u64, val),
Format.uint8 => readUint8(T, intbuf),
Format.uint16 => readUint16(T, intbuf),
Format.uint32 => readUint32(T, intbuf),
Format.uint64 => readUint64(T, intbuf),
else => error.InvalidNumberSize,
},
},
else => error.InvalidType,
};
}
pub fn readBin8(buf: []const u8) DecodeError![]const u8 {
var n = try readUint8(u8, buf);
var sbuf = buf[1..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readBin16(buf: []const u8) DecodeError![]const u8 {
var n = try readUint16(u16, buf);
var sbuf = buf[2..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readBin32(buf: []const u8) DecodeError![]const u8 {
var n = try readUint32(u32, buf);
var sbuf = buf[4..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readFixStr(buf: []const u8, len: u8) DecodeError![]const u8 {
if (buf.len < len) {
return error.TruncatedInput;
}
return buf[0..len];
}
pub fn readStr8(buf: []const u8) DecodeError![]const u8 {
var n = try readUint8(u8, buf);
var sbuf = buf[1..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readStr16(buf: []const u8) DecodeError![]const u8 {
var n = try readUint16(u16, buf);
var sbuf = buf[2..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readStr32(buf: []const u8) DecodeError![]const u8 {
var n = try readUint32(u32, buf);
var sbuf = buf[4..];
if (sbuf.len < n) {
return error.TruncatedInput;
}
return sbuf[0..n];
}
pub fn readUint8(comptime U: type, buf: []const u8) DecodeError!U {
if (buf.len < @sizeOf(u8)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(u8, buf[0..@sizeOf(u8)]);
}
pub fn readUint16(comptime U: type, buf: []const u8) DecodeError!U {
if (buf.len < @sizeOf(u16)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(u16, buf[0..@sizeOf(u16)]);
}
pub fn readUint32(comptime U: type, buf: []const u8) DecodeError!U {
if (buf.len < @sizeOf(u32)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(u32, buf[0..@sizeOf(u32)]);
}
pub fn readUint64(comptime U: type, buf: []const u8) DecodeError!U {
if (buf.len < @sizeOf(u64)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(u64, buf[0..@sizeOf(u64)]);
}
pub fn readInt8(comptime I: type, buf: []const u8) DecodeError!I {
if (buf.len < @sizeOf(i8)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(i8, buf[0..@sizeOf(i8)]);
}
pub fn readInt16(comptime I: type, buf: []const u8) DecodeError!I {
if (buf.len < @sizeOf(i16)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(i16, buf[0..@sizeOf(i16)]);
}
pub fn readInt32(comptime I: type, buf: []const u8) DecodeError!I {
if (buf.len < @sizeOf(i32)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(i32, buf[0..@sizeOf(i32)]);
}
pub fn readInt64(comptime I: type, buf: []const u8) DecodeError!I {
if (buf.len < @sizeOf(i64)) {
return error.TruncatedInput;
}
return std.mem.readIntBig(i64, buf[0..@sizeOf(i64)]);
}
pub fn readFloat32(comptime F: type, buf: []const u8) DecodeError!F {
if (buf.len < @sizeOf(f32)) {
return error.TruncatedInput;
}
return @bitCast(f32, std.mem.readIntBig(u32, buf[0..@sizeOf(f32)]));
}
pub fn readFloat64(comptime F: type, buf: []const u8) DecodeError!F {
if (buf.len < @sizeOf(f64)) {
return error.TruncatedInput;
}
return @bitCast(f64, std.mem.readIntBig(u64, buf[0..@sizeOf(f64)]));
}
test "empty input" {
var data: [0]u8 = undefined;
if (decode(i32, std.testing.allocator, data[0..])) {
@panic("unexpected OK with empty input");
} else |err| switch (err) {
error.EmptyInput => {},
else => @panic("invalid error received, expected empty input"),
}
}
test "decode nil" {
const hex = "c0";
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
var v = try decode(?bool, std.testing.allocator, data[0..]);
expect(v == null);
}
test "decode bool false" {
const hex = "c2";
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
var v = try decode(?bool, std.testing.allocator, data[0..]);
expect(v == false);
// null
var hex2 = "c0";
var data2: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data2[0..], hex2);
v = try decode(?bool, std.testing.allocator, data2[0..]);
expect(v == null);
}
test "decode bool true" {
const hex = "c3";
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
var v = try decode(?bool, std.testing.allocator, data[0..]);
expect(v == true);
}
test "decode int8" {
const hex = "d085"; // -123
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
// decode strict first
var v = try decode(i8, std.testing.allocator, data[0..]);
expect(v == -123);
// decode error now trying to use wrong type with strict setting
if (decode(i32, std.testing.allocator, data[0..])) {
@panic("unexpected OK with wrong type and strict");
} else |err| switch (err) {
error.InvalidNumberSize => {},
else => @panic("invalid error received, expected truncated input"),
}
// decode non-strict
var decoder = Decoder{
.allocator = std.testing.allocator,
.strictNumberSize = false,
};
var v2 = try decoder.decode(i64, data[0..]);
expect(v2 == -123);
}
test "decode int16" {
const hex = "d1fb30"; // -1232
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
// decode strict first
var v = try decode(i16, std.testing.allocator, data[0..]);
expect(v == -1232);
// decode error now trying to use wrong type with strict setting
if (decode(i32, std.testing.allocator, data[0..])) {
@panic("unexpected OK with wrong type and strict");
} else |err| switch (err) {
error.InvalidNumberSize => {},
else => @panic("invalid error received, expected truncated input"),
}
// decode non-strict
var decoder = Decoder{
.allocator = std.testing.allocator,
.strictNumberSize = false,
};
var v2 = try decoder.decode(i64, data[0..]);
expect(v2 == -1232);
// decode non-strict but error for size too small
// decode error now trying to use wrong type with strict setting
if (decoder.decode(i8, data[0..])) {
@panic("unexpected OK with wrong type and strict");
} else |err| switch (err) {
error.InvalidNumberSize => {},
else => @panic("invalid error received, expected truncated input"),
}
}
test "decode float32" {
const hex = "ca40918c7d"; // 4.548399448394775
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
// decode strict first
var v = try decode(f32, std.testing.allocator, data[0..]);
expect(v == 4.548399448394775);
// decode non-strict
var decoder = Decoder{
.allocator = std.testing.allocator,
.strictNumberSize = false,
};
var v2 = try decoder.decode(f64, data[0..]);
expect(v2 == 4.548399448394775);
// decode non-strict but error for size too small
// decode error now trying to use wrong type with strict setting
if (decoder.decode(i8, data[0..])) {
@panic("unexpected OK with wrong type and strict");
} else |err| switch (err) {
error.InvalidType => {},
else => @panic("invalid error received, expected InvalidType"),
}
}
test "decode const str8" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
var v = try decode([]const u8, std.testing.allocator, data[0..]);
defer std.testing.allocator.free(v);
expect(std.mem.eql(u8, "hello world hello world hello world", v));
}
test "decode str8" {
const hex = "d92368656c6c6f20776f726c642068656c6c6f20776f726c642068656c6c6f20776f726c64"; // "hello world hello world hello world"
var data: [hex.len / 2]u8 = undefined;
try std.fmt.hexToBytes(data[0..], hex);
var v = try decode([]u8, std.testing.allocator, data[0..]);
defer std.testing.allocator.free(v);
expect(std.mem.eql(u8, "hello world hello world hello world", v));
} | src/decode.zig |
const std = @import("std");
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const AutoHashMap = std.AutoHashMap;
const StringHashMap = std.StringHashMap;
// Useful stdlib functions
const tokenize = std.mem.tokenize;
const split = std.mem.split;
const trim = std.mem.trim;
const parseInt = std.fmt.parseInt;
const parseFloat = std.fmt.parseFloat;
const min = std.math.min;
const min3 = std.math.min3;
const max = std.math.max;
const max3 = std.math.max3;
const print = std.debug.print;
const assert = std.debug.assert;
const sort = std.sort.sort;
const asc = std.sort.asc;
const desc = std.sort.desc;
const util = @import("util.zig");
const gpa = util.gpa;
const Rotation = [3][3]i32;
const rotations: [24]Rotation = [24]Rotation{
// X+
Rotation{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, 1 } }, // 0
Rotation{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 0, 1, 0 } }, // 1
Rotation{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, -1 } }, // 2
Rotation{ [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 0, -1, 0 } }, // 3
// X-
Rotation{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, 1 } }, // 4
Rotation{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 0, 1, 0 } }, // 5
Rotation{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, -1 } }, // 6
Rotation{ [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 0, -1, 0 } }, // 7
// Y+
Rotation{ [3]i32{ 0, 1, 0 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, 1 } }, // 8
Rotation{ [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ 1, 0, 0 } }, // 9
Rotation{ [3]i32{ 0, 1, 0 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, -1 } }, // 10
Rotation{ [3]i32{ 0, 1, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ -1, 0, 0 } }, // 11
// Y-
Rotation{ [3]i32{ 0, -1, 0 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 0, 1 } }, // 12
Rotation{ [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, -1 }, [3]i32{ 1, 0, 0 } }, // 13
Rotation{ [3]i32{ 0, -1, 0 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 0, -1 } }, // 14
Rotation{ [3]i32{ 0, -1, 0 }, [3]i32{ 0, 0, 1 }, [3]i32{ -1, 0, 0 } }, // 15
// Z+
Rotation{ [3]i32{ 0, 0, 1 }, [3]i32{ 0, 1, 0 }, [3]i32{ -1, 0, 0 } }, // 16
Rotation{ [3]i32{ 0, 0, 1 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, 1, 0 } }, // 17
Rotation{ [3]i32{ 0, 0, 1 }, [3]i32{ 0, -1, 0 }, [3]i32{ 1, 0, 0 } }, // 18
Rotation{ [3]i32{ 0, 0, 1 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, -1, 0 } }, // 19
// Z-
Rotation{ [3]i32{ 0, 0, -1 }, [3]i32{ 0, -1, 0 }, [3]i32{ -1, 0, 0 } }, // 20
Rotation{ [3]i32{ 0, 0, -1 }, [3]i32{ -1, 0, 0 }, [3]i32{ 0, 1, 0 } }, // 21
Rotation{ [3]i32{ 0, 0, -1 }, [3]i32{ 0, 1, 0 }, [3]i32{ 1, 0, 0 } }, // 22
Rotation{ [3]i32{ 0, 0, -1 }, [3]i32{ 1, 0, 0 }, [3]i32{ 0, -1, 0 } }, // 23
};
const Point = struct {
x: i32,
y: i32,
z: i32,
fn cmp(a: Point, b: Point) std.math.Order {
if (a.x == b.x) {
if (a.y == b.y) {
return std.math.order(a.z, b.z);
} else {
return std.math.order(a.y, b.y);
}
} else {
return std.math.order(a.x, b.x);
}
}
fn cmpAsc(ctx: void, a: Point, b: Point) bool {
if (a.x == b.x) {
if (a.y == b.y) {
return a.z < b.z;
} else {
return a.y < b.y;
}
} else {
return a.x < b.x;
}
}
fn add(a: Point, b: Point) Point {
return .{
.x = a.x + b.x,
.y = a.y + b.y,
.z = a.z + b.z,
};
}
fn diff(a: Point, b: Point) Point {
return .{
.x = a.x - b.x,
.y = a.y - b.y,
.z = a.z - b.z,
};
}
fn dist(a: Point, b: Point) f32 {
var dx: f32 = @intToFloat(f32, a.x - b.x);
var dy: f32 = @intToFloat(f32, a.y - b.y);
var dz: f32 = @intToFloat(f32, a.z - b.z);
return std.math.sqrt(dx * dx + dy * dy + dz * dz);
}
fn manDist(a: Point, b: Point) i32 {
var x = std.math.absInt(a.x - b.x) catch unreachable;
var y = std.math.absInt(a.y - b.y) catch unreachable;
var z = std.math.absInt(a.z - b.z) catch unreachable;
return x + y + z;
}
fn rotate(p: Point, r: Rotation) Point {
var x = r[0][0] * p.x + r[0][1] * p.y + r[0][2] * p.z;
var y = r[1][0] * p.x + r[1][1] * p.y + r[1][2] * p.z;
var z = r[2][0] * p.x + r[2][1] * p.y + r[2][2] * p.z;
return .{ .x = x, .y = y, .z = z };
}
};
const Scanner = struct {
points: ArrayList(Point),
dists: ArrayList(IdxDist),
allocator: *Allocator,
idx: u64,
solved: bool = false,
offset: Point = .{ .x = 0, .y = 0, .z = 0 },
const IdxDist = struct {
const Self = @This();
dist: f32,
a: usize,
b: usize,
fn cmp(a: Self, b: Self) std.math.Order {
return std.math.order(a.dist, b.dist);
}
fn cmpAsc(ctx: void, a: Self, b: Self) bool {
return a.dist < b.dist;
}
};
fn init(idx: u64, allocator: *Allocator) Scanner {
var points = ArrayList(Point).init(allocator);
var dists = ArrayList(IdxDist).init(allocator);
var s = Scanner{ .points = points, .dists = dists, .allocator = allocator, .idx = idx };
return s;
}
fn deinit(self: Scanner) void {
self.points.deinit();
self.dists.deinit();
}
fn addPoint(self: *Scanner, point: Point) void {
var new_idx = self.points.items.len;
for (self.points.items) |p, idx| {
var d = p.dist(point);
self.dists.append(.{ .dist = d, .a = idx, .b = new_idx }) catch unreachable;
}
self.points.append(point) catch unreachable;
sort(IdxDist, self.dists.items, {}, IdxDist.cmpAsc);
}
fn distsMatchCount(self: Scanner, other: Scanner) u64 {
var count: u64 = 0;
var a = self.dists.items;
var b = other.dists.items;
var idx: usize = 0;
var jdx: usize = 0;
while (idx < a.len and jdx < b.len) {
if (std.math.approxEqAbs(f32, a[idx].dist, b[jdx].dist, 0.001)) {
count += 1;
idx += 1;
jdx += 1;
} else if (a[idx].dist < b[jdx].dist) {
idx += 1;
} else if (a[idx].dist > b[jdx].dist) {
jdx += 1;
}
}
return count;
}
fn rotateAndMatch(self: *Scanner, other: *Scanner) void {
var candidates_a = ArrayList(Point).init(self.allocator);
var candidates_b = ArrayList(Point).init(self.allocator);
defer candidates_a.deinit();
defer candidates_b.deinit();
// Obtain candidates.
{
var points_a = self.points.items;
var points_b = other.points.items;
var flags_a = self.allocator.alloc(u64, points_a.len) catch unreachable;
var flags_b = self.allocator.alloc(u64, points_b.len) catch unreachable;
defer self.allocator.free(flags_a);
defer self.allocator.free(flags_b);
std.mem.set(u64, flags_a, 0);
std.mem.set(u64, flags_b, 0);
var dists_a = self.dists.items;
var dists_b = other.dists.items;
var idx: usize = 0;
var jdx: usize = 0;
while (idx < dists_a.len and jdx < dists_b.len) {
var da = dists_a[idx];
var db = dists_b[jdx];
if (std.math.approxEqAbs(f32, da.dist, db.dist, 0.001)) {
// print("Match: {} {} {} {}\n", .{da.a, da.b, db.a, db.b});
flags_a[da.a] += 1;
flags_a[da.b] += 1;
flags_b[db.a] += 1;
flags_b[db.b] += 1;
if (flags_a[da.a] == 10) candidates_a.append(points_a[da.a]) catch unreachable;
if (flags_a[da.b] == 10) candidates_a.append(points_a[da.b]) catch unreachable;
if (flags_b[db.a] == 10) candidates_b.append(points_b[db.a]) catch unreachable;
if (flags_b[db.b] == 10) candidates_b.append(points_b[db.b]) catch unreachable;
idx += 1;
jdx += 1;
} else if (da.dist < db.dist) {
idx += 1;
} else if (da.dist > db.dist) {
jdx += 1;
}
}
sort(Point, candidates_a.items, {}, Point.cmpAsc);
sort(Point, candidates_b.items, {}, Point.cmpAsc);
assert(candidates_a.items.len > 10);
assert(candidates_b.items.len > 10);
assert(candidates_a.items.len == candidates_b.items.len);
}
// Try all rotations and sort.
{
var rot_answer: ?Rotation = null;
var offset_answer: ?Point = null;
var rot_idx: usize = 0;
var q = candidates_b.items[0];
var old_orient = candidates_a.items;
var new_orient = self.allocator.alloc(Point, candidates_b.items.len) catch unreachable;
defer self.allocator.free(new_orient);
for (rotations) |r, ridx| {
for (candidates_b.items) |p, idx| {
new_orient[idx] = p.rotate(r);
}
q = new_orient[0];
sort(Point, new_orient, {}, Point.cmpAsc);
var offset = old_orient[0].diff(new_orient[0]);
for (old_orient) |p, idx| {
if (p.diff(new_orient[idx]).cmp(offset) != .eq) break;
} else {
rot_answer = r;
offset_answer = offset;
rot_idx = ridx;
break;
}
}
if (rot_answer) |rot| {
var offset = offset_answer.?;
print("Offset found: {d} {d} {d} (R: {})\n", .{ offset.x, offset.y, offset.z, rot_idx });
for (other.points.items) |*p, idx| {
p.* = p.rotate(rot).add(offset);
}
other.solved = true;
other.offset = offset;
}
}
}
};
fn parseScannerName(line: []const u8) u64 {
print("{s}\n", .{line});
var splits = split(line, " ");
_ = splits.next().?;
_ = splits.next().?;
return parseInt(u64, splits.next().?, 0) catch unreachable;
}
fn printPoints(points: []Point) void {
for (points) |p| {
print("{d},{d},{d}\n", .{ p.x, p.y, p.z });
}
print("\n", .{});
}
fn printScannerSorted(scanner: Scanner) void {
var points = gpa.alloc(Point, scanner.points.items.len) catch unreachable;
defer gpa.free(points);
std.mem.copy(Point, points, scanner.points.items);
sort(Point, points, {}, Point.cmpAsc);
print("--- scanner {} ({}) - {d},{d},{d} ---\n", .{ scanner.idx, scanner.solved, scanner.offset.x, scanner.offset.y, scanner.offset.z });
printPoints(points);
}
const Answer = struct {
part1: usize,
part2: i32,
};
fn compute(data: []const u8) Answer {
var lines = tokenize(data, "\r\n");
var scanners = ArrayList(Scanner).init(gpa);
defer {
for (scanners.items) |s| {
s.deinit();
}
scanners.deinit();
}
var line0 = lines.next().?;
var active_scanner = Scanner.init(parseScannerName(line0), gpa);
while (lines.next()) |line| {
if (std.mem.eql(u8, line[0..3], "---")) {
scanners.append(active_scanner) catch unreachable;
active_scanner = Scanner.init(parseScannerName(line), gpa);
} else {
var splits = split(line, ",");
var x = parseInt(i32, splits.next().?, 0) catch unreachable;
var y = parseInt(i32, splits.next().?, 0) catch unreachable;
var z = parseInt(i32, splits.next().?, 0) catch unreachable;
var p = Point{ .x = x, .y = y, .z = z };
active_scanner.addPoint(p);
}
}
scanners.append(active_scanner) catch unreachable;
// Print Graph.
{
print(" ", .{});
for (scanners.items) |a, idx| {
print(" {d: >2}", .{idx});
}
for (scanners.items) |a, idx| {
print("\n{d: >2}:", .{idx});
for (scanners.items) |b, jdx| {
if (idx != jdx) {
var d = a.distsMatchCount(b);
if (d > 60) {
print(" {d: >2}", .{d});
} else {
print(" ", .{});
}
} else {
print(" ", .{});
}
}
}
print("\n\n", .{});
}
// Rotate and solve scanners.
{
scanners.items[0].solved = true;
printScannerSorted(scanners.items[0]);
var solved_count: usize = 1;
while (solved_count < scanners.items.len) {
for (scanners.items) |*a| {
if (a.*.solved) continue;
for (scanners.items) |*b| {
if (!b.*.solved) continue;
if (a.distsMatchCount(b.*) < 60) continue;
b.rotateAndMatch(a);
printScannerSorted(a.*);
solved_count += 1;
break;
}
}
}
}
var answer = Answer{ .part1 = 0, .part2 = 0 };
// Count points.
{
var all_points = AutoHashMap(Point, bool).init(gpa);
defer all_points.deinit();
for (scanners.items) |s| {
for (s.points.items) |p| {
all_points.put(p, true) catch unreachable;
}
}
answer.part1 = all_points.count();
}
// Dist scanners.
{
var result: i32 = 0;
for (scanners.items) |a| {
for (scanners.items) |b| {
result = max(result, a.offset.manDist(b.offset));
}
}
answer.part2 = result;
}
return answer;
}
pub fn main() !void {
const data = @embedFile("../data/puzzle/day19.txt");
var answer = compute(data);
print("Part 1: {}\n", .{answer.part1});
print("Part 2: {}\n", .{answer.part2});
}
test "sample data" {
const data = @embedFile("../data/test/day19.txt");
var answer = compute(data);
try std.testing.expectEqual(answer.part1, 79);
try std.testing.expectEqual(answer.part2, 3621);
} | src/day19.zig |
const std = @import("std");
var a: *std.mem.Allocator = undefined;
const stdout = std.io.getStdOut().writer(); //prepare stdout to write in
test "aoc example" {
const in =
\\abc
\\
\\a
\\b
\\c
\\
\\ab
\\ac
\\
\\a
\\a
\\a
\\a
\\
\\z
\\
;
var b = in.*;
const ans = run(&b);
std.debug.print("{}\n", .{ans});
std.testing.expect(ans == 6);
}
fn run(input: [:0]u8) u32 {
var out: u32 = 0;
var is_first: bool = true;
var questions: u26 = 0;
var group_questions: u26 = 0;
var all_lines_it = std.mem.split(input, "\n");
comptime var offset: u5 = 0;
while (all_lines_it.next()) |line| {
if (line.len == 0) {
// Group analysis
inline while (offset < 26) : (offset += 1) {
if ((group_questions & (@as(u26, 1) << offset)) != 0) {
out += 1;
}
}
offset = 0;
group_questions = 0;
is_first = true;
} else {
// Create summary for this person
questions = 0;
for (line) |char| {
questions |= @as(u26, 1) << @intCast(u5, (char - 'a'));
}
// If first, create first flag
if (is_first) {
group_questions = questions;
is_first = false;
} else {
// else, &= with group
group_questions &= questions;
}
}
}
inline while (offset < 26) : (offset += 1) {
if ((group_questions & (@as(u26, 1) << offset)) != 0) {
out += 1;
}
}
return out;
}
pub fn main() !void {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // create memory allocator for strings
defer arena.deinit(); // clear memory
var arg_it = std.process.args();
_ = arg_it.skip(); // skip over exe name
a = &arena.allocator; // get ref to allocator
const input: [:0]u8 = try (arg_it.next(a)).?; // get the first argument
const start: i128 = std.time.nanoTimestamp(); // start time
const answer = run(input); // compute answer
const elapsed_nano: f128 = @intToFloat(f128, std.time.nanoTimestamp() - start);
const elapsed_milli: f64 = @floatCast(f64, @divFloor(elapsed_nano, 1_000_000));
try stdout.print("_duration:{d}\n{}\n", .{ elapsed_milli, answer }); // emit actual lines parsed by AOC
} | day-06/part-2/lelithium.zig |
const std = @import("std");
const engine = @import("kiragine");
usingnamespace engine.kira.log;
const check = engine.check;
const kira = engine.kira;
const ft2 = kira.ft2;
const gl = kira.gl;
const c = kira.c;
const math = kira.math;
const Mat4x4f = math.mat4x4.Generic(f32);
const Vec3f = math.vec3.Generic(f32);
const vertexshader =
\\#version 330 core
\\layout (location = 0) in vec4 vertex; // <vec2 pos, vec2 tex>
\\out vec2 TexCoords;
\\
\\uniform mat4 projection;
\\
\\void main()
\\{
\\ gl_Position = projection * vec4(vertex.xy, 0.0, 1.0);
\\ TexCoords = vertex.zw;
\\}
;
const fragmentshader =
\\#version 330 core
\\in vec2 TexCoords;
\\out vec4 color;
\\
\\uniform sampler2D text;
\\uniform vec3 textColor;
\\
\\void main()
\\{
\\ vec4 sampled = vec4(1.0, 1.0, 1.0, texture(text, TexCoords).r);
\\ color = vec4(textColor, 1.0) * sampled;
\\}
;
const Char = struct {
textureid: u32 = 0,
codepoint: u64 = 0,
sizex: i32 = 0,
sizey: i32 = 0,
bearingx: i32 = 0,
bearingy: i32 = 0,
advance: i32 = 0,
};
var window_running = false;
var targetfps: f64 = 0;
var chars: std.ArrayList(Char) = undefined;
pub fn main() !void {
try kira.glfw.init();
defer kira.glfw.deinit();
kira.glfw.resizable(false);
kira.glfw.initGLProfile();
var window = kira.window.Info{};
var frametime = kira.window.FrameTime{};
var fps = kira.window.FpsDirect{};
window.title = "test-font";
window.callbacks.close = closeCallback;
window.callbacks.resize = resizeCallback;
const sw = kira.glfw.getScreenWidth();
const sh = kira.glfw.getScreenHeight();
window.position.x = @divTrunc((sw - window.size.width), 2);
window.position.y = @divTrunc((sh - window.size.height), 2);
try window.create(false);
defer window.destroy() catch unreachable;
const ortho = Mat4x4f.ortho(0, @intToFloat(f32, window.size.width), @intToFloat(f32, window.size.height), 0, -1, 1);
var cam = math.Camera2D{};
cam.ortho = ortho;
kira.glfw.makeContext(window.handle);
kira.glfw.vsync(true);
gl.init();
defer gl.deinit();
gl.setBlending(true);
c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1);
var lib = ft2.Library{};
try lib.init();
var shader = try gl.shaderProgramCreate(std.heap.page_allocator, vertexshader, fragmentshader);
defer gl.shaderProgramDelete(shader);
chars = std.ArrayList(Char).init(std.heap.page_allocator);
defer chars.deinit();
var face = try ft2.Face.new(lib, "assets/Roboto/Roboto-Regular.ttf", 0);
{
var i: u64 = 0;
while (i < 128) : (i += 1) {
face.loadChar(i, ft2.Load.render) catch |err| {
continue;
};
var glyph = face.base.*.glyph;
var char = Char{
.codepoint = i,
};
// NOTE: Do NOT forget to destroy it
gl.texturesGen(1, @ptrCast([*]u32, &char.textureid));
gl.textureBind(gl.TextureType.t2D, char.textureid);
gl.textureTexImage2D(gl.TextureType.t2D, 0, gl.TextureFormat.red, @intCast(i32, glyph.*.bitmap.width), @intCast(i32, glyph.*.bitmap.rows), 0, gl.TextureFormat.red, u8, glyph.*.bitmap.buffer);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_s, gl.TextureParamater.wrap_clamp_to_edge);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.wrap_t, gl.TextureParamater.wrap_clamp_to_edge);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.min_filter, gl.TextureParamater.filter_linear);
gl.textureTexParameteri(gl.TextureType.t2D, gl.TextureParamaterType.mag_filter, gl.TextureParamater.filter_linear);
try chars.append(char);
}
gl.textureBind(gl.TextureType.t2D, 0);
}
try face.destroy();
try lib.deinit();
var vao: u32 = 0;
var vbo: u32 = 0;
// NOTE: Do NOT forget to destroy it
gl.vertexArraysGen(1, @ptrCast([*]u32, &vao));
gl.buffersGen(1, @ptrCast([*]u32, &vbo));
defer gl.vertexArraysDelete(1, @ptrCast([*]const u32, &vao));
defer gl.buffersDelete(1, @ptrCast([*]const u32, &vbo));
{
gl.shaderProgramUse(shader);
defer gl.shaderProgramUse(0);
gl.vertexArrayBind(vao);
gl.bufferBind(gl.BufferType.array, vbo);
defer gl.bufferBind(gl.BufferType.array, 0);
defer gl.vertexArrayBind(0);
gl.bufferData(gl.BufferType.array, @sizeOf(f32) * 6 * 4, null, gl.DrawType.dynamic);
gl.shaderProgramSetVertexAttribArray(0, true);
gl.shaderProgramSetVertexAttribPointer(0, 4, f32, false, 4 * @sizeOf(f32), null);
}
window_running = true;
while (window_running) {
frametime.start();
defer {
kira.glfw.sync(window.handle);
kira.glfw.processEvents();
frametime.stop();
frametime.sleep(targetfps);
fps = fps.calculate(frametime);
std.log.notice("FPS: {}", .{fps.fps});
}
gl.clearColour(0.1, 0.1, 0.1, 1.0);
gl.clearBuffers(gl.BufferBit.colour);
cam.attach();
const mvp = @ptrCast([*]const f32, &cam.view.toArray());
{
gl.shaderProgramUse(shader);
defer gl.shaderProgramUse(0);
gl.vertexArrayBind(vao);
defer gl.vertexArrayBind(0);
gl.bufferBind(gl.BufferType.array, vbo);
defer gl.bufferBind(gl.BufferType.array, 0);
const loc = gl.shaderProgramGetUniformLocation(shader, "projection");
try check(loc == -1, "fuck", .{});
gl.shaderProgramSetMat4x4f(loc, mvp);
const loc2 = gl.shaderProgramGetUniformLocation(shader, "textColor");
try check(loc2 == -1, "fuck2", .{});
var col = engine.Colour{ .r = 1, .g = 1, .b = 1, .a = 1 };
gl.shaderProgramSetVec3f(loc2, @ptrCast([*]const f32, &col));
try renderText("Hello", 200, 200, 24, 24);
}
cam.detach();
}
}
// Does not work?
fn renderText(text: []const u8, x: f32, y: f32, sx: f32, sy: f32) !void {
var i: u32 = 0;
var cc: u64 = 0;
var ix = x;
c.glActiveTexture(c.GL_TEXTURE0);
defer gl.textureBind(gl.TextureType.t2D, 0);
while (i < text.len) : (i += 1) {
cc = text[i];
var j: u32 = 0;
const ch = chars.items;
while (j < ch.len) : (j += 1) {
if (cc == ch[j].codepoint) break;
}
//std.log.warn("codepoint: {}", .{cc});
var char = ch[j];
const xp = ix + @intToFloat(f32, char.bearingx) * sx;
const yp = y - @intToFloat(f32, (char.sizey - char.bearingy)) * sy;
const w = @intToFloat(f32, char.sizex) * sx;
const h = @intToFloat(f32, char.sizey) * sy;
var vertices = [6][4]f32{
[4]f32{ xp, yp + h, 0, 0 },
[4]f32{ xp, yp, 0, 1 },
[4]f32{ xp + w, yp, 1, 1 },
[4]f32{ xp, yp + h, 0, 0 },
[4]f32{ xp + w, yp, 1, 1 },
[4]f32{ xp + w, yp + h, 1, 0 },
};
gl.textureBind(gl.TextureType.t2D, char.textureid);
gl.bufferSubData(gl.BufferType.array, 0, @sizeOf(f32) * 6 * 4, @ptrCast(?*const c_void, &vertices));
gl.drawArrays(gl.DrawMode.triangles, 0, 6);
ix += @intToFloat(f32, (char.advance >> 6)) * sx;
}
}
fn closeCallback(handle: ?*c_void) void {
window_running = false;
}
fn resizeCallback(handle: ?*c_void, w: i32, h: i32) void {
gl.viewport(0, 0, w, h);
} | src/tests/font.zig |
const std = @import("std");
const debug = std.debug;
const io = std.io;
const mem = std.mem;
const testing = std.testing;
/// An array of string<->string that models how to encode and decode
/// from any decoding to any other encoding.
pub const Char = [2][]const u8;
pub const CharMap = []const Char;
/// Encode from one encoding to another using `CharMap` as the specification
/// of how to do transform between the encodings.
/// `curr` specifies what the encoding the `reader` is in and is an index
/// into entries in `map`. `writer` will always be the opposite encoding
/// of `reader`.
pub fn encodeEx(map: CharMap, curr: u1, reader: anytype, writer: anytype) !void {
const in: usize = @boolToInt(curr == 1);
const out: usize = @boolToInt(curr != 1);
var buf: [16]u8 = undefined;
var len: usize = 0;
while (true) {
len += try reader.readAll(buf[len..]);
const chars = buf[0..len];
if (chars.len == 0)
break;
var best_match: ?Char = null;
for (map) |char| {
debug.assert(char[in].len <= buf.len);
if (!mem.startsWith(u8, chars, char[in]))
continue;
best_match = if (best_match) |best| blk: {
break :blk if (best[in].len < char[in].len) char else best;
} else char;
}
const best = best_match orelse
return error.DecodeError;
try writer.writeAll(best[out]);
mem.copy(u8, chars, chars[best[in].len..]);
len -= best[in].len;
}
}
pub fn encode(map: CharMap, curr: u1, in: []const u8, writer: anytype) !void {
var fis = io.fixedBufferStream(in);
try encodeEx(map, curr, fis.reader(), writer);
}
fn testHelper(map: CharMap, curr: u1, in: []const u8, out: []const u8) !void {
var res: [1024]u8 = undefined;
var fos = io.fixedBufferStream(&res);
try encode(map, curr, in, fos.writer());
try testing.expectEqualSlices(u8, out, fos.getWritten());
}
pub fn testCharMap(map: CharMap, a: []const u8, b: []const u8) !void {
try testHelper(map, 0, a, b);
try testHelper(map, 1, b, a);
} | src/core/rom/encoding.zig |
const std = @import("std");
const builtin = @import("builtin");
const data = @import("../common/data.zig");
const options = @import("../common/options.zig");
const protocol = @import("../common/protocol.zig");
const rng = @import("../common/rng.zig");
const moves = @import("data/moves.zig");
const species = @import("data/species.zig");
const types = @import("data/types.zig");
const mechanics = @import("mechanics.zig");
const assert = std.debug.assert;
const expectEqual = std.testing.expectEqual;
const expect = std.testing.expect;
pub const MAX_OPTIONS = 9; // move 1..4, switch 2..6
pub const MAX_LOGS = 191;
pub const OPTIONS_SIZE = if (builtin.mode == .ReleaseSmall)
MAX_OPTIONS
else
std.math.ceilPowerOfTwo(usize, MAX_OPTIONS) catch unreachable;
pub const LOG_SIZE = if (builtin.mode == .ReleaseSmall)
MAX_LOGS
else
std.math.ceilPowerOfTwo(usize, MAX_LOGS) catch unreachable;
pub const Choice = data.Choice;
pub const ID = data.ID;
pub const Player = data.Player;
pub const Result = data.Result;
const showdown = options.showdown;
pub const PRNG = rng.PRNG(1);
pub fn Battle(comptime RNG: anytype) align(64) type {
return extern struct {
const Self = @This();
sides: [2]Side,
turn: u16 = 0,
last_damage: u16 = 0,
last_selected_indexes: MoveIndexes = .{},
rng: RNG,
pub inline fn side(self: *Self, player: Player) *Side {
return &self.sides[@enumToInt(player)];
}
pub inline fn foe(self: *Self, player: Player) *Side {
return &self.sides[@enumToInt(player.foe())];
}
pub inline fn active(self: *Self, player: Player) ID {
return player.ident(@truncate(u3, self.side(player).order[0]));
}
pub fn update(self: *Self, c1: Choice, c2: Choice, log: anytype) !Result {
return mechanics.update(self, c1, c2, switch (@typeInfo(@TypeOf(log))) {
.Null => protocol.NULL,
.Optional => log orelse protocol.NULL,
else => log,
});
}
pub fn choices(self: *Self, player: Player, request: Choice.Type, out: []Choice) u8 {
return mechanics.choices(self, player, request, out);
}
};
}
test "Battle" {
try expectEqual(384, @sizeOf(Battle(PRNG)));
}
pub const Side = extern struct {
pokemon: [6]Pokemon = [_]Pokemon{.{}} ** 6,
active: ActivePokemon = .{},
order: [6]u8 = [_]u8{0} ** 6,
last_selected_move: Move = .None,
last_used_move: Move = .None,
comptime {
assert(@sizeOf(Side) == 184);
}
pub inline fn get(self: *Side, slot: u8) *Pokemon {
assert(slot > 0 and slot <= 6);
const id = self.order[slot - 1];
assert(id > 0 and id <= 6);
return &self.pokemon[id - 1];
}
pub inline fn stored(self: *Side) *Pokemon {
return self.get(1);
}
};
pub const ActivePokemon = extern struct {
stats: Stats(u16) = .{},
species: Species = .None,
types: Types = .{},
boosts: Boosts = .{},
volatiles: Volatiles = .{},
moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4,
comptime {
assert(@sizeOf(ActivePokemon) == 32);
}
pub inline fn move(self: *ActivePokemon, mslot: u8) *MoveSlot {
assert(mslot > 0 and mslot <= 4);
assert(self.moves[mslot - 1].id != .None);
return &self.moves[mslot - 1];
}
};
pub const Pokemon = extern struct {
stats: Stats(u16) = .{},
moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4,
hp: u16 = 0,
status: u8 = 0,
species: Species = .None,
types: Types = .{},
level: u8 = 100,
comptime {
assert(@sizeOf(Pokemon) == 24);
}
pub inline fn move(self: *Pokemon, mslot: u8) *MoveSlot {
assert(mslot > 0 and mslot <= 4);
assert(self.moves[mslot - 1].id != .None);
return &self.moves[mslot - 1];
}
};
pub const MoveSlot = extern struct {
id: Move = .None,
pp: u8 = 0,
comptime {
assert(@sizeOf(MoveSlot) == @sizeOf(u16));
}
};
const uindex = if (showdown) u16 else u4;
pub const MoveIndexes = packed struct {
p1: uindex = 0,
p2: uindex = 0,
comptime {
assert(@sizeOf(MoveIndexes) == if (showdown) 4 else 1);
}
};
pub const Status = enum(u8) {
// 0 and 1 bits are also used for SLP
SLP = 2,
PSN = 3,
BRN = 4,
FRZ = 5,
PAR = 6,
// Gen 1/2 uses Volatiles.Toxic instead of TOX, so the top Status bit is
// repurposed to track whether the SLP status was self-inflicted or not
// in order to implement Pokémon Showdown's "Sleep Clause Mod"
SLF = 7,
const SLP = 0b111;
pub inline fn is(num: u8, status: Status) bool {
if (status == .SLP) return Status.duration(num) > 0;
return ((num >> @intCast(u3, @enumToInt(status))) & 1) != 0;
}
pub inline fn init(status: Status) u8 {
assert(status != .SLP and status != .SLF);
return @as(u8, 1) << @intCast(u3, @enumToInt(status));
}
pub inline fn slp(dur: u3) u8 {
assert(dur > 0);
return @as(u8, dur);
}
pub inline fn slf(dur: u3) u8 {
assert(dur > 0);
return 0x80 | slp(dur);
}
pub inline fn duration(num: u8) u3 {
return @intCast(u3, num & SLP);
}
pub inline fn any(num: u8) bool {
return num > 0;
}
// @test-only
pub fn name(num: u8) []const u8 {
if (Status.is(num, .SLF)) return "SLF";
if (Status.is(num, .SLP)) return "SLP";
if (Status.is(num, .PSN)) return "PSN";
if (Status.is(num, .BRN)) return "BRN";
if (Status.is(num, .FRZ)) return "FRZ";
if (Status.is(num, .PAR)) return "PAR";
return "OK";
}
};
test "Status" {
try expect(!Status.any(0));
try expect(Status.is(Status.init(.PSN), .PSN));
try expect(!Status.is(Status.init(.PSN), .PAR));
try expect(Status.is(Status.init(.BRN), .BRN));
try expect(!Status.is(Status.init(.FRZ), .SLP));
try expect(Status.is(Status.init(.FRZ), .FRZ));
try expect(!Status.is(0, .SLP));
try expect(Status.is(Status.slp(5), .SLP));
try expect(!Status.is(Status.slp(5), .SLF));
try expect(!Status.is(Status.slp(7), .PSN));
try expectEqual(@as(u3, 5), Status.duration(Status.slp(5)));
try expect(Status.is(Status.slf(2), .SLP));
try expect(Status.is(Status.slf(2), .SLF));
try expectEqual(@as(u3, 1), Status.duration(Status.slp(1)));
}
pub const Volatiles = packed struct {
Bide: bool = false,
Thrashing: bool = false,
MultiHit: bool = false,
Flinch: bool = false,
Charging: bool = false,
Trapping: bool = false,
Invulnerable: bool = false,
Confusion: bool = false,
Mist: bool = false,
FocusEnergy: bool = false,
Substitute: bool = false,
Recharging: bool = false,
Rage: bool = false,
LeechSeed: bool = false,
Toxic: bool = false,
LightScreen: bool = false,
Reflect: bool = false,
Transform: bool = false,
confusion: u3 = 0,
attacks: u3 = 0,
// NB: used for both bide and accuracy overwriting!
state: u16 = 0,
substitute: u8 = 0,
disabled: Disabled = .{},
toxic: u4 = 0,
transform: u4 = 0,
const Disabled = packed struct {
move: u4 = 0,
duration: u4 = 0,
};
comptime {
assert(@sizeOf(Volatiles) == 8);
}
};
test "Volatiles" {
var volatiles = Volatiles{};
volatiles.Confusion = true;
volatiles.confusion = 2;
volatiles.Thrashing = true;
volatiles.state = 235;
volatiles.attacks = 3;
volatiles.Substitute = true;
volatiles.substitute = 42;
volatiles.toxic = 4;
volatiles.disabled = .{ .move = 2, .duration = 4 };
try expect(volatiles.Confusion);
try expect(volatiles.Thrashing);
try expect(volatiles.Substitute);
try expect(!volatiles.Recharging);
try expect(!volatiles.Transform);
try expect(!volatiles.MultiHit);
try expectEqual(@as(u16, 235), volatiles.state);
try expectEqual(@as(u8, 42), volatiles.substitute);
try expectEqual(@as(u4, 2), volatiles.disabled.move);
try expectEqual(@as(u4, 4), volatiles.disabled.duration);
try expectEqual(@as(u4, 2), volatiles.confusion);
try expectEqual(@as(u4, 4), volatiles.toxic);
try expectEqual(@as(u4, 3), volatiles.attacks);
}
// @test-only
pub const Stat = enum { hp, atk, def, spe, spc };
pub fn Stats(comptime T: type) type {
return extern struct {
hp: T = 0,
atk: T = 0,
def: T = 0,
spe: T = 0,
spc: T = 0,
// @test-only
pub fn calc(comptime stat: []const u8, base: T, dv: u4, exp: u16, level: u8) T {
assert(level > 0 and level <= 100);
const core: u32 = (2 *% (@as(u32, base) +% dv)) +% @as(u32, (std.math.sqrt(exp) / 4));
const factor: u32 = if (std.mem.eql(u8, stat, "hp")) level + 10 else 5;
return @truncate(T, core *% @as(u32, level) / 100 +% factor);
}
};
}
test "Stats" {
try expectEqual(5, @sizeOf(Stats(u8)));
const stats = Stats(u16){ .atk = 2, .spe = 3 };
try expectEqual(2, stats.atk);
try expectEqual(0, stats.def);
}
pub const Boosts = packed struct {
atk: i4 = 0,
def: i4 = 0,
spe: i4 = 0,
spc: i4 = 0,
accuracy: i4 = 0,
evasion: i4 = 0,
_: u8 = 0,
comptime {
assert(@sizeOf(Boosts) == 4);
}
};
test "Boosts" {
const boosts = Boosts{ .spc = -6 };
try expectEqual(0, boosts.atk);
try expectEqual(-6, boosts.spc);
}
pub const Move = moves.Move;
test "Move" {
try expectEqual(2, @enumToInt(Move.KarateChop));
const move = Move.get(.Fissure);
try expectEqual(Move.Effect.OHKO, move.effect);
try expectEqual(@as(u8, 30), move.accuracy);
try expectEqual(Type.Ground, move.type);
try expect(!Move.Effect.onBegin(.None));
try expect(Move.Effect.onBegin(.Confusion));
try expect(Move.Effect.onBegin(.Transform));
try expect(!Move.Effect.onBegin(.AccuracyDown1));
try expect(!Move.Effect.isStatDown(.Transform));
try expect(Move.Effect.isStatDown(.AccuracyDown1));
try expect(Move.Effect.isStatDown(.SpeedDown1));
try expect(!Move.Effect.isStatDown(.AttackUp1));
try expect(!Move.Effect.onEnd(.Transform));
try expect(Move.Effect.onEnd(.AccuracyDown1));
try expect(Move.Effect.onEnd(.SpeedUp2));
try expect(!Move.Effect.onEnd(.Charge));
try expect(!Move.Effect.alwaysHappens(.SpeedUp2));
try expect(Move.Effect.alwaysHappens(.DrainHP));
try expect(Move.Effect.alwaysHappens(.Recoil));
try expect(!Move.Effect.alwaysHappens(.Charge));
try expect(!Move.Effect.alwaysHappens(.SpeedDownChance));
try expect(Move.Effect.alwaysHappens(.Rage));
// all considered "always happens" on cartridge
try expect(!Move.Effect.alwaysHappens(.DoubleHit));
try expect(!Move.Effect.alwaysHappens(.MultiHit));
try expect(!Move.Effect.alwaysHappens(.Twineedle));
try expect(!Move.Effect.isSpecial(.SpeedUp2));
try expect(Move.Effect.isSpecial(.DrainHP));
try expect(Move.Effect.isSpecial(.Rage)); // other on cartridge
try expect(Move.Effect.isSpecial(.DoubleHit));
try expect(Move.Effect.isSpecial(.MultiHit));
try expect(!Move.Effect.isSpecial(.Twineedle));
try expect(!Move.Effect.isMulti(.Trapping));
try expect(Move.Effect.isMulti(.DoubleHit));
try expect(Move.Effect.isMulti(.MultiHit));
try expect(Move.Effect.isMulti(.Twineedle));
try expect(!Move.Effect.isMulti(.AttackDownChance));
try expect(!Move.Effect.isStatDownChance(.Trapping));
try expect(Move.Effect.isStatDownChance(.AttackDownChance));
try expect(Move.Effect.isStatDownChance(.SpecialDownChance));
try expect(!Move.Effect.isStatDownChance(.BurnChance1));
try expectEqual(@as(u8, 0), Move.frames(.Bide, .resolve));
try expectEqual(@as(u8, 1), Move.frames(.Tackle, .resolve));
try expectEqual(@as(u8, 2), Move.frames(.Counter, .resolve));
try expectEqual(@as(u8, 0), Move.frames(.Counter, .run));
try expectEqual(@as(u8, 1), Move.frames(.Swift, .run));
try expect(!Move.get(.Bide).target.resolves());
try expect(Move.get(.Tackle).target.resolves());
try expect(!Move.get(.Counter).target.runs());
try expect(Move.get(.Swift).target.runs());
}
pub const Species = species.Species;
test "Species" {
try expectEqual(2, @enumToInt(Species.Ivysaur));
try expectEqual(@as(u8, 100), Species.get(.Mew).stats.def);
}
pub const Type = types.Type;
pub const Types = types.Types;
pub const Effectiveness = enum(u8) {
Immune = 0,
Resisted = 5,
Neutral = 10,
Super = 20,
pub const neutral: u16 = @enumToInt(Effectiveness.Neutral) * @enumToInt(Effectiveness.Neutral);
comptime {
assert(@bitSizeOf(Effectiveness) == 8);
}
};
test "Types" {
try expectEqual(14, @enumToInt(Type.Dragon));
try expectEqual(20, @enumToInt(Effectiveness.Super));
try expect(!Type.Ghost.special());
try expect(Type.Dragon.special());
try expectEqual(Effectiveness.Immune, Type.effectiveness(.Ghost, .Psychic));
try expectEqual(Effectiveness.Super, Type.Water.effectiveness(.Fire));
try expectEqual(Effectiveness.Resisted, Type.effectiveness(.Fire, .Water));
try expectEqual(Effectiveness.Neutral, Type.effectiveness(.Normal, .Grass));
const t: Types = .{ .type1 = .Rock, .type2 = .Ground };
try expect(!t.immune(.Grass));
try expect(t.immune(.Electric));
try expect(!t.includes(.Fire));
try expect(t.includes(.Rock));
}
// @test-only
pub const DVs = struct {
atk: u4 = 15,
def: u4 = 15,
spe: u4 = 15,
spc: u4 = 15,
pub fn hp(self: DVs) u4 {
return (self.atk & 1) << 3 | (self.def & 1) << 2 | (self.spe & 1) << 1 | (self.spc & 1);
}
pub fn random(rand: *rng.PSRNG) DVs {
return .{
.atk = if (rand.chance(u8, 1, 5)) rand.range(u4, 1, 15 + 1) else 15,
.def = if (rand.chance(u8, 1, 5)) rand.range(u4, 1, 15 + 1) else 15,
.spe = if (rand.chance(u8, 1, 5)) rand.range(u4, 1, 15 + 1) else 15,
.spc = if (rand.chance(u8, 1, 5)) rand.range(u4, 1, 15 + 1) else 15,
};
}
};
test "DVs" {
var dvs = DVs{ .spc = 15, .spe = 15 };
try expectEqual(@as(u4, 15), dvs.hp());
dvs = DVs{
.atk = 5,
.def = 15,
.spe = 13,
.spc = 13,
};
try expectEqual(@as(u4, 15), dvs.hp());
dvs = DVs{
.def = 3,
.spe = 10,
.spc = 11,
};
try expectEqual(@as(u4, 13), dvs.hp());
} | src/lib/gen1/data.zig |
const std = @import("std");
const StructField = std.builtin.TypeInfo.StructField;
const isSignedInt = std.meta.trait.isSignedInt;
const isIntegral = std.meta.trait.isIntegral;
// common definitions
const ArrayList = std.ArrayList;
/// Type of encoding for a Varint value.
const VarintType = enum { Simple, ZigZagOptimized };
/// Enum describing the different field types available.
pub const FieldTypeTag = enum { Varint, FixedInt, SubMessage, List, OneOf, Map };
/// Enum describing the content type of a repeated field.
pub const ListTypeTag = enum {
Varint,
FixedInt,
SubMessage,
};
/// Tagged union for repeated fields, giving the details of the underlying type.
pub const ListType = union(ListTypeTag) {
Varint: VarintType,
FixedInt,
SubMessage,
};
/// Enum describing the details of keys or values for a map type.
pub const KeyValueTypeTag = enum {
Varint,
FixedInt,
SubMessage,
List,
};
/// Tagged union giving the details of underlying types in a map field
pub const KeyValueType = union(KeyValueTypeTag) {
Varint: VarintType,
FixedInt,
SubMessage,
List: ListType,
pub fn toFieldType(self: KeyValueType) FieldType {
return switch (self) {
.Varint => |varint_type| .{ .Varint = varint_type },
.FixedInt => .{.FixedInt},
.SubMessage => .{.SubMessage},
.List => |list_type| .{ .List = list_type },
};
}
};
/// Struct for key and values of a map type
pub const KeyValueTypeData = struct {
t: type,
pb_data: KeyValueType,
};
/// Struct describing keys and values of a map
pub const MapData = struct { key: KeyValueTypeData, value: KeyValueTypeData };
/// Main tagged union holding the details of any field type.
pub const FieldType = union(FieldTypeTag) {
Varint: VarintType,
FixedInt,
SubMessage,
List: ListType,
OneOf: type,
Map: MapData,
/// returns the wire type of a field. see https://developers.google.com/protocol-buffers/docs/encoding#structure
pub fn get_wirevalue(comptime ftype: FieldType, comptime value_type: type) u3 {
comptime {
switch (ftype) {
.OneOf => @compileError("Shouldn't pass a .OneOf field to this function here."),
else => {},
}
}
const real_type: type = switch (@typeInfo(value_type)) {
.Optional => |opt| opt.child,
else => value_type,
};
return switch (ftype) {
.Varint => 0,
.FixedInt => return switch (@bitSizeOf(real_type)) {
64 => 1,
32 => 5,
else => @compileLog("Invalid size for fixed int :", @bitSizeOf(real_type), "type is ", real_type),
},
.SubMessage, .List, .Map => 2,
.OneOf => unreachable,
};
}
};
/// Structure describing a field. Most of the relevant informations are
/// In the FieldType data. Tag is optional as OneOf fields are "virtual" fields.
pub const FieldDescriptor = struct {
tag: ?u32,
ftype: FieldType,
};
/// Helper function to build a FieldDescriptor. Makes code clearer, mostly.
pub fn fd(tag: ?u32, comptime ftype: FieldType) FieldDescriptor {
return FieldDescriptor{ .tag = tag, .ftype = ftype };
}
// encoding
/// Appends an unsigned varint value.
/// Awaits a u64 value as it's the biggest unsigned varint possible,
// so anything can be cast to it by definition
fn append_raw_varint(pb: *ArrayList(u8), value: u64) !void {
var copy = value;
while (copy > 0x7F) {
try pb.append(0x80 + @intCast(u8, copy & 0x7F));
copy = copy >> 7;
}
try pb.append(@intCast(u8, copy & 0x7F));
}
/// Inserts a varint into the pb at start_index
/// Mostly useful when inserting the size of a field after it has been
/// Appended to the pb buffer.
fn insert_raw_varint(pb: *ArrayList(u8), size: u64, start_index: usize) !void {
if (size < 0x7F) {
try pb.insert(start_index, @truncate(u8, size));
} else {
var copy = size;
var index = start_index;
while (copy > 0x7F) : (index += 1) {
try pb.insert(index, 0x80 + @intCast(u8, copy & 0x7F));
copy = copy >> 7;
}
try pb.insert(index, @intCast(u8, copy & 0x7F));
}
}
/// Appends a varint to the pb array.
/// Mostly does the required transformations to use append_raw_varint
/// after making the value some kind of unsigned value.
fn append_as_varint(pb: *ArrayList(u8), value: anytype, comptime varint_type: VarintType) !void {
if (value < 0x7F and value >= 0) {
try pb.append(@intCast(u8, value));
} else {
const type_of_val = @TypeOf(value);
const bitsize = @bitSizeOf(type_of_val);
const val: u64 = comptime blk: {
if (isSignedInt(type_of_val)) {
switch (varint_type) {
.ZigZagOptimized => {
break :blk @intCast(u64, (value >> (bitsize - 1)) ^ (value << 1));
},
.Simple => {
break :blk @bitCast(std.meta.Int(.unsigned, bitsize), value);
},
}
} else {
break :blk @intCast(u64, value);
}
};
try append_raw_varint(pb, val);
}
}
/// Append a value of any complex type that can be transfered as a varint
/// Only serves as an indirection to manage Enum and Booleans properly.
fn append_varint(pb: *ArrayList(u8), value: anytype, comptime varint_type: VarintType) !void {
switch (@typeInfo(@TypeOf(value))) {
.Enum => try append_as_varint(pb, @as(i32, @enumToInt(value)), varint_type),
.Bool => try append_as_varint(pb, @as(u8, @boolToInt(value)), varint_type),
else => try append_as_varint(pb, value, varint_type),
}
}
/// Appends a fixed size int to the pb buffer.
/// Takes care of casting any signed/float value to an appropriate unsigned type
fn append_fixed(pb: *ArrayList(u8), value: anytype) !void {
comptime {
switch (@TypeOf(value)) {
f32, f64, i32, i64, u32, u64, u8 => {},
else => @compileError("Invalid type for append_fixed"),
}
}
const bitsize = @bitSizeOf(@TypeOf(value));
var as_unsigned_int = switch (@TypeOf(value)) {
f32, f64, i32, i64 => @bitCast(std.meta.Int(.unsigned, bitsize), value),
u32, u64, u8 => value,
else => unreachable,
};
var index: usize = 0;
while (index < (bitsize / 8)) : (index += 1) {
try pb.append(@truncate(u8, as_unsigned_int));
as_unsigned_int = as_unsigned_int >> 8;
}
}
/// Appends a submessage to the array.
/// Recursively calls internal_pb_encode.
fn append_submessage(pb: *ArrayList(u8), value: anytype) !void {
const len_index = pb.items.len;
try internal_pb_encode(pb, value);
const size_encoded = pb.items.len - len_index;
try insert_raw_varint(pb, size_encoded, len_index);
}
/// Simple appending of a list of bytes.
fn append_bytes(pb: *ArrayList(u8), value: *const ArrayList(u8)) !void {
try append_as_varint(pb, value.len, .Simple);
try pb.appendSlice(value.items);
}
/// simple appending of a list of fixed-size data.
fn append_list_of_fixed(pb: *ArrayList(u8), value: anytype) !void {
const total_len = @divFloor(value.items.len * @bitSizeOf(@typeInfo(@TypeOf(value.items)).Pointer.child), 8);
try append_as_varint(pb, total_len, .Simple);
if (@TypeOf(value) == ArrayList(u8)) {
try pb.appendSlice(value.items);
} else {
for (value.items) |item| {
try append_fixed(pb, item);
}
}
}
/// Appends a list of varint to the pb buffer.
fn append_list_of_varint(pb: *ArrayList(u8), value_list: anytype, comptime varint_type: VarintType) !void {
const len_index = pb.items.len;
for (value_list.items) |item| {
try append_varint(pb, item, varint_type);
}
const size_encoded = pb.items.len - len_index;
try insert_raw_varint(pb, size_encoded, len_index);
}
/// Appends a list of submessages to the pb_buffer.
fn append_list_of_submessages(pb: *ArrayList(u8), value_list: anytype) !void {
const len_index = pb.items.len;
for (value_list.items) |item| {
try append_submessage(pb, item);
}
const size_encoded = pb.items.len - len_index;
try insert_raw_varint(pb, size_encoded, len_index);
}
/// calculates the comptime value of (tag_index << 3) + wire type.
/// This is fully calculated at comptime which is great.
fn get_full_tag_value(comptime field: FieldDescriptor, comptime value_type: type) ?u32 {
return if (field.tag) |tag| ((tag << 3) | field.ftype.get_wirevalue(value_type)) else null;
}
/// Appends the full tag of the field in the pb buffer, if there is any.
fn append_tag(pb: *ArrayList(u8), comptime field: FieldDescriptor, value_type: type) !void {
if (get_full_tag_value(field, value_type)) |tag_value| {
try append_varint(pb, tag_value, .Simple);
}
}
fn MapSubmessage(comptime key_data: KeyValueTypeData, comptime value_data: KeyValueTypeData) type {
return struct {
const Self = @This();
key: ?key_data.t,
value: ?value_data.t,
pub const _desc_table = .{ .key = fd(1, key_data.pb_data.toFieldType()), .value = fd(2, value_data.pb_data.toFieldType()) };
pub fn encode(self: Self, allocator: *mem.Allocator) ![]u8 {
return pb_encode(self, allocator);
}
pub fn decode(input: []const u8, allocator: *mem.Allocator) !Self {
return pb_decode(Self, input, allocator);
}
pub fn init(allocator: *mem.Allocator) Self {
return pb_init(Self, allocator);
}
pub fn deinit(self: Self) void {
pb_deinit(self);
}
};
}
/// Appends the content of a Map field to the pb buffer.
/// Relies on a property of maps being basically a list of submessage with key index = 1 and value index = 2
/// By relying on this property, encoding maps is as easy as building an internal
/// Struct type with this data, and encoding using all the rest of the tool already
/// at hand.
/// See this note for details https://developers.google.com/protocol-buffers/docs/proto3#backwards_compatibility
fn append_map(pb: *ArrayList(u8), comptime field: FieldDescriptor, map: anytype) !void {
const len_index = pb.items.len;
var iterator: @TypeOf(map).Iterator = map.iterator();
const key_type_data = field.ftype.Map.key;
const value_type_data = field.ftype.Map.value;
const Submessage = MapSubmessage(key_type_data, value_type_data);
while (iterator.next()) |data| {
try append_submessage(pb, Submessage{ .key = data.key_ptr.*, .value = data.value_ptr.* });
}
const size_encoded = pb.items.len - len_index;
try insert_raw_varint(pb, size_encoded, len_index);
}
/// Appends a value to the pb buffer. Starts by appending the tag, then a comptime switch
/// routes the code to the correct type of data to append.
fn append(pb: *ArrayList(u8), comptime field: FieldDescriptor, value_type: type, value: anytype) !void {
try append_tag(pb, field, value_type);
switch (field.ftype) {
.Varint => |varint_type| {
try append_varint(pb, value, varint_type);
},
.FixedInt => {
try append_fixed(pb, value);
},
.SubMessage => {
try append_submessage(pb, value);
},
.List => |list_type| {
switch (list_type) {
.FixedInt => {
try append_list_of_fixed(pb, value);
},
.SubMessage => {
try append_list_of_submessages(pb, value);
},
.Varint => |varint_type| {
try append_list_of_varint(pb, value, varint_type);
},
}
},
.OneOf => |union_type| {
const active = @tagName(value);
inline for (@typeInfo(@TypeOf(union_type._union_desc)).Struct.fields) |union_field| {
if (std.mem.eql(u8, union_field.name, active)) {
try append(pb, @field(union_type._union_desc, union_field.name), @TypeOf(@field(value, union_field.name)), @field(value, union_field.name));
}
}
},
.Map => {
try append_map(pb, field, value);
},
}
}
/// Internal function that decodes the descriptor information and struct fields
/// before passing them to the append function
fn internal_pb_encode(pb: *ArrayList(u8), data: anytype) !void {
const field_list = @typeInfo(@TypeOf(data)).Struct.fields;
const data_type = @TypeOf(data);
inline for (field_list) |field| {
if (@typeInfo(field.field_type) == .Optional) {
if (@field(data, field.name)) |value| {
try append(pb, @field(data_type._desc_table, field.name), @TypeOf(value), value);
}
} else {
switch (@field(data_type._desc_table, field.name).ftype) {
.List => if (@field(data, field.name).items.len != 0) {
try append(pb, @field(data_type._desc_table, field.name), @TypeOf(@field(data, field.name)), @field(data, field.name));
},
.Map => if (@field(data, field.name).count() != 0) {
try append(pb, @field(data_type._desc_table, field.name), @TypeOf(@field(data, field.name)), @field(data, field.name));
},
else => @compileLog("You shouldn't be here"),
}
}
}
}
/// Public encoding function, meant to be embdedded in generated structs
pub fn pb_encode(data: anytype, allocator: *std.mem.Allocator) ![]u8 {
var pb = ArrayList(u8).init(allocator);
errdefer pb.deinit();
try internal_pb_encode(&pb, data);
return pb.toOwnedSlice();
}
/// Generic init function. Properly initialise any field required. Meant to be embedded in generated structs.
pub fn pb_init(comptime T: type, allocator: *std.mem.Allocator) T {
var value: T = undefined;
inline for (@typeInfo(T).Struct.fields) |field| {
switch (@field(T._desc_table, field.name).ftype) {
.Varint, .FixedInt, .SubMessage => {
@field(value, field.name) = if (field.default_value) |val| val else null;
},
.List, .Map => {
@field(value, field.name) = @TypeOf(@field(value, field.name)).init(allocator);
},
.OneOf => {
@field(value, field.name) = null;
},
}
}
return value;
}
/// Generic deinit function. Properly initialise any field required. Meant to be embedded in generated structs.
pub fn pb_deinit(data: anytype) void {
const T = @TypeOf(data);
inline for (@typeInfo(T).Struct.fields) |field| {
deinit_field(data, field.name, @field(T._desc_table, field.name).ftype);
}
}
/// Internal deinit function for a specific field
fn deinit_field(field: anytype, comptime field_name: []const u8, comptime ftype: FieldType) void {
switch (ftype) {
.Varint, .FixedInt => {},
.SubMessage => {
@field(field, field_name).deinit();
},
.List => |list_type| {
if (list_type == .SubMessage) {
for (@field(field, field_name).items) |item| {
item.deinit();
}
}
@field(field, field_name).deinit();
},
.OneOf => |union_type| {
if (@field(field, field_name)) |union_value| {
const active = @tagName(union_value);
inline for (@typeInfo(@TypeOf(union_type._union_desc)).Struct.fields) |union_field| {
if (std.mem.eql(u8, union_field.name, active)) {
deinit_field(union_value, union_field.name, @field(union_type._union_desc, union_field.name).ftype);
}
}
}
},
.Map => |_| {
// for unknown reason i have to specifically made it var here. Otherwise it's a const field.
var temp = @field(field, field_name); // key/values requiring dealloc aren't managed yet!
temp.deinit();
},
}
}
// decoding
/// Enum describing if described data is raw (<u64) data or a byte slice.
const ExtractedDataTag = enum {
RawValue,
Slice,
};
/// Union enclosing either a u64 raw value, or a byte slice.
const ExtractedData = union(ExtractedDataTag) { RawValue: u64, Slice: []const u8 };
/// Unit of extracted data from a stream
/// Please not that "tag" is supposed to be the full tag. See get_full_tag_value.
const Extracted = struct { tag: u32, data: ExtractedData };
/// Decoded varint value generic type
fn DecodedVarint(comptime T: type) type {
return struct {
value: T,
size: usize,
};
}
/// Decodes a varint from a slice, to type T.
fn decode_varint(comptime T: type, input: []const u8) DecodedVarint(T) {
var value: T = 0;
var index: usize = 0;
while ((input[index] & 0b10000000) != 0) : (index += 1) {
value += (@as(T, input[index] & 0x7F)) << (@intCast(std.math.Log2Int(T), index * 7));
}
value += (@as(T, input[index] & 0x7F)) << (@intCast(std.math.Log2Int(T), index * 7));
return DecodedVarint(T){
.value = value,
.size = index + 1,
};
}
/// Decodes a fixed value to type T
fn decode_fixed(comptime T: type, slice: []const u8) T {
const result_base: type = switch (@bitSizeOf(T)) {
32 => u32,
64 => u64,
else => @compileError("can only manage 32 or 64 bit sizes"),
};
var result: result_base = 0;
for (slice) |byte, index| {
result += @intCast(result_base, byte) << (@intCast(std.math.Log2Int(result_base), index * 8));
}
return switch (T) {
u32, u64 => result,
else => @bitCast(T, result),
};
}
test "decode fixed" {
const u_32 = [_]u8{ 2, 0, 0, 0 };
const u_32_result: u32 = 2;
try testing.expectEqual(u_32_result, decode_fixed(u32, &u_32));
const u_64 = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 };
const u_64_result: u64 = 1;
try testing.expectEqual(u_64_result, decode_fixed(u64, &u_64));
const i_32 = [_]u8{ 0xFF, 0xFF, 0xFF, 0xFF };
const i_32_result: i32 = -1;
try testing.expectEqual(i_32_result, decode_fixed(i32, &i_32));
const i_64 = [_]u8{ 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
const i_64_result: i64 = -2;
try testing.expectEqual(i_64_result, decode_fixed(i64, &i_64));
const f_32 = [_]u8{ 0x00, 0x00, 0xa0, 0x40 };
const f_32_result: f32 = 5.0;
try testing.expectEqual(f_32_result, decode_fixed(f32, &f_32));
const f_64 = [_]u8{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x40 };
const f_64_result: f64 = 5.0;
try testing.expectEqual(f_64_result, decode_fixed(f64, &f_64));
}
fn FixedDecoderIterator(comptime T: type) type {
return struct {
const Self = @This();
const num_bytes = @divFloor(@bitSizeOf(T), 8);
input: []const u8,
current_index: usize = 0,
fn next(self: *Self) ?T {
if (self.current_index < self.input.len) {
defer self.current_index += Self.num_bytes;
return decode_fixed(T, self.input[self.current_index .. self.current_index + Self.num_bytes]);
}
return null;
}
};
}
fn VarintDecoderIterator(comptime T: type, comptime varint_type: VarintType) type {
return struct {
const Self = @This();
input: []const u8,
current_index: usize = 0,
fn next(self: *Self) ?T {
if (self.current_index < self.input.len) {
const raw_value = decode_varint(u64, self.input[self.current_index..]);
defer self.current_index += raw_value.size;
return get_varint_value(T, varint_type, raw_value.value);
}
return null;
}
};
}
fn SubmessageDecoderIterator(comptime T: type) type {
return struct {
const Self = @This();
input: []const u8,
current_index: usize = 0,
allocator: *std.mem.Allocator,
fn next(self: *Self) !?T {
if (self.current_index < self.input.len) {
const size = decode_varint(u64, self.input[self.current_index..]);
self.current_index += size.size;
defer self.current_index += size.value;
return try T.decode(self.input[self.current_index .. self.current_index + size.value], self.allocator);
}
return null;
}
};
}
/// "Tokenizer" of a byte slice to raw pb data.
const WireDecoderIterator = struct {
input: []const u8,
current_index: usize = 0,
/// Attempts at decoding the next pb_buffer data.
fn next(state: *WireDecoderIterator) !?Extracted {
if (state.current_index < state.input.len) {
const tag_and_wire = decode_varint(u32, state.input[state.current_index..]);
state.current_index += tag_and_wire.size;
const tag: u32 = tag_and_wire.value;
const wire_value = tag_and_wire.value & 0b00000111;
const data: ExtractedData = switch (wire_value) {
0 => blk: {
const varint = decode_varint(u64, state.input[state.current_index..]);
state.current_index += varint.size;
break :blk ExtractedData{
.RawValue = varint.value,
};
},
1 => blk: {
const value = ExtractedData{ .RawValue = decode_fixed(u64, state.input[state.current_index .. state.current_index + 8]) };
state.current_index += 8;
break :blk value;
},
5 => blk: {
const value = ExtractedData{ .RawValue = decode_fixed(u32, state.input[state.current_index .. state.current_index + 4]) };
state.current_index += 4;
break :blk value;
},
2 => blk: {
const size = decode_varint(u32, state.input[state.current_index..]);
const value = ExtractedData{ .Slice = state.input[(state.current_index + size.size)..(state.current_index + size.size + size.value)] };
state.current_index += size.value + size.size;
break :blk value;
},
else => @panic("Not implemented yet"),
};
return Extracted{ .tag = tag, .data = data };
} else {
return null;
}
}
};
/// Get a real varint of type T from a raw u64 data.
fn get_varint_value(comptime T: type, comptime varint_type: VarintType, raw: u64) T {
return comptime switch (varint_type) {
.ZigZagOptimized => switch (@typeInfo(T)) {
.Int => @intCast(T, (@intCast(i64, raw) >> 1) ^ (-(@intCast(i64, raw) & 1))),
.Enum => @intToEnum(T, @intCast(i32, (@intCast(i64, raw) >> 1) ^ (-(@intCast(i64, raw) & 1)))),
else => @compileError("Invalid type passed"),
},
.Simple => switch (@typeInfo(T)) {
.Int => switch (T) {
u32, u64 => @intCast(T, raw),
i32, i64 => @bitCast(T, @truncate(std.meta.Int(.unsigned, @bitSizeOf(T)), raw)),
else => @compileError("Invalid type passed"),
},
.Bool => raw == 1,
.Enum => @intToEnum(T, @intCast(i32, raw)),
else => @compileError("Invalid type passed"),
},
};
}
/// Get a real fixed value of type T from a raw u64 value.
fn get_fixed_value(comptime T: type, raw: u64) T {
return switch (T) {
i32, u32, f32 => @bitCast(T, @truncate(std.meta.Int(.unsigned, @bitSizeOf(T)), raw)),
i64, f64, u64 => @bitCast(T, raw),
else => @compileError("Invalid type for get_fixed_value"),
};
}
/// public decoding function meant to be embedded in message structures
/// Iterates over the input and try to fill the resulting structure accordingly.
pub fn pb_decode(comptime T: type, input: []const u8, allocator: *std.mem.Allocator) !T {
var result = pb_init(T, allocator);
var iterator = WireDecoderIterator{ .input = input };
while (try iterator.next()) |extracted_data| {
const field_found: ?StructField = inline for (@typeInfo(T).Struct.fields) |field| {
if (get_full_tag_value(@field(T._desc_table, field.name), field.field_type)) |tag_value| {
if (tag_value == extracted_data.tag) break field;
}
} else null;
if (field_found) |field| {
switch (@field(T._desc_table, field.name).ftype) {
.Varint, .FixedInt, .SubMessage => {
const child_type = @typeInfo(field.field_type).Optional.child;
@field(result, field.name) = switch (@field(T._desc_table, field.name).ftype) {
.Varint => |varint_type| get_varint_value(child_type, varint_type, extracted_data.data.RawValue),
.FixedInt => get_fixed_value(child_type, extracted_data.data.RawValue),
.SubMessage => try pb_decode(child_type, extracted_data.data.Slice, allocator),
else => @panic("Not implemented"),
};
},
.List => |list_type| {
const child_type = @typeInfo(@TypeOf(@field(result, field.name).items)).Pointer.child;
switch (list_type) {
.FixedInt => {
switch (child_type) {
u8 => try @field(result, field.name).appendSlice(extracted_data.data.Slice),
u32, i32, u64, i64, f32, f64 => {
var fixed_iterator = FixedDecoderIterator(child_type){ .input = extracted_data.data.Slice };
while (fixed_iterator.next()) |value| {
try @field(result, field.name).append(value);
}
},
else => @compileError("can't encode this bruh"),
}
},
.Varint => |varint_type| {
var varint_iterator = VarintDecoderIterator(child_type, varint_type){ .input = extracted_data.data.Slice };
while (varint_iterator.next()) |value| {
try @field(result, field.name).append(value);
}
},
.SubMessage => {
var submessage_iterator = SubmessageDecoderIterator(child_type){ .input = extracted_data.data.Slice, .allocator = allocator };
while (try submessage_iterator.next()) |value| {
try @field(result, field.name).append(value);
}
},
}
},
else => @panic("Not implemented"),
}
}
}
return result;
}
// TBD
// tests
const testing = std.testing;
test "get varint" {
var pb = ArrayList(u8).init(testing.allocator);
const value: u32 = 300;
defer pb.deinit();
try append_varint(&pb, value, .Simple);
try testing.expectEqualSlices(u8, &[_]u8{ 0b10101100, 0b00000010 }, pb.items);
} | src/protobuf.zig |
const nk = @import("nuklear");
const std = @import("std");
const math = std.math;
pub fn showcase(ctx: *nk.Context) void {
const Static = struct {
var progress: u8 = 0;
var checkbox_label: bool = false;
var checkbox_flags_label: usize = 0;
var check_label: bool = false;
var check_flags_label: usize = 0;
var color_picker_picked: nk.Colorf = .{ .r = 0, .g = 0, .b = 0, .a = 0, ._pad = 0 };
var color_pick_picked: nk.Colorf = .{ .r = 0, .g = 0, .b = 0, .a = 0, ._pad = 0 };
var combo_items_selected: usize = 0;
var combo_sep_selected: usize = 0;
var combo_string_selected: usize = 0;
var combo_callback_selected: usize = 0;
var combo_begin_label_selected: []const u8 = "BUTTONS!";
var edit_string_buf: [100]u8 = undefined;
var edit_string: []u8 = edit_string_buf[0..0];
var edit_stringz: [100:0]u8 = [_]u8{0} ** 100;
};
if (nk.window.begin(ctx, &nk.id(opaque {}), nk.rect(100, 100, 500, 500), .{
.title = "showcase",
.border = true,
.moveable = true,
.closable = true,
.minimizable = true,
.background = false,
.scalable = true,
})) |_| {
nk.layout.rowDynamic(ctx, 70, 1);
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.bar",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 0, 1);
Static.progress = @intCast(u8, nk.bar.prog(
ctx,
Static.progress,
math.maxInt(u8),
true,
));
Static.progress +%= 1;
}
nk.layout.rowDynamic(ctx, 360, 2);
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.button",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 0, 1);
if (nk.button.label(ctx, "label"))
std.log.info("nk.button.label", .{});
nk.layout.rowDynamic(ctx, 0, 3);
if (nk.button.color(ctx, nk.rgb(180, 30, 30)))
std.log.info("nk.button.color: red", .{});
if (nk.button.color(ctx, nk.rgb(30, 180, 30)))
std.log.info("nk.button.color: green", .{});
if (nk.button.color(ctx, nk.rgb(30, 30, 180)))
std.log.info("nk.button.color: blue", .{});
if (nk.button.symbol(ctx, .circle_solid))
std.log.info("nk.button.symbol: circle", .{});
if (nk.button.symbol(ctx, .rect_solid))
std.log.info("nk.button.symbol: rect", .{});
if (nk.button.symbol(ctx, .triangle_up))
std.log.info("nk.button.symbol: triangle", .{});
// if (nk.button.image(ctx, undefined))
// std.log.info("nk.button.image", .{});
nk.layout.rowDynamic(ctx, 0, 1);
if (nk.button.symbolLabel(ctx, .rect_solid, "symbolLabel", .left))
std.log.info("nk.button.symbolLabel", .{});
var style = ctx.style.button;
style.normal.type = .NK_STYLE_ITEM_COLOR;
style.normal.data.color = nk.rgb(20, 20, 20);
if (nk.button.symbolStyled(ctx, .rect_solid, style))
std.log.info("nk.button.symbolStyled", .{});
// if (nk.button.imageStyled(ctx, undefined, style))
// std.log.info("nk.button.imageStyled", .{});
//
if (nk.button.symbolLabelStyled(
ctx,
.rect_solid,
"symbolLabelStyled",
.right,
style,
)) {
std.log.info("nk.button.symbolLabelStyled", .{});
}
// if (nk.button.imageLabelStyled(
// ctx,
// undefined,
// "imageLabelStyled",
// .right,
// style,
// )) {
// std.log.info("nk.button.symbolLabelStyled", .{});
// }
}
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.chart",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
const points = 10;
nk.layout.rowDynamic(ctx, 100, 1);
if (nk.chart.begin(ctx, .lines, points, 0, points - 1)) {
defer nk.chart.end(ctx);
var i: u8 = 0;
while (i < points) : (i += 1) {
if (nk.chart.push(ctx, @intToFloat(f32, i)) == .clicked)
std.log.info("nk.chart.begin: {}", .{i});
}
}
nk.chart.plot(ctx, .column, &[_]f32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 });
nk.chart.function(ctx, .lines, 100, 0, {}, struct {
fn func(_: void, index: usize) f32 {
return math.sqrt(@intToFloat(f32, index));
}
}.func);
}
nk.layout.rowDynamic(ctx, 130, 2);
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.checkbox",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 0, 1);
if (nk.checkbox.label(ctx, "label", &Static.checkbox_label))
std.log.info("nk.checkbox.label", .{});
if (nk.checkbox.flagsLabel(
ctx,
"flagsLabel",
&Static.checkbox_flags_label,
0b01,
)) {
std.log.info("nk.checkbox.flagsLabel", .{});
}
if (nk.checkbox.flagsLabel(
ctx,
"flagsLabel",
&Static.checkbox_flags_label,
0b10,
)) {
std.log.info("nk.checkbox.flagsLabel", .{});
}
}
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.check",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 0, 1);
Static.check_label = nk.check.label(ctx, "label", Static.check_label);
Static.check_flags_label = nk.check.flagsLabel(
ctx,
"flagsLabel",
Static.check_flags_label,
0b01,
);
Static.check_flags_label = nk.check.flagsLabel(
ctx,
"flagsLabel",
Static.check_flags_label,
0b10,
);
}
nk.layout.rowDynamic(ctx, 200, 1);
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.color",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 150, 2);
Static.color_picker_picked = nk.color.picker(ctx, Static.color_picker_picked, .rgb);
if (nk.color.pick(ctx, &Static.color_pick_picked, .rgba))
std.log.info("nk.color.pick: r={d:.2} g={d:.2} b={d:.2} a={d:.2}", .{
Static.color_pick_picked.r,
Static.color_pick_picked.g,
Static.color_pick_picked.b,
Static.color_pick_picked.a,
});
}
nk.layout.rowDynamic(ctx, 140, 1);
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.combo",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
const size = nk.vec2(200, 600);
nk.layout.rowDynamic(ctx, 0, 2);
Static.combo_items_selected = nk.combo.items(
ctx,
size,
16,
Static.combo_items_selected,
&.{
nk.slice("this"), nk.slice("is"), nk.slice("an"),
nk.slice("array"), nk.slice("of"), nk.slice("strings"),
},
);
Static.combo_sep_selected = nk.combo.separator(
ctx,
size,
16,
Static.combo_sep_selected,
5,
',',
"this,is,seperated,by,comma",
);
Static.combo_string_selected = nk.combo.string(
ctx,
size,
16,
Static.combo_string_selected,
5,
"this\x00is\x00seperated\x00by\x00null",
);
Static.combo_callback_selected = nk.combo.callback(
ctx,
size,
16,
Static.combo_callback_selected,
5,
{},
struct {
fn callback(_: void, index: usize) []const u8 {
return "abcdef"[0 .. index + 1];
}
}.callback,
);
if (nk.combo.beginLabel(ctx, size, Static.combo_begin_label_selected)) {
defer nk.combo.end(ctx);
nk.layout.rowDynamic(ctx, 0, 2);
if (nk.button.label(ctx, "pretty"))
Static.combo_begin_label_selected = "pretty";
if (nk.button.label(ctx, "neat"))
Static.combo_begin_label_selected = "neat";
nk.layout.rowDynamic(ctx, 0, 1);
if (nk.button.label(ctx, "BUTTONS!"))
Static.combo_begin_label_selected = "BUTTONS!";
}
}
// if (nk.group.begin(ctx, &nk.id(opaque {}), .{
// .title = "nk.contextual",
// .border = true,
// .scrollbar = false,
// })) {
// defer nk.group.end(ctx);
// }
if (nk.group.begin(ctx, &nk.id(opaque {}), .{
.title = "nk.edit",
.border = true,
.scrollbar = false,
})) {
defer nk.group.end(ctx);
nk.layout.rowDynamic(ctx, 0, 2);
_ = nk.edit.string(
ctx,
&Static.edit_string,
Static.edit_string_buf.len,
.{ .flags = nk.edit.Flags.simple },
);
_ = nk.edit.string(
ctx,
&Static.edit_string,
Static.edit_string_buf.len,
.{ .flags = nk.edit.Flags.field },
);
_ = nk.edit.string(
ctx,
&Static.edit_string,
Static.edit_string_buf.len,
.{ .flags = nk.edit.Flags.box },
);
_ = nk.edit.string(
ctx,
&Static.edit_string,
Static.edit_string_buf.len,
.{ .flags = nk.edit.Flags.editor },
);
}
}
nk.window.end(ctx);
} | examples/examples.zig |
const std = @import("std.zig");
const builtin = @import("builtin");
const testing = std.testing;
const assert = std.debug.assert;
const Backoff = std.SpinLock.Backoff;
const c = std.c;
const os = std.os;
const time = std.time;
const linux = os.linux;
const windows = os.windows;
/// A resource object which supports blocking until signaled.
/// Once finished, the `deinit()` method should be called for correctness.
pub const ResetEvent = struct {
os_event: OsEvent,
pub fn init() ResetEvent {
return ResetEvent{ .os_event = OsEvent.init() };
}
pub fn deinit(self: *ResetEvent) void {
self.os_event.deinit();
self.* = undefined;
}
/// Returns whether or not the event is currenetly set
pub fn isSet(self: *ResetEvent) bool {
return self.os_event.isSet();
}
/// Sets the event if not already set and
/// wakes up AT LEAST one thread waiting the event.
/// Returns whether or not a thread was woken up.
pub fn set(self: *ResetEvent, auto_reset: bool) bool {
return self.os_event.set(auto_reset);
}
/// Resets the event to its original, unset state.
/// Returns whether or not the event was currently set before un-setting.
pub fn reset(self: *ResetEvent) bool {
return self.os_event.reset();
}
const WaitError = error{
/// The thread blocked longer than the maximum time specified.
TimedOut,
};
/// Wait for the event to be set by blocking the current thread.
/// Optionally provided timeout in nanoseconds which throws an
/// `error.TimedOut` if the thread blocked AT LEAST longer than specified.
/// Returns whether or not the thread blocked from the event being unset at the time of calling.
pub fn wait(self: *ResetEvent, timeout_ns: ?u64) WaitError!bool {
return self.os_event.wait(timeout_ns);
}
};
const OsEvent = if (builtin.single_threaded) DebugEvent else switch (builtin.os) {
.windows => WindowsEvent,
.linux => if (builtin.link_libc) PosixEvent else LinuxEvent,
else => if (builtin.link_libc) PosixEvent else SpinEvent,
};
const DebugEvent = struct {
is_set: @TypeOf(set_init),
const set_init = if (std.debug.runtime_safety) false else {};
pub fn init() DebugEvent {
return DebugEvent{ .is_set = set_init };
}
pub fn deinit(self: *DebugEvent) void {
self.* = undefined;
}
pub fn isSet(self: *DebugEvent) bool {
if (!std.debug.runtime_safety)
return true;
return self.is_set;
}
pub fn set(self: *DebugEvent, auto_reset: bool) bool {
if (std.debug.runtime_safety)
self.is_set = !auto_reset;
return false;
}
pub fn reset(self: *DebugEvent) bool {
if (!std.debug.runtime_safety)
return false;
const was_set = self.is_set;
self.is_set = false;
return was_set;
}
pub fn wait(self: *DebugEvent, timeout: ?u64) ResetEvent.WaitError!bool {
if (std.debug.runtime_safety and !self.is_set)
@panic("deadlock detected");
return ResetEvent.WaitError.TimedOut;
}
};
fn AtomicEvent(comptime FutexImpl: type) type {
return struct {
state: u32,
const IS_SET: u32 = 1 << 0;
const WAIT_MASK = ~IS_SET;
pub const Self = @This();
pub const Futex = FutexImpl;
pub fn init() Self {
return Self{ .state = 0 };
}
pub fn deinit(self: *Self) void {
self.* = undefined;
}
pub fn isSet(self: *const Self) bool {
const state = @atomicLoad(u32, &self.state, .Acquire);
return (state & IS_SET) != 0;
}
pub fn reset(self: *Self) bool {
const old_state = @atomicRmw(u32, &self.state, .Xchg, 0, .Monotonic);
return (old_state & IS_SET) != 0;
}
pub fn set(self: *Self, auto_reset: bool) bool {
const new_state = if (auto_reset) 0 else IS_SET;
const old_state = @atomicRmw(u32, &self.state, .Xchg, new_state, .Release);
if ((old_state & WAIT_MASK) == 0) {
return false;
}
Futex.wake(&self.state);
return true;
}
pub fn wait(self: *Self, timeout: ?u64) ResetEvent.WaitError!bool {
var dummy_value: u32 = undefined;
const wait_token = @truncate(u32, @ptrToInt(&dummy_value));
var state = @atomicLoad(u32, &self.state, .Monotonic);
while (true) {
if ((state & IS_SET) != 0)
return false;
state = @cmpxchgWeak(u32, &self.state, state, wait_token, .Acquire, .Monotonic) orelse break;
}
try Futex.wait(&self.state, wait_token, timeout);
return true;
}
};
}
const SpinEvent = AtomicEvent(struct {
fn wake(ptr: *const u32) void {}
fn wait(ptr: *const u32, expected: u32, timeout: ?u64) ResetEvent.WaitError!void {
// TODO: handle platforms where time.Timer.start() fails
var spin = Backoff.init();
var timer = if (timeout == null) null else time.Timer.start() catch unreachable;
while (@atomicLoad(u32, ptr, .Acquire) == expected) {
spin.yield();
if (timeout) |timeout_ns| {
if (timer.?.read() > timeout_ns)
return ResetEvent.WaitError.TimedOut;
}
}
}
});
const LinuxEvent = AtomicEvent(struct {
fn wake(ptr: *const u32) void {
const key = @ptrCast(*const i32, ptr);
const rc = linux.futex_wake(key, linux.FUTEX_WAKE | linux.FUTEX_PRIVATE_FLAG, 1);
assert(linux.getErrno(rc) == 0);
}
fn wait(ptr: *const u32, expected: u32, timeout: ?u64) ResetEvent.WaitError!void {
var ts: linux.timespec = undefined;
var ts_ptr: ?*linux.timespec = null;
if (timeout) |timeout_ns| {
ts_ptr = &ts;
ts.tv_sec = @intCast(isize, timeout_ns / time.ns_per_s);
ts.tv_nsec = @intCast(isize, timeout_ns % time.ns_per_s);
}
const key = @ptrCast(*const i32, ptr);
const key_expect = @bitCast(i32, expected);
while (@atomicLoad(i32, key, .Acquire) == key_expect) {
const rc = linux.futex_wait(key, linux.FUTEX_WAIT | linux.FUTEX_PRIVATE_FLAG, key_expect, ts_ptr);
switch (linux.getErrno(rc)) {
0, linux.EAGAIN => break,
linux.EINTR => continue,
linux.ETIMEDOUT => return ResetEvent.WaitError.TimedOut,
else => unreachable,
}
}
}
});
const WindowsEvent = AtomicEvent(struct {
fn wake(ptr: *const u32) void {
if (getEventHandle()) |handle| {
const key = @ptrCast(*const c_void, ptr);
const rc = windows.ntdll.NtReleaseKeyedEvent(handle, key, windows.FALSE, null);
assert(rc == 0);
}
}
fn wait(ptr: *const u32, expected: u32, timeout: ?u64) ResetEvent.WaitError!void {
// fallback to spinlock if NT Keyed Events arent available
const handle = getEventHandle() orelse {
return SpinEvent.Futex.wait(ptr, expected, timeout);
};
// NT uses timeouts in units of 100ns with negative value being relative
var timeout_ptr: ?*windows.LARGE_INTEGER = null;
var timeout_value: windows.LARGE_INTEGER = undefined;
if (timeout) |timeout_ns| {
timeout_ptr = &timeout_value;
timeout_value = -@intCast(windows.LARGE_INTEGER, timeout_ns / 100);
}
// NtWaitForKeyedEvent doesnt have spurious wake-ups
if (@atomicLoad(u32, ptr, .Acquire) == expected) {
const key = @ptrCast(*const c_void, ptr);
const rc = windows.ntdll.NtWaitForKeyedEvent(handle, key, windows.FALSE, timeout_ptr);
switch (rc) {
0 => {},
windows.WAIT_TIMEOUT => return ResetEvent.WaitError.TimedOut,
else => unreachable,
}
}
}
var keyed_state = State.Uninitialized;
var keyed_handle: ?windows.HANDLE = null;
const State = enum(u8) {
Uninitialized,
Intializing,
Initialized,
};
fn getEventHandle() ?windows.HANDLE {
var spin = Backoff.init();
var state = @atomicLoad(State, &keyed_state, .Monotonic);
while (true) {
switch (state) {
.Initialized => {
return keyed_handle;
},
.Intializing => {
spin.yield();
state = @atomicLoad(State, &keyed_state, .Acquire);
},
.Uninitialized => state = @cmpxchgWeak(State, &keyed_state, state, .Intializing, .Acquire, .Monotonic) orelse {
var handle: windows.HANDLE = undefined;
const access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE;
if (windows.ntdll.NtCreateKeyedEvent(&handle, access_mask, null, 0) == 0)
keyed_handle = handle;
@atomicStore(State, &keyed_state, .Initialized, .Release);
return keyed_handle;
},
}
}
}
});
const PosixEvent = struct {
state: u32,
cond: c.pthread_cond_t,
mutex: c.pthread_mutex_t,
const IS_SET: u32 = 1;
pub fn init() PosixEvent {
return PosixEvent{
.state = 0,
.cond = c.PTHREAD_COND_INITIALIZER,
.mutex = c.PTHREAD_MUTEX_INITIALIZER,
};
}
pub fn deinit(self: *PosixEvent) void {
// On dragonfly, the destroy functions return EINVAL if they were initialized statically.
const retm = c.pthread_mutex_destroy(&self.mutex);
assert(retm == 0 or retm == (if (builtin.os == .dragonfly) os.EINVAL else 0));
const retc = c.pthread_cond_destroy(&self.cond);
assert(retc == 0 or retc == (if (builtin.os == .dragonfly) os.EINVAL else 0));
}
pub fn isSet(self: *PosixEvent) bool {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
return self.state == IS_SET;
}
pub fn reset(self: *PosixEvent) bool {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
const was_set = self.state == IS_SET;
self.state = 0;
return was_set;
}
pub fn set(self: *PosixEvent, auto_reset: bool) bool {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
const had_waiter = self.state > IS_SET;
self.state = if (auto_reset) 0 else IS_SET;
if (had_waiter) {
assert(c.pthread_cond_signal(&self.cond) == 0);
}
return had_waiter;
}
pub fn wait(self: *PosixEvent, timeout: ?u64) ResetEvent.WaitError!bool {
assert(c.pthread_mutex_lock(&self.mutex) == 0);
defer assert(c.pthread_mutex_unlock(&self.mutex) == 0);
if (self.state == IS_SET)
return false;
var ts: os.timespec = undefined;
if (timeout) |timeout_ns| {
var timeout_abs = timeout_ns;
if (comptime std.Target.current.isDarwin()) {
var tv: os.darwin.timeval = undefined;
assert(os.darwin.gettimeofday(&tv, null) == 0);
timeout_abs += @intCast(u64, tv.tv_sec) * time.second;
timeout_abs += @intCast(u64, tv.tv_usec) * time.microsecond;
} else {
os.clock_gettime(os.CLOCK_REALTIME, &ts) catch unreachable;
timeout_abs += @intCast(u64, ts.tv_sec) * time.second;
timeout_abs += @intCast(u64, ts.tv_nsec);
}
ts.tv_sec = @intCast(@TypeOf(ts.tv_sec), @divFloor(timeout_abs, time.second));
ts.tv_nsec = @intCast(@TypeOf(ts.tv_nsec), @mod(timeout_abs, time.second));
}
var dummy_value: u32 = undefined;
var wait_token = @truncate(u32, @ptrToInt(&dummy_value));
self.state = wait_token;
while (self.state == wait_token) {
const rc = switch (timeout == null) {
true => c.pthread_cond_wait(&self.cond, &self.mutex),
else => c.pthread_cond_timedwait(&self.cond, &self.mutex, &ts),
};
// TODO: rc appears to be the positive error code making os.errno() always return 0 on linux
switch (std.math.max(@as(c_int, os.errno(rc)), rc)) {
0 => {},
os.ETIMEDOUT => return ResetEvent.WaitError.TimedOut,
os.EINVAL => unreachable,
os.EPERM => unreachable,
else => unreachable,
}
}
return true;
}
};
test "std.ResetEvent" {
// TODO
if (builtin.single_threaded)
return error.SkipZigTest;
var event = ResetEvent.init();
defer event.deinit();
// test event setting
testing.expect(event.isSet() == false);
testing.expect(event.set(false) == false);
testing.expect(event.isSet() == true);
// test event resetting
testing.expect(event.reset() == true);
testing.expect(event.isSet() == false);
testing.expect(event.reset() == false);
// test cross thread signaling
const Context = struct {
event: ResetEvent,
value: u128,
fn receiver(self: *@This()) void {
// wait for the sender to notify us with updated value
assert(self.value == 0);
assert((self.event.wait(1 * time.second) catch unreachable) == true);
assert(self.value == 1);
// wait for sender to sleep, then notify it of new value
time.sleep(50 * time.millisecond);
self.value = 2;
assert(self.event.set(false) == true);
}
fn sender(self: *@This()) !void {
// wait for the receiver() to start wait()'ing
time.sleep(50 * time.millisecond);
// update value to 1 and notify the receiver()
assert(self.value == 0);
self.value = 1;
assert(self.event.set(true) == true);
// wait for the receiver to update the value & notify us
assert((try self.event.wait(1 * time.second)) == true);
assert(self.value == 2);
}
};
_ = event.reset();
var context = Context{
.event = event,
.value = 0,
};
var receiver = try std.Thread.spawn(&context, Context.receiver);
defer receiver.wait();
try context.sender();
} | lib/std/reset_event.zig |
const std = @import("std");
const getty = @import("getty");
const Serializer = @import("serializer.zig").Serializer;
const Token = @import("common/token.zig").Token;
const allocator = std.testing.allocator;
test "array" {
try t([_]i32{}, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
try t([_]i32{ 1, 2, 3 }, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
});
}
test "array list" {
// managed
{
var list = std.ArrayList(std.ArrayList(i32)).init(allocator);
defer list.deinit();
var a = std.ArrayList(i32).init(allocator);
defer a.deinit();
var b = std.ArrayList(i32).init(allocator);
defer b.deinit();
var c = std.ArrayList(i32).init(allocator);
defer c.deinit();
try t(list, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
try b.append(1);
try c.append(2);
try c.append(3);
try list.appendSlice(&[_]std.ArrayList(i32){ a, b, c });
try t(list, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
.{ .Seq = .{ .len = 1 } },
.{ .I32 = 1 },
.{ .SeqEnd = .{} },
.{ .Seq = .{ .len = 2 } },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
.{ .SeqEnd = .{} },
});
}
// unmanaged
{
var list = std.ArrayListUnmanaged(std.ArrayListUnmanaged(i32)){};
defer list.deinit(allocator);
var a = std.ArrayListUnmanaged(i32){};
defer a.deinit(allocator);
var b = std.ArrayListUnmanaged(i32){};
defer b.deinit(allocator);
var c = std.ArrayListUnmanaged(i32){};
defer c.deinit(allocator);
try t(list, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
try b.append(allocator, 1);
try c.append(allocator, 2);
try c.append(allocator, 3);
try list.appendSlice(allocator, &[_]std.ArrayListUnmanaged(i32){ a, b, c });
try t(list, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
.{ .Seq = .{ .len = 1 } },
.{ .I32 = 1 },
.{ .SeqEnd = .{} },
.{ .Seq = .{ .len = 2 } },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
.{ .SeqEnd = .{} },
});
}
}
test "bool" {
try t(true, &[_]Token{.{ .Bool = true }});
try t(false, &[_]Token{.{ .Bool = false }});
}
test "enum" {
// literal
try t(.foo, &[_]Token{ .{ .Enum = {} }, .{ .String = "foo" } });
try t(.bar, &[_]Token{ .{ .Enum = {} }, .{ .String = "bar" } });
// non-literal
const T = enum { foo, bar };
try t(T.foo, &[_]Token{ .{ .Enum = {} }, .{ .String = "foo" } });
try t(T.bar, &[_]Token{ .{ .Enum = {} }, .{ .String = "bar" } });
}
test "error" {
try t(error.Foobar, &[_]Token{.{ .String = "Foobar" }});
}
// TODO: Serializing a f128 results in a compiler bug. I believe it its because
// f128 and anytype don't work well together.
test "float" {
// comptime_float
try t(0.0, &[_]Token{.{ .ComptimeFloat = {} }});
// float
try t(@as(f16, 0), &[_]Token{.{ .F16 = 0 }});
try t(@as(f32, 0), &[_]Token{.{ .F32 = 0 }});
try t(@as(f64, 0), &[_]Token{.{ .F64 = 0 }});
//try t(@as(f128, 0), &[_]Token{.{ .F128 = 0 }});
}
test "hash map" {
// managed
{
var map = std.AutoHashMap(i32, i32).init(allocator);
defer map.deinit();
try t(map, &[_]Token{
.{ .Map = .{ .len = 0 } },
.{ .MapEnd = .{} },
});
try map.put(1, 2);
try t(map, &[_]Token{
.{ .Map = .{ .len = 1 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .MapEnd = .{} },
});
}
// unmanaged
{
var map = std.AutoHashMapUnmanaged(i32, i32){};
defer map.deinit(allocator);
try t(map, &[_]Token{
.{ .Map = .{ .len = 0 } },
.{ .MapEnd = .{} },
});
try map.put(allocator, 1, 2);
try t(map, &[_]Token{
.{ .Map = .{ .len = 1 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .MapEnd = .{} },
});
}
// string
{
var map = std.StringHashMap(i32).init(allocator);
defer map.deinit();
try t(map, &[_]Token{
.{ .Map = .{ .len = 0 } },
.{ .MapEnd = .{} },
});
try map.put("1", 2);
try t(map, &[_]Token{
.{ .Map = .{ .len = 1 } },
.{ .String = "1" },
.{ .I32 = 2 },
.{ .MapEnd = .{} },
});
}
}
test "integer" {
// comptime_int
try t(0, &[_]Token{.{ .ComptimeInt = {} }});
// signed
try t(@as(i8, 0), &[_]Token{.{ .I8 = 0 }});
try t(@as(i16, 0), &[_]Token{.{ .I16 = 0 }});
try t(@as(i32, 0), &[_]Token{.{ .I32 = 0 }});
try t(@as(i64, 0), &[_]Token{.{ .I64 = 0 }});
try t(@as(i128, 0), &[_]Token{.{ .I128 = 0 }});
// unsigned
try t(@as(u8, 0), &[_]Token{.{ .U8 = 0 }});
try t(@as(u16, 0), &[_]Token{.{ .U16 = 0 }});
try t(@as(u32, 0), &[_]Token{.{ .U32 = 0 }});
try t(@as(u64, 0), &[_]Token{.{ .U64 = 0 }});
try t(@as(u128, 0), &[_]Token{.{ .U128 = 0 }});
}
test "linked list" {
var list = std.SinglyLinkedList(i32){};
try t(list, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
var one = @TypeOf(list).Node{ .data = 1 };
var two = @TypeOf(list).Node{ .data = 2 };
var three = @TypeOf(list).Node{ .data = 3 };
list.prepend(&one);
one.insertAfter(&two);
two.insertAfter(&three);
try t(list, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
});
}
test "null" {
try t(null, &[_]Token{.{ .Null = {} }});
}
test "optional" {
try t(@as(?i32, null), &[_]Token{.{ .Null = {} }});
try t(@as(?i32, 0), &[_]Token{ .{ .Some = {} }, .{ .I32 = 0 } });
}
test "pointer" {
// one level of indirection
{
var ptr = try allocator.create(i32);
defer allocator.destroy(ptr);
ptr.* = @as(i32, 1);
try t(ptr, &[_]Token{.{ .I32 = 1 }});
}
// two levels of indirection
{
var tmp = try allocator.create(i32);
defer allocator.destroy(tmp);
tmp.* = 2;
var ptr = try allocator.create(*i32);
defer allocator.destroy(ptr);
ptr.* = tmp;
try t(ptr, &[_]Token{.{ .I32 = 2 }});
}
// pointer to slice
{
var ptr = try allocator.create([]const u8);
defer allocator.destroy(ptr);
ptr.* = "3";
try t(ptr, &[_]Token{.{ .String = "3" }});
}
}
test "slice" {
try t(&[_]i32{}, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
try t(&[_]i32{ 1, 2, 3 }, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
});
}
test "string" {
try t("abc", &[_]Token{.{ .String = "abc" }});
try t(&[_]u8{ 'a', 'b', 'c' }, &[_]Token{.{ .String = "abc" }});
try t(&[_:0]u8{ 'a', 'b', 'c' }, &[_]Token{.{ .String = "abc" }});
}
test "struct" {
const Struct = struct { a: i32, b: i32, c: i32 };
try t(Struct{ .a = 1, .b = 2, .c = 3 }, &[_]Token{
.{ .Struct = .{ .name = "Struct", .len = 3 } },
.{ .String = "a" },
.{ .I32 = 1 },
.{ .String = "b" },
.{ .I32 = 2 },
.{ .String = "c" },
.{ .I32 = 3 },
.{ .StructEnd = {} },
});
}
test "tail queue" {
var list = std.TailQueue(i32){};
try t(list, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
var one = @TypeOf(list).Node{ .data = 1 };
var two = @TypeOf(list).Node{ .data = 2 };
var three = @TypeOf(list).Node{ .data = 3 };
list.append(&one);
list.append(&two);
list.append(&three);
try t(list, &[_]Token{
.{ .Seq = .{ .len = 3 } },
.{ .I32 = 1 },
.{ .I32 = 2 },
.{ .I32 = 3 },
.{ .SeqEnd = .{} },
});
}
test "tuple" {
try t(.{}, &[_]Token{
.{ .Seq = .{ .len = 0 } },
.{ .SeqEnd = .{} },
});
try t(std.meta.Tuple(&[_]type{ i32, bool }){ 1, true }, &[_]Token{
.{ .Seq = .{ .len = 2 } },
.{ .I32 = 1 },
.{ .Bool = true },
.{ .SeqEnd = .{} },
});
try t(.{ @as(i32, 1), true }, &[_]Token{
.{ .Seq = .{ .len = 2 } },
.{ .I32 = 1 },
.{ .Bool = true },
.{ .SeqEnd = .{} },
});
}
test "union" {
const Union = union(enum) { Int: i32, Bool: bool };
try t(Union{ .Int = 0 }, &[_]Token{.{ .I32 = 0 }});
try t(Union{ .Bool = true }, &[_]Token{.{ .Bool = true }});
}
test "vector" {
try t(@splat(2, @as(i32, 1)), &[_]Token{
.{ .Seq = .{ .len = 2 } },
.{ .I32 = 1 },
.{ .I32 = 1 },
.{ .SeqEnd = {} },
});
}
test "void" {
try t({}, &[_]Token{.{ .Void = {} }});
}
fn t(v: anytype, tokens: []const Token) !void {
var s = Serializer.init(tokens);
getty.serialize(v, s.serializer()) catch return error.TestUnexpectedError;
try std.testing.expect(s.remaining() == 0);
} | src/tests/ser/tests.zig |
const std = @import("std");
const c = @import("c.zig");
const util = @import("util.zig");
// TODO: calculate this whole error and function below at comptime
const CompilationError = error{
// Success = 0
InvalidStage,
CompilationError,
InternalError,
NullResultObject,
InvalidAssembly,
ValidationError,
TransformationError,
ConfigurationError,
UnknownError,
};
fn status_to_err(i: c_int) CompilationError {
switch (i) {
c.shaderc_compilation_status_invalid_stage => return CompilationError.InvalidStage,
c.shaderc_compilation_status_compilation_error => return CompilationError.CompilationError,
c.shaderc_compilation_status_internal_error => return CompilationError.InternalError,
c.shaderc_compilation_status_null_result_object => return CompilationError.NullResultObject,
c.shaderc_compilation_status_invalid_assembly => return CompilationError.InvalidAssembly,
c.shaderc_compilation_status_validation_error => return CompilationError.ValidationError,
c.shaderc_compilation_status_transformation_error => return CompilationError.TransformationError,
c.shaderc_compilation_status_configuration_error => return CompilationError.ConfigurationError,
else => return CompilationError.UnknownError,
}
}
export fn include_cb(
user_data: ?*c_void,
requested_source: [*c]const u8,
include_type: c_int,
requesting_source: [*c]const u8,
include_depth: usize,
) *c.shaderc_include_result {
_ = include_type;
_ = requesting_source;
_ = include_depth;
const alloc = @ptrCast(*std.mem.Allocator, @alignCast(8, user_data));
var out = alloc.create(c.shaderc_include_result) catch |err| {
std.debug.panic("Could not allocate shaderc_include_result: {}", .{err});
};
out.* = (c.shaderc_include_result){
.user_data = user_data,
.source_name = "",
.source_name_length = 0,
.content = null,
.content_length = 0,
};
const name = std.mem.spanZ(requested_source);
const file = std.fs.cwd().openFile(name, std.fs.File.OpenFlags{ .read = true }) catch |err| {
const msg = std.fmt.allocPrint(alloc, "{}", .{err}) catch |err2| {
std.debug.panic("Could not allocate error message: {}", .{err2});
};
out.content = msg.ptr;
out.content_length = msg.len;
return out;
};
defer file.close();
const size = file.getEndPos() catch |err| {
std.debug.panic("Could not get end position of file: {}", .{err});
};
const buf = alloc.alloc(u8, size) catch |err| {
std.debug.panic("Could not allocate space for data: {}", .{err});
};
_ = file.readAll(buf) catch |err| {
std.debug.panic("Could not read header: {}", .{err});
};
out.source_name = requested_source;
out.source_name_length = name.len;
out.content = buf.ptr;
out.content_length = buf.len;
return out;
}
export fn include_release_cb(user_data: ?*c_void, include_result: ?*c.shaderc_include_result) void {
// We don't need to do anything here, because we're using an arena allocator
_ = user_data;
_ = include_result;
}
pub fn build_shader_from_file(alloc: *std.mem.Allocator, comptime name: []const u8) ![]u32 {
var arena = std.heap.ArenaAllocator.init(alloc);
defer arena.deinit();
const buf = try util.file_contents(&arena, name);
return build_shader(alloc, name, buf);
}
pub fn build_shader(alloc: *std.mem.Allocator, name: []const u8, src: []const u8) ![]u32 {
var arena = std.heap.ArenaAllocator.init(alloc);
var tmp_alloc: *std.mem.Allocator = &arena.allocator;
defer arena.deinit();
const compiler = c.shaderc_compiler_initialize();
defer c.shaderc_compiler_release(compiler);
const options = c.shaderc_compile_options_initialize();
defer c.shaderc_compile_options_release(options);
c.shaderc_compile_options_set_include_callbacks(
options,
include_cb,
include_release_cb,
tmp_alloc,
);
const result = c.shaderc_compile_into_spv(
compiler,
src.ptr,
src.len,
c.shaderc_glsl_infer_from_source,
name.ptr,
"main",
options,
);
defer c.shaderc_result_release(result);
const r = c.shaderc_result_get_compilation_status(result);
// if (@enumToInt(r) != c.shaderc_compilation_status_success) {
if (r != c.shaderc_compilation_status_success) {
const err = c.shaderc_result_get_error_message(result);
std.debug.warn("Shader error: {} {s}\n", .{ r, err });
// return status_to_err(@enumToInt(r));
return status_to_err(@intCast(c_int, r));
}
// Copy the result out of the shader
const len = c.shaderc_result_get_length(result);
std.debug.assert(len % 4 == 0);
const out = alloc.alloc(u32, len / 4) catch unreachable;
@memcpy(@ptrCast([*]u8, out.ptr), c.shaderc_result_get_bytes(result), len);
return out;
}
////////////////////////////////////////////////////////////////////////////////
pub const LineErr = struct {
msg: []const u8,
line: ?u32,
};
pub const Error = struct {
errs: []const LineErr,
code: c.shaderc_compilation_status,
};
pub const Shader = struct {
spirv: []const u32,
has_time: bool,
};
pub const Result = union(enum) {
Shader: Shader,
Error: Error,
pub fn deinit(self: Result, alloc: *std.mem.Allocator) void {
switch (self) {
.Shader => |d| alloc.free(d.spirv),
.Error => |e| {
for (e.errs) |r| {
alloc.free(r.msg);
}
alloc.free(e.errs);
},
}
}
}; | src/shaderc.zig |
const std = @import("std");
const string = []const u8;
const input = @embedFile("../input/day08.txt");
const constraints = struct {
pub const zer: [7]u1 = .{ 1, 1, 1, 0, 1, 1, 1 }; // 0
pub const one: [7]u1 = .{ 0, 0, 1, 0, 0, 1, 0 }; // 1
pub const two: [7]u1 = .{ 1, 0, 1, 1, 1, 0, 1 }; // 2
pub const thr: [7]u1 = .{ 1, 0, 1, 1, 0, 1, 1 }; // 3
pub const fou: [7]u1 = .{ 0, 1, 1, 1, 0, 1, 0 }; // 4
pub const fiv: [7]u1 = .{ 1, 1, 0, 1, 0, 1, 1 }; // 5
pub const six: [7]u1 = .{ 1, 1, 0, 1, 1, 1, 1 }; // 6
pub const sev: [7]u1 = .{ 1, 0, 1, 0, 0, 1, 0 }; // 7
pub const eit: [7]u1 = .{ 1, 1, 1, 1, 1, 1, 1 }; // 8
pub const nin: [7]u1 = .{ 1, 1, 1, 1, 0, 1, 1 }; // 9
pub const _all = [_][7]u1{ zer, one, two, thr, fou, fiv, six, sev, eit, nin };
};
pub fn main() !void {
//
// part 1
{
var iter = std.mem.split(u8, input, "\n");
var count: u32 = 0;
while (iter.next()) |line| {
if (line.len == 0) continue;
const bar_index = std.mem.indexOf(u8, line, " | ").?;
// const input = line[0..bar_index];
const output = line[bar_index + 3 ..];
var out_iter = std.mem.split(u8, output, " ");
while (out_iter.next()) |jtem| {
if (jtem.len == 2) count += 1; // 1
if (jtem.len == 4) count += 1; // 4
if (jtem.len == 3) count += 1; // 7
if (jtem.len == 7) count += 1; // 8
}
}
std.debug.print("{d}\n", .{count});
}
// part 2
{
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const alloc = &arena.allocator;
var iter = std.mem.split(u8, input, "\n");
var sum: u32 = 0;
while (iter.next()) |line| {
if (line.len == 0) continue;
const bar_index = std.mem.indexOf(u8, line, " | ").?;
const in = try splitAlloc(alloc, line[0..bar_index], " ");
const out = try splitAlloc(alloc, line[bar_index + 3 ..], " ");
// make a list for each letter of the possible positions it might be, start with all true
var positions = PosPossibilities{
.letters = .{
[_]u1{1} ** 7,
[_]u1{1} ** 7,
[_]u1{1} ** 7,
[_]u1{1} ** 7,
[_]u1{1} ** 7,
[_]u1{1} ** 7,
[_]u1{1} ** 7,
},
.numbers = std.StringHashMap(std.ArrayList(u32)).init(alloc),
};
// read input numbers and slowly remove positions from each list based on constraints
for (in) |item| {
try positions.numbers.put(item, std.ArrayList(u32).init(alloc));
if (item.len == 2) positions.mustBe(item, constraints.one, 1);
if (item.len == 4) positions.mustBe(item, constraints.fou, 4);
if (item.len == 3) positions.mustBe(item, constraints.sev, 7);
if (item.len == 7) positions.mustBe(item, constraints.eit, 8);
if (item.len == 5) {
try positions.numbers.getEntry(item).?.value_ptr.*.appendSlice(&[_]u32{ 2, 3, 5 });
}
if (item.len == 6) {
try positions.numbers.getEntry(item).?.value_ptr.*.appendSlice(&[_]u32{ 0, 6, 9 });
}
}
// for dab - ab to top position
const diff_7_1 = try difference(alloc, positions.seqByNum(1, 1)[0], positions.seqByNum(1, 7)[0]);
const spot_a = diff_7_1[0];
positions.set(spot_a, 'a');
// for ef set all to 0 except bd
const diff_1_4 = try difference(alloc, positions.seqByNum(1, 1)[0], positions.seqByNum(1, 4)[0]);
positions.setMulti(diff_1_4, "bd");
// put f in the middle from the intersection of 4, 2, 3, 5
// (gcdfa fbcad cdfbe ef) f
const poses_2 = positions.seqByNum(3, 2);
const diff_4235 = try intersection(alloc, &[_]string{ diff_1_4, poses_2[0], poses_2[1], poses_2[2] });
const spot_d = diff_4235[0];
positions.set(spot_d, 'd');
/////// intersection of 2, 3, 5 thats not in spot_d is in spot_b
// (gcdfa fbcad cdfbe) - d = e
const spot_b = std.mem.trim(u8, diff_1_4, diff_4235)[0];
positions.set(spot_b, 'b');
// intersection of 2, 3, 5 thats not spot_a or spot_d is in spot_g (c)
const diff_235 = try intersection(alloc, &poses_2);
const spot_g = (try trim(alloc, diff_235, &[_]u8{ spot_a, diff_4235[0] }))[0];
positions.set(spot_g, 'g');
// we found 5
for (poses_2) |item| {
const list = positions.numbers.getEntry(item).?.value_ptr;
if (std.mem.indexOfScalar(u8, item, spot_b)) |_| {
list.items[0] = 5;
list.shrinkRetainingCapacity(1);
} else {
_ = list.orderedRemove(indexOf(list.items, 5));
}
}
// dealing with 2 and 3
{
// gcdfa fbcad
// ga ba
// b { 0, 0, 1, 0, 0, 1, 0 }
// g { 0, 0, 1, 0, 1, 1, 0 }
const poses_2_new = positions.seqByNum(2, 2);
const to_check = try difference(alloc, poses_2_new[0], poses_2_new[1]);
const x = positions.letters[to_check[0] - 'a'];
const y = positions.letters[to_check[1] - 'a'];
for (x) |item, i| {
if (item != y[i]) {
if (item == 1) {
positions.set(to_check[0], @intCast(u8, i) + 'a');
}
if (y[i] == 1) {
positions.set(to_check[1], @intCast(u8, i) + 'a');
}
}
}
}
// final spot, spot_f
const diff_1_5 = try intersection(alloc, &[_]string{ positions.seqByNum(1, 1)[0], positions.seqByNum(1, 5)[0] });
positions.set(diff_1_5[0], 'f');
// remap output numbers
const real = positions.fixed();
// deafgbc -> cdfeb
var num_s: [4]u8 = undefined;
for (out) |item, i| {
var temp = std.mem.zeroes([7]u1);
for (item) |c| {
temp[std.mem.indexOfScalar(u8, &real, c).?] = 1;
}
for (constraints._all) |jtem, j| {
if (std.mem.eql(u1, &temp, &jtem)) {
num_s[i] = @intCast(u8, j) + '0';
}
}
}
// add to running sum
const num = try std.fmt.parseUnsigned(u32, &num_s, 10);
sum += num;
}
std.debug.print("{d}\n", .{sum});
}
}
const PosPossibilities = struct {
letters: [7][7]u1,
numbers: std.StringHashMap(std.ArrayList(u32)),
pub fn mustBe(self: *PosPossibilities, sequence: string, constraint: [7]u1, number: u32) void {
for (sequence) |c| {
for (constraint) |o, j| {
self.letters[c - 'a'][j] &= o;
}
}
self.numbers.getEntry(sequence).?.value_ptr.*.append(number) catch @panic("");
}
pub fn seqByNum(self: PosPossibilities, comptime N: usize, number: u32) [N]string {
var iter = self.numbers.iterator();
var result: [N]string = undefined;
var i: usize = 0;
while (iter.next()) |entry| {
if (std.mem.indexOfScalar(u32, entry.value_ptr.*.items, number)) |_| {
result[i] = entry.key_ptr.*;
i += 1;
}
}
return result;
}
pub fn set(self: *PosPossibilities, x: u8, y: u8) void {
for (self.letters) |_, i| self.letters[x - 'a'][i] = 0;
for (self.letters) |_, i| self.letters[i][y - 'a'] = 0;
self.letters[x - 'a'][y - 'a'] = 1;
}
pub fn setMulti(self: *PosPossibilities, diff: []const u8, valid: []const u8) void {
for (diff) |c| {
for (self.letters) |_, i| self.letters[c - 'a'][i] = 0;
for (valid) |v| self.letters[c - 'a'][v - 'a'] = 1;
}
}
pub fn fixed(self: PosPossibilities) [7]u8 {
var res: [7]u8 = undefined;
for (self.letters) |item, i| {
for (item) |jtem, j| {
if (jtem == 1) {
res[j] = @intCast(u8, i) + 'a';
}
}
}
return res;
}
};
fn splitAlloc(alloc: *std.mem.Allocator, in: string, delim: string) ![]const string {
var list = std.ArrayList(string).init(alloc);
var iter = std.mem.split(u8, in, delim);
while (iter.next()) |item| {
try list.append(item);
}
return list.toOwnedSlice();
}
fn difference(alloc: *std.mem.Allocator, a: string, b: string) !string {
if (a.len > b.len) {
return try trim(alloc, a, b);
}
if (b.len > a.len) {
return try trim(alloc, b, a);
}
var list = std.ArrayList(u8).init(alloc);
defer list.deinit();
try list.writer().writeAll(try trim(alloc, a, b));
try list.writer().writeAll(try trim(alloc, b, a));
return list.toOwnedSlice();
}
fn trim(alloc: *std.mem.Allocator, in: string, values_to_strip: []const u8) !string {
var list = std.ArrayList(u8).init(alloc);
defer list.deinit();
for (in) |c| {
if (std.mem.indexOfScalar(u8, values_to_strip, c)) |_| {} else {
try list.append(c);
}
}
return list.toOwnedSlice();
}
// put the smallest first
fn intersection(alloc: *std.mem.Allocator, xs: []const string) !string {
var list = std.ArrayList(u8).init(alloc);
defer list.deinit();
for (xs[0]) |c| {
var bad = false;
for (xs) |x| {
if (std.mem.indexOfScalar(u8, x, c)) |_| {} else {
bad = true;
break;
}
}
if (!bad) {
try list.append(c);
}
}
return list.toOwnedSlice();
}
fn indexOf(haystack: []const u32, needle: u32) usize {
for (haystack) |item, i| {
if (item == needle) {
return i;
}
}
@panic("it really should be there...");
} | src/day08.zig |
const std = @import("std");
const log = std.log.default;
const build_options = @import("build_options");
const c = @import("c.zig");
const program_name = build_options.program_name;
const WaylandState = struct {
wl_display: ?*c.wl_display = null,
wl_registry: ?*c.wl_registry = null,
wl_shm: ?*c.wl_shm = null,
wl_compositor: ?*c.wl_compositor = null,
xdg_wm_base: ?*c.xdg_wm_base = null,
wl_surface: ?*c.wl_surface = null,
xdg_surface: ?*c.xdg_surface = null,
xdg_toplevel: ?*c.xdg_toplevel = null,
};
fn random_name(buffer: []u8) void {
var timestamp = std.time.nanoTimestamp();
for (buffer) |*buf| {
buf.* = 'A' + @intCast(u8, (timestamp & 0xf) + (timestamp & 0x10) * 2);
timestamp >>= 5;
}
}
fn create_shm_file() !i32 {
const base_path = "/dev/shm/wl_shm-";
var file_path: [base_path.len + "XXXXXX".len]u8 = undefined;
std.mem.copy(u8, &file_path, base_path);
var retries: usize = 100;
return blk: while (retries > 0) : (retries -= 1) {
random_name(file_path[base_path.len..]);
var fd = std.os.open(
&file_path,
std.os.O.RDWR | std.os.O.CREAT | std.os.O.EXCL | std.os.O.NOFOLLOW | std.os.O.CLOEXEC,
0600,
) catch |e| {
if (e == error.PathAlreadyExists) continue;
break :blk e;
};
try std.os.unlink(&file_path);
break :blk fd;
} else error.TooManyRetries;
}
fn wlBufferRelease(_: ?*c_void, wl_buffer: ?*c.wl_buffer) callconv(.C) void {
c.wl_buffer_destroy(wl_buffer);
}
const wl_buffer_listener = c.wl_buffer_listener{
.release = wlBufferRelease,
};
fn drawFrame(state: *WaylandState) !?*c.wl_buffer {
const width = 1920;
const height = 1080;
const stride = width * 4;
const size = height * stride;
const shm_fd = try create_shm_file();
defer std.os.close(shm_fd);
try std.os.ftruncate(shm_fd, size);
var data = try std.os.mmap(
null,
size,
std.os.PROT.READ | std.os.PROT.WRITE,
std.os.MAP.SHARED,
shm_fd,
0,
);
defer std.os.munmap(data);
const pool = c.wl_shm_create_pool(state.wl_shm, shm_fd, size);
defer c.wl_shm_pool_destroy(pool);
const buffer = c.wl_shm_pool_create_buffer(
pool,
0,
width,
height,
stride,
c.WL_SHM_FORMAT_ARGB8888,
);
var pixels = std.mem.bytesAsSlice(u32, data);
for (pixels) |*pixel| pixel.* = 0x33ff00ff;
_ = c.wl_buffer_add_listener(buffer, &wl_buffer_listener, null);
return buffer;
}
fn xdgSurfaceConfigure(data: ?*c_void, xdg_surface: ?*c.xdg_surface, serial: u32) callconv(.C) void {
var state = @ptrCast(*WaylandState, @alignCast(@alignOf(WaylandState), data));
c.xdg_surface_ack_configure(xdg_surface, serial);
const buffer = drawFrame(state) catch unreachable;
c.wl_surface_attach(state.wl_surface, buffer, 0, 0);
c.wl_surface_commit(state.wl_surface);
// c.wl_surface_damage(surface, 0, 0, width, height);
}
const xdg_surface_listener = c.xdg_surface_listener{
.configure = xdgSurfaceConfigure,
};
fn xdgWmBasePing(_: ?*c_void, xdg_wm_base: ?*c.xdg_wm_base, serial: u32) callconv(.C) void {
c.xdg_wm_base_pong(xdg_wm_base, serial);
}
const xdg_wm_base_listener = c.xdg_wm_base_listener{
.ping = xdgWmBasePing,
};
fn registryHandleGlobal(
data: ?*c_void,
registry: ?*c.wl_registry,
name: u32,
interface: [*c]const u8,
version: u32,
) callconv(.C) void {
if (false)
log.info("interface: '{s}', version: {d}, name {d}", .{ interface, version, name });
var state = @ptrCast(*WaylandState, @alignCast(@alignOf(WaylandState), data));
const interface_slice = std.mem.span(interface);
const compositor_slice = std.mem.span(c.wl_compositor_interface.name);
const shm_slice = std.mem.span(c.wl_shm_interface.name);
const xdg_wm_base_slice = std.mem.span(c.xdg_wm_base_interface.name);
if (std.mem.eql(u8, interface_slice, compositor_slice)) {
state.wl_compositor = @ptrCast(*c.wl_compositor, c.wl_registry_bind(
registry,
name,
&c.wl_compositor_interface,
version,
));
} else if (std.mem.eql(u8, interface_slice, shm_slice)) {
state.wl_shm = @ptrCast(*c.wl_shm, c.wl_registry_bind(
registry,
name,
&c.wl_shm_interface,
version,
));
} else if (std.mem.eql(u8, interface_slice, xdg_wm_base_slice)) {
state.xdg_wm_base = @ptrCast(*c.xdg_wm_base, c.wl_registry_bind(
registry,
name,
&c.xdg_wm_base_interface,
version,
));
// TODO: See what happens if I put `null` here
_ = c.xdg_wm_base_add_listener(state.xdg_wm_base, &xdg_wm_base_listener, null);
}
}
fn registryHandleGlobalRemove(_: ?*c_void, _: ?*c.wl_registry, _: u32) callconv(.C) void {
// NOTE: Do nothing
}
const wl_registry_listener = c.wl_registry_listener{
.global = registryHandleGlobal,
.global_remove = registryHandleGlobalRemove,
};
pub fn main() anyerror!void {
var state = WaylandState{};
state.wl_display = c.wl_display_connect(null) orelse {
log.err("Unable to connect to Wayland display", .{});
std.os.exit(1);
};
state.wl_registry = c.wl_display_get_registry(state.wl_display);
_ = c.wl_registry_add_listener(state.wl_registry, &wl_registry_listener, &state);
_ = c.wl_display_roundtrip(state.wl_display);
if (state.wl_compositor) |_| {} else {
log.err("Unable to get wl_compositor", .{});
std.os.exit(1);
}
if (state.wl_shm) |_| {} else {
log.err("Unable to get wl_shm", .{});
std.os.exit(1);
}
if (state.xdg_wm_base) |_| {} else {
log.err("Unable to get xdg_wm_base", .{});
std.os.exit(1);
}
state.wl_surface = c.wl_compositor_create_surface(state.wl_compositor);
state.xdg_surface = c.xdg_wm_base_get_xdg_surface(state.xdg_wm_base, state.wl_surface);
_ = c.xdg_surface_add_listener(state.xdg_surface, &xdg_surface_listener, &state);
state.xdg_toplevel = c.xdg_surface_get_toplevel(state.xdg_surface);
c.xdg_toplevel_set_title(state.xdg_toplevel, program_name);
c.wl_surface_commit(state.wl_surface);
while (c.wl_display_dispatch(state.wl_display) != 0) {
// NOTE: Do nothing
}
c.wl_display_disconnect(state.wl_display);
} | src/main.zig |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.