diff --git a/TODO.txt b/TODO.txt new file mode 100644 index 0000000..4274638 --- /dev/null +++ b/TODO.txt @@ -0,0 +1,3 @@ +string formatting +Dynamic arrays +C-style arrays \ No newline at end of file diff --git a/bindings/generate.py b/bindings/generate.py deleted file mode 100755 index f2ce3c2..0000000 --- a/bindings/generate.py +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python3 - -import sys -import os -import clang.cindex -from clang.cindex import CursorKind, TypeKind, Type - - -def map_type(clang_type: Type): - canonical = clang_type.get_canonical() - kind = canonical.kind - spelling = ( - canonical.spelling.replace("const ", "") - .replace("volatile ", "") - .replace("restrict ", "") - .replace("struct ", "") - .replace("union ", "") - ) - - if kind == TypeKind.POINTER: - pointee = canonical.get_pointee() - if pointee.kind == TypeKind.RECORD: - decl = pointee.get_declaration() - if not decl.is_definition(): - return "^void" - - if pointee.kind == TypeKind.FUNCTIONPROTO: - arg_types = [] - - for arg in pointee.get_canonical().argument_types(): - arg_types.append(map_type(arg)) - - mapped_return = map_type(pointee.get_canonical().get_result()) - args_str = ", ".join(arg_types) - - return f"func({args_str}): {mapped_return}" - - return f"^{map_type(pointee)}" - - if kind == TypeKind.CONSTANTARRAY: - element_type = canonical.get_array_element_type() - size = canonical.get_array_size() - return f"[{size}]{map_type(element_type)}" - - if kind == TypeKind.INCOMPLETEARRAY: - element_type = canonical.get_array_element_type() - return f"[?]{map_type(element_type)}" - - if kind == TypeKind.FUNCTIONPROTO or kind == TypeKind.FUNCTIONNOPROTO: - arg_types = [] - - for arg in canonical.argument_types(): - arg_types.append(map_type(arg)) - - mapped_return = map_type(canonical.get_result()) - args_str = ", ".join(arg_types) - - return f"func({args_str}): {mapped_return}" - - if kind == TypeKind.VOID: - return "void" - - if kind == TypeKind.BOOL: - return "bool" - - if kind in [TypeKind.CHAR_S, TypeKind.SCHAR]: - return "i8" - if kind == TypeKind.CHAR_U or kind == TypeKind.UCHAR: - return "u8" - if kind == TypeKind.SHORT: - return "i16" - if kind == TypeKind.USHORT: - return "u16" - if kind == TypeKind.INT: - return "i32" - if kind == TypeKind.UINT: - return "u32" - if kind in [TypeKind.LONG, TypeKind.LONGLONG]: - return "i64" - if kind in [TypeKind.ULONG, TypeKind.ULONGLONG]: - return "u64" - - if kind == TypeKind.FLOAT: - return "f32" - if kind == TypeKind.DOUBLE or kind == TypeKind.LONGDOUBLE: - return "f64" - - if kind == TypeKind.RECORD: - return spelling - - raise Exception(f"Unresolved type: {spelling}") - - -if len(sys.argv) != 2: - print("Usage: python3 generate.py [path to header]", file=sys.stderr) - sys.exit(1) - -filename = sys.argv[1] - -index = clang.cindex.Index.create() - -tu = index.parse(filename, ["-x", "c", "-std=c23", "-I/usr/include"]) - -if tu.diagnostics: - for diag in tu.diagnostics: - if diag.severity >= clang.cindex.Diagnostic.Error: - print(f"Error: {diag.spelling}", file=sys.stderr) - -print(f'module "{os.path.basename(filename).split(".")[0]}"') -print() - -seen_structs = [] - -for cursor in tu.cursor.walk_preorder(): - if cursor.location.file and cursor.location.file.name != filename: - continue - - if cursor.kind == CursorKind.FUNCTION_DECL: - name = cursor.spelling - return_type = map_type(cursor.result_type) - - params = [] - for arg in cursor.get_arguments(): - param_name = arg.spelling - param_type = map_type(arg.type) - params.append(f"{param_name}: {param_type}") - - params_str = ", ".join(params) - - print(f'export extern "{name}" func {name}({params_str}): {return_type}') - - elif cursor.kind == CursorKind.STRUCT_DECL: - if cursor.get_usr() in seen_structs: - continue - - seen_structs.append(cursor.get_usr()) - - if cursor.is_definition(): - name = cursor.spelling - print(f"export struct {name}") - print("{") - for field in cursor.get_children(): - if field.kind == CursorKind.FIELD_DECL: - field_name = field.spelling - field_type = map_type(field.type) - print(f" {field_name}: {field_type}") - else: - raise Exception( - f"Unsupported child of struct: {field.spelling}: {field.kind}" - ) - print("}") - - elif cursor.kind == CursorKind.ENUM_DECL: - name = cursor.spelling - print(f"export enum {name} : u32") - print("{") - for field in cursor.get_children(): - if field.kind == CursorKind.ENUM_CONSTANT_DECL: - field_name = field.spelling - field_value = field.enum_value - print(f" {field_name} = {field_value}") - else: - raise Exception( - f"Unsupported child of enum: {field.spelling}: {field.kind}" - ) - print("}") diff --git a/compiler/.gitignore b/compiler/.gitignore index c6cc67a..0418d79 100644 --- a/compiler/.gitignore +++ b/compiler/.gitignore @@ -1,34 +1,4 @@ -# Common IntelliJ Platform excludes - -# User specific -**/.idea/**/workspace.xml -**/.idea/**/tasks.xml -**/.idea/shelf/* -**/.idea/dictionaries -**/.idea/httpRequests/ - -# Sensitive or high-churn files -**/.idea/**/dataSources/ -**/.idea/**/dataSources.ids -**/.idea/**/dataSources.xml -**/.idea/**/dataSources.local.xml -**/.idea/**/sqlDataSources.xml -**/.idea/**/dynamic.xml - -# Rider -# Rider auto-generates .iml files, and contentModel.xml -**/.idea/**/*.iml -**/.idea/**/contentModel.xml -**/.idea/**/modules.xml - -*.suo -*.user -.vs/ -[Bb]in/ -[Oo]bj/ -_UpgradeReport_Files/ -[Pp]ackages/ - -Thumbs.db -Desktop.ini -.DS_Store \ No newline at end of file +.idea +bin +obj +.build \ No newline at end of file diff --git a/compiler/.idea/.idea.Compiler/.idea/.gitignore b/compiler/.idea/.idea.Compiler/.idea/.gitignore deleted file mode 100644 index cda1cf4..0000000 --- a/compiler/.idea/.idea.Compiler/.idea/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Default ignored files -/shelf/ -/workspace.xml -# Rider ignored files -/modules.xml -/projectSettingsUpdater.xml -/contentModel.xml -/.idea.Compiler.iml -# Editor-based HTTP Client requests -/httpRequests/ -# Datasource local storage ignored files -/dataSources/ -/dataSources.local.xml diff --git a/compiler/.idea/.idea.Compiler/.idea/.name b/compiler/.idea/.idea.Compiler/.idea/.name deleted file mode 100644 index b92b7a3..0000000 --- a/compiler/.idea/.idea.Compiler/.idea/.name +++ /dev/null @@ -1 +0,0 @@ -Compiler \ No newline at end of file diff --git a/compiler/.idea/.idea.Compiler/.idea/encodings.xml b/compiler/.idea/.idea.Compiler/.idea/encodings.xml deleted file mode 100644 index df87cf9..0000000 --- a/compiler/.idea/.idea.Compiler/.idea/encodings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - \ No newline at end of file diff --git a/compiler/.idea/.idea.Compiler/.idea/indexLayout.xml b/compiler/.idea/.idea.Compiler/.idea/indexLayout.xml deleted file mode 100644 index 2135b43..0000000 --- a/compiler/.idea/.idea.Compiler/.idea/indexLayout.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - - Runtime - - - - - \ No newline at end of file diff --git a/compiler/.idea/.idea.Compiler/.idea/vcs.xml b/compiler/.idea/.idea.Compiler/.idea/vcs.xml deleted file mode 100644 index 6c0b863..0000000 --- a/compiler/.idea/.idea.Compiler/.idea/vcs.xml +++ /dev/null @@ -1,6 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/compiler/NubLang/NubLang.csproj b/compiler/Compiler.csproj similarity index 82% rename from compiler/NubLang/NubLang.csproj rename to compiler/Compiler.csproj index b682a68..85b4959 100644 --- a/compiler/NubLang/NubLang.csproj +++ b/compiler/Compiler.csproj @@ -1,10 +1,10 @@  + Exe net9.0 enable enable - true diff --git a/compiler/Compiler.sln b/compiler/Compiler.sln deleted file mode 100644 index 480156a..0000000 --- a/compiler/Compiler.sln +++ /dev/null @@ -1,28 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang", "NubLang\NubLang.csproj", "{5047E21F-590D-4CB3-AFF3-064316485009}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang.CLI", "NubLang.CLI\NubLang.CLI.csproj", "{A22F17ED-FA17-45AB-92BA-CD02C28B3524}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NubLang.LSP", "NubLang.LSP\NubLang.LSP.csproj", "{07968F84-0C2E-4D2E-8905-DC8A6140B4C0}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Release|Any CPU = Release|Any CPU - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {5047E21F-590D-4CB3-AFF3-064316485009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {5047E21F-590D-4CB3-AFF3-064316485009}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5047E21F-590D-4CB3-AFF3-064316485009}.Release|Any CPU.ActiveCfg = Release|Any CPU - {5047E21F-590D-4CB3-AFF3-064316485009}.Release|Any CPU.Build.0 = Release|Any CPU - {A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A22F17ED-FA17-45AB-92BA-CD02C28B3524}.Release|Any CPU.Build.0 = Release|Any CPU - {07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {07968F84-0C2E-4D2E-8905-DC8A6140B4C0}.Release|Any CPU.Build.0 = Release|Any CPU - EndGlobalSection -EndGlobal diff --git a/compiler/Diagnostic.cs b/compiler/Diagnostic.cs new file mode 100644 index 0000000..1d4b46e --- /dev/null +++ b/compiler/Diagnostic.cs @@ -0,0 +1,173 @@ +namespace Compiler; + +public class Diagnostic +{ + public static Builder Info(string message) => new Builder(DiagnosticSeverity.Info, message); + public static Builder Warning(string message) => new Builder(DiagnosticSeverity.Warning, message); + public static Builder Error(string message) => new Builder(DiagnosticSeverity.Error, message); + + private Diagnostic(DiagnosticSeverity severity, string message, string? help, FileInfo? file) + { + Severity = severity; + Message = message; + Help = help; + File = file; + } + + public class FileInfo(string file, int line, int column, int length) + { + public string File { get; } = file; + public int Line { get; } = line; + public int Column { get; } = column; + public int Length { get; } = length; + } + + public DiagnosticSeverity Severity { get; } + public string Message { get; } + public string? Help { get; } + public FileInfo? File { get; } + + public enum DiagnosticSeverity + { + Info, + Warning, + Error, + } + + public class Builder(DiagnosticSeverity severity, string message) + { + private FileInfo? file; + private string? help; + + public Builder At(string fileName, int line, int column, int length) + { + file = new FileInfo(fileName, line, column, length); + return this; + } + + public Builder At(string fileName, Token? token) + { + if (token != null) + { + At(fileName, token.Line, token.Column, token.Length); + } + + return this; + } + + public Builder At(string fileName, Node? node) + { + if (node != null && node.Tokens.Count != 0) + { + // todo(nub31): Calculate length based on last token + At(fileName, node.Tokens[0]); + } + + return this; + } + + public Builder At(string fileName, TypedNode? node) + { + if (node != null && node.Tokens.Count != 0) + { + // todo(nub31): Calculate length based on last token + At(fileName, node.Tokens[0]); + } + + return this; + } + + public Builder WithHelp(string helpMessage) + { + help = helpMessage; + return this; + } + + public Diagnostic Build() + { + return new Diagnostic(severity, message, help, file); + } + } +} + +public class CompileException(Diagnostic diagnostic) : Exception +{ + public Diagnostic Diagnostic { get; } = diagnostic; +} + +public static class DiagnosticFormatter +{ + public static void Print(Diagnostic diagnostic, TextWriter writer) + { + var (label, color) = diagnostic.Severity switch + { + Diagnostic.DiagnosticSeverity.Info => ("info", Ansi.Cyan), + Diagnostic.DiagnosticSeverity.Warning => ("warning", Ansi.Yellow), + Diagnostic.DiagnosticSeverity.Error => ("error", Ansi.Red), + _ => ("unknown", Ansi.Reset), + }; + + writer.Write(color); + writer.Write(label); + writer.Write(Ansi.Reset); + writer.Write(": "); + writer.WriteLine(diagnostic.Message); + + if (diagnostic.File is null) + return; + + var file = diagnostic.File; + var lineNumberWidth = diagnostic.File.Line.ToString().Length; + + writer.WriteLine($" {new string(' ', lineNumberWidth)}{file.File}:{file.Line}:{file.Column}"); + writer.WriteLine($"{new string(' ', lineNumberWidth)} | "); + + var sourceLine = TryReadLine(file.File, file.Line); + if (sourceLine != null) + { + writer.Write($"{file.Line.ToString().PadLeft(lineNumberWidth)} | "); + writer.WriteLine(sourceLine); + + writer.Write(new string(' ', lineNumberWidth)); + writer.Write(" | "); + writer.Write(new string(' ', file.Column - 1)); + writer.Write(color); + writer.Write(new string('^', Math.Max(1, file.Length))); + writer.WriteLine(Ansi.Reset); + } + + writer.WriteLine($"{new string(' ', lineNumberWidth)} |"); + + if (!string.IsNullOrWhiteSpace(diagnostic.Help)) + { + writer.WriteLine($" = help: {diagnostic.Help}"); + } + } + + private static string? TryReadLine(string file, int line) + { + try + { + using var reader = new StreamReader(file); + for (var i = 1; i < line; i++) + { + if (reader.ReadLine() == null) + return null; + } + + return reader.ReadLine(); + } + catch + { + return null; + } + } + + private static class Ansi + { + public const string Reset = "\e[0m"; + public const string Red = "\e[31m"; + public const string Yellow = "\e[33m"; + public const string Cyan = "\e[36m"; + } +} \ No newline at end of file diff --git a/compiler/Generator.cs b/compiler/Generator.cs new file mode 100644 index 0000000..61cd584 --- /dev/null +++ b/compiler/Generator.cs @@ -0,0 +1,1136 @@ +using System.Diagnostics; +using System.Text; + +namespace Compiler; + +public class Generator +{ + public static string Emit(List functions, ModuleGraph moduleGraph, string? entryPoint) + { + return new Generator(functions, moduleGraph, entryPoint).Emit(); + } + + private Generator(List functions, ModuleGraph moduleGraph, string? entryPoint) + { + this.functions = functions; + this.moduleGraph = moduleGraph; + this.entryPoint = entryPoint; + } + + const string NUB_H_CONTENTS = + """ + #include + #include + #include + #include + + static inline void *nub_alloc(size_t size) + { + void *mem = malloc(size); + if (mem == NULL) + { + puts("Out of memory"); + exit(1); + } + + return mem; + } + + typedef struct + { + char *data; + size_t length; + size_t ref; + uint32_t flags; + } string; + + typedef string *string_ptr; + + #define FLAG_STRING_LITERAL 1 + + static inline void string_rc_inc(string_ptr str) + { + if (str == NULL) + return; + + if (str->flags & FLAG_STRING_LITERAL) + return; + + str->ref += 1; + } + + static inline void string_rc_dec(string_ptr str) + { + if (str == NULL) + return; + + if (str->flags & FLAG_STRING_LITERAL) + return; + + if (str->ref == 0) + return; + + str->ref -= 1; + + if (str->ref == 0) + { + free(str->data); + free(str); + } + } + + static inline string_ptr string_concat(string_ptr left, string_ptr right) + { + size_t new_length = left->length + right->length; + + string_ptr result = (string_ptr)nub_alloc(sizeof(string)); + result->data = (char*)nub_alloc(new_length + 1); + + memcpy(result->data, left->data, left->length); + memcpy(result->data + left->length, right->data, right->length); + + result->data[new_length] = '\0'; + result->length = new_length; + result->ref = 1; + result->flags = 0; + + return result; + } + + static inline string_ptr string_from_cstr(char *cstr) + { + size_t len = strlen(cstr); + + string_ptr result = (string_ptr)nub_alloc(sizeof(string)); + result->data = (char*)nub_alloc(len + 1); + + memcpy(result->data, cstr, len + 1); + + result->length = len; + result->ref = 1; + result->flags = 0; + + return result; + } + + #define da_append(xs, x) \ + do \ + { \ + if ((xs)->count >= (xs)->capacity) \ + { \ + (xs)->capacity *= 2; \ + (xs)->items = realloc((xs)->items, (xs)->capacity * sizeof(*(xs)->items)); \ + } \ + (xs)->items[(xs)->count++] = (x); \ + } while (0) + + """; + + private readonly List functions; + private readonly ModuleGraph moduleGraph; + private readonly string? entryPoint; + private IndentedTextWriter writer = new(); + private readonly Dictionary referencedStringLiterals = []; + private readonly HashSet emittedTypes = []; + private readonly Stack scopes = new(); + private int tmpNameIndex = 0; + + private string Emit() + { + var outPath = ".build"; + var fileName = "out.c"; + + if (entryPoint != null) + { + writer.WriteLine("int main(int argc, char *argv[])"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine($"return {entryPoint}();"); + } + writer.WriteLine("}"); + writer.WriteLine(); + } + + foreach (var function in functions) + { + if (!moduleGraph.TryResolveIdentifier(function.Module, function.Name.Ident, true, out var info)) + throw new UnreachableException($"Module graph does not have info about the function {function.Module}::{function.Name.Ident}. This should have been caught earlier"); + + if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported) + writer.Write("static "); + + var parameters = function.Parameters.Select(x => $"{TypeName(x.Type)} {x.Name.Ident}"); + + writer.WriteLine($"{TypeName(function.ReturnType)} {info.MangledName}({string.Join(", ", parameters)})"); + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + EmitStatement(function.Body); + PopScope(); + } + writer.WriteLine("}"); + writer.WriteLine(); + } + + var definitions = writer.ToString(); + + writer = new IndentedTextWriter(); + + foreach (var module in moduleGraph.GetModules()) + { + foreach (var (name, info) in module.GetIdentifiers()) + { + if (info.Source == Module.DefinitionSource.Internal || info.Exported) + { + if (info.Source == Module.DefinitionSource.Imported || info.Extern) + writer.Write("extern "); + else if (info.Source == Module.DefinitionSource.Internal && !info.Extern && !info.Exported) + writer.Write("static "); + + if (info.Type is NubTypeFunc fn) + writer.WriteLine($"{TypeName(fn.ReturnType)} {info.MangledName}({string.Join(", ", fn.Parameters.Select(TypeName))});"); + else + writer.WriteLine($"{TypeName(info.Type)} {info.MangledName};"); + + writer.WriteLine(); + } + } + } + + foreach (var (name, value) in referencedStringLiterals) + { + writer.WriteLine + ( + $$""" + static string {{name}} = (string){ + .data = "{{value}}", + .length = {{Encoding.UTF8.GetByteCount(value)}}, + .ref = 0, + .flags = FLAG_STRING_LITERAL + }; + + """ + ); + } + + var declarations = writer.ToString(); + + writer = new IndentedTextWriter(); + + + while (emittedTypes.Count != typeNames.Count) + { + var nextTypes = typeNames.Keys.ToArray(); + foreach (var type in nextTypes) + { + EmitTypeDefinitionIfNotEmitted(type); + } + } + + var types = writer.ToString(); + + var sb = new StringBuilder(); + + sb.AppendLine("#include \"nub.h\""); + sb.AppendLine(); + sb.AppendLine(types); + sb.AppendLine(declarations); + sb.AppendLine(definitions); + + Directory.CreateDirectory(outPath); + + var filePath = Path.Combine(outPath, fileName); + + File.WriteAllText(Path.Combine(outPath, "nub.h"), NUB_H_CONTENTS); + File.WriteAllText(filePath, sb.ToString()); + + return filePath; + } + + private void EmitTypeDefinitionIfNotEmitted(NubType type) + { + if (emittedTypes.Contains(type)) + return; + + emittedTypes.Add(type); + + var name = TypeName(type); + + switch (type) + { + case NubTypeStruct structType: + { + if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo) + throw new UnreachableException(); + + foreach (var field in structInfo.Fields) + EmitTypeDefinitionIfNotEmitted(field.Type); + + if (structInfo.Packed) + writer.Write("__attribute__((__packed__)) "); + + writer.WriteLine("typedef struct"); + writer.WriteLine("{"); + using (writer.Indent()) + { + foreach (var field in structInfo.Fields) + { + writer.WriteLine($"{TypeName(field.Type)} {field.Name};"); + } + } + writer.WriteLine($"}} {name};"); + writer.WriteLine(); + + break; + } + case NubTypeAnonymousStruct anonymousStructType: + { + foreach (var field in anonymousStructType.Fields) + EmitTypeDefinitionIfNotEmitted(field.Type); + + writer.WriteLine("typedef struct"); + writer.WriteLine("{"); + using (writer.Indent()) + { + foreach (var field in anonymousStructType.Fields) + { + writer.WriteLine($"{TypeName(field.Type)} {field.Name};"); + } + } + writer.WriteLine($"}} {name};"); + writer.WriteLine(); + + break; + } + case NubTypeEnum enumType: + { + if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo) + throw new UnreachableException(); + + foreach (var variant in enumInfo.Variants) + { + if (variant.Type is not null) + { + EmitTypeDefinitionIfNotEmitted(variant.Type); + } + } + + writer.WriteLine("typedef struct"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine("uint32_t tag;"); + writer.WriteLine("union"); + writer.WriteLine("{"); + using (writer.Indent()) + { + foreach (var variant in enumInfo.Variants) + { + if (variant.Type is not null) + { + writer.WriteLine($"{TypeName(variant.Type)} {variant.Name};"); + } + } + } + writer.WriteLine("};"); + } + writer.WriteLine($"}} {name};"); + writer.WriteLine(); + + break; + } + case NubTypeEnumVariant variantType: + { + EmitTypeDefinitionIfNotEmitted(variantType.EnumType); + break; + } + case NubTypePointer pointerType: + { + EmitTypeDefinitionIfNotEmitted(pointerType.To); + writer.WriteLine($"typedef {TypeName(pointerType.To)} *{name};"); + break; + } + case NubTypeFunc funcType: + { + EmitTypeDefinitionIfNotEmitted(funcType.ReturnType); + foreach (var parameterType in funcType.Parameters) + EmitTypeDefinitionIfNotEmitted(parameterType); + + writer.WriteLine($"typedef {TypeName(funcType.ReturnType)} (*)({string.Join(", ", funcType.Parameters.Select(TypeName))}) {name};"); + + break; + } + case NubTypeArray arrayType: + { + EmitTypeDefinitionIfNotEmitted(arrayType.ElementType); + + var backingName = Tmp(); + + writer.WriteLine("typedef struct"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine("size_t count;"); + writer.WriteLine("size_t capacity;"); + writer.WriteLine($"{TypeName(arrayType.ElementType)} *items;"); + writer.WriteLine("uint32_t ref;"); + } + writer.WriteLine($"}} {backingName};"); + writer.WriteLine(); + + writer.WriteLine($"typedef {backingName} *{name};"); + writer.WriteLine(); + + writer.WriteLine($"static inline void {name}_rc_inc({name} array)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine("if (array == NULL) return;"); + writer.WriteLine("array->ref += 1;"); + } + writer.WriteLine("}"); + writer.WriteLine(); + + writer.WriteLine($"static inline void {name}_rc_dec({name} array)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine("if (array == NULL) return;"); + writer.WriteLine("if (array->ref == 0) return;"); + writer.WriteLine(); + writer.WriteLine("array->ref -= 1;"); + writer.WriteLine(); + writer.WriteLine("if (array->ref == 0)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine("for (size_t i = 0; i < array->count; ++i)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + EmitCopyDestructor("array->items[i]", arrayType.ElementType); + } + writer.WriteLine("}"); + writer.WriteLine(); + writer.WriteLine("free(array->items);"); + writer.WriteLine("free(array);"); + } + writer.WriteLine("}"); + } + writer.WriteLine("}"); + writer.WriteLine(); + + writer.WriteLine($"static inline {name} {name}_make()"); + writer.WriteLine("{"); + using (writer.Indent()) + { + writer.WriteLine($"{name} array = ({name})nub_alloc(sizeof({backingName}));"); + writer.WriteLine("array->ref = 1;"); + writer.WriteLine("array->count = 0;"); + writer.WriteLine("array->capacity = 10;"); + writer.WriteLine($"array->items = ({TypeName(arrayType.ElementType)}*)nub_alloc(sizeof({TypeName(arrayType.ElementType)}) * array->capacity);"); + writer.WriteLine("return array;"); + } + writer.WriteLine("}"); + writer.WriteLine(); + + break; + } + } + } + + private void EmitStatement(TypedNodeStatement node) + { + if (scopes.Peek().Unreachable) + return; + + switch (node) + { + case TypedNodeStatementBlock statement: + EmitStatementBlock(statement); + break; + case TypedNodeStatementFuncCall statement: + EmitStatementFuncCall(statement); + break; + case TypedNodeStatementReturn statement: + EmitStatementReturn(statement); + break; + case TypedNodeStatementVariableDeclaration statement: + EmitStatementVariableDeclaration(statement); + break; + case TypedNodeStatementAssignment statement: + EmitStatementAssignment(statement); + break; + case TypedNodeStatementIf statement: + EmitStatementIf(statement); + break; + case TypedNodeStatementWhile statement: + EmitStatementWhile(statement); + break; + case TypedNodeStatementFor statement: + EmitStatementFor(statement); + break; + case TypedNodeStatementMatch statement: + EmitStatementMatch(statement); + break; + default: + throw new ArgumentOutOfRangeException(nameof(node), node, null); + } + } + + private void EmitStatementBlock(TypedNodeStatementBlock node) + { + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + foreach (var statement in node.Statements) + EmitStatement(statement); + PopScope(); + } + writer.WriteLine("}"); + } + + private void EmitStatementFuncCall(TypedNodeStatementFuncCall node) + { + var name = EmitExpression(node.Target); + var parameterValues = node.Parameters.Select(EmitExpression).ToList(); + writer.WriteLine($"{name}({string.Join(", ", parameterValues)});"); + } + + private void EmitStatementReturn(TypedNodeStatementReturn statement) + { + if (statement.Value != null) + { + var value = EmitExpression(statement.Value); + EmitCleanupAllScopes(); + writer.WriteLine($"return {value};"); + } + else + { + EmitCleanupAllScopes(); + writer.WriteLine($"return;"); + } + + scopes.Peek().Unreachable = true; + } + + private void EmitStatementVariableDeclaration(TypedNodeStatementVariableDeclaration statement) + { + var value = EmitExpression(statement.Value); + EmitCopyConstructor(value, statement.Value.Type); + writer.WriteLine($"{TypeName(statement.Type)} {statement.Name.Ident} = {value};"); + scopes.Peek().DeconstructableNames.Add((statement.Name.Ident, statement.Type)); + } + + private void EmitStatementAssignment(TypedNodeStatementAssignment statement) + { + var target = EmitExpression(statement.Target); + EmitCopyDestructor(target, statement.Target.Type); + var value = EmitExpression(statement.Value); + EmitCopyConstructor(value, statement.Value.Type); + writer.WriteLine($"{target} = {value};"); + } + + private void EmitStatementIf(TypedNodeStatementIf statement) + { + var condition = EmitExpression(statement.Condition); + writer.WriteLine($"if ({condition})"); + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + EmitStatement(statement.ThenBlock); + PopScope(); + } + writer.WriteLine("}"); + + if (statement.ElseBlock != null) + { + writer.Write("else"); + if (statement.ElseBlock is TypedNodeStatementIf) + writer.Write(" "); + else + writer.WriteLine(); + + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + EmitStatement(statement.ElseBlock); + PopScope(); + } + writer.WriteLine("}"); + } + } + + private void EmitStatementWhile(TypedNodeStatementWhile statement) + { + var condition = EmitExpression(statement.Condition); + writer.WriteLine($"while ({condition})"); + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + EmitStatement(statement.Body); + PopScope(); + } + writer.WriteLine("}"); + } + + private void EmitStatementFor(TypedNodeStatementFor statement) + { + var index = Tmp(); + var array = EmitExpression(statement.Array); + writer.WriteLine($"for (size_t {index} = 0; {index} < {array}->count; ++{index})"); + writer.WriteLine("{"); + using (writer.Indent()) + { + var arrayType = (NubTypeArray)statement.Array.Type; + writer.WriteLine($"{TypeName(arrayType.ElementType)} {statement.VariableName.Ident} = {array}->items[{index}];"); + EmitStatement(statement.Body); + } + writer.WriteLine("}"); + } + + private void EmitStatementMatch(TypedNodeStatementMatch statement) + { + var target = EmitExpression(statement.Target); + var enumType = (NubTypeEnum)statement.Target.Type; + + if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info)) + throw new UnreachableException(); + + var enumInfo = (Module.TypeInfoEnum)info; + + writer.WriteLine($"switch ({target}.tag)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + foreach (var @case in statement.Cases) + { + var variantInfo = enumInfo.Variants.First(x => x.Name == @case.Variant.Ident); + var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == @case.Variant.Ident); + + writer.WriteLine($"case {tag}:"); + writer.WriteLine("{"); + using (writer.Indent()) + { + PushScope(); + if (@case.VariableName != null) + { + Debug.Assert(variantInfo.Type is not null); + writer.WriteLine($"{TypeName(variantInfo.Type)} {@case.VariableName.Ident} = {target}.{@case.Variant.Ident};"); + } + + EmitStatement(@case.Body); + PopScope(); + writer.WriteLine("break;"); + } + writer.WriteLine("}"); + } + } + writer.WriteLine("}"); + } + + private string EmitExpression(TypedNodeExpression node) + { + return node switch + { + TypedNodeExpressionBinary expression => EmitExpressionBinary(expression), + TypedNodeExpressionUnary expression => EmitExpressionUnary(expression), + TypedNodeExpressionBoolLiteral expression => expression.Value.Value ? "true" : "false", + TypedNodeExpressionIntLiteral expression => expression.Value.Value.ToString(), + TypedNodeExpressionStringLiteral expression => EmitExpressionStringLiteral(expression), + TypedNodeExpressionStructLiteral expression => EmitExpressionStructLiteral(expression), + TypedNodeExpressionEnumLiteral expression => EmitExpressionEnumLiteral(expression), + TypedNodeExpressionArrayLiteral expression => EmitNodeExpressionArrayLiteral(expression), + TypedNodeExpressionStringConstructor expression => EmitExpressionStringConstructor(expression), + TypedNodeExpressionStructMemberAccess expression => EmitExpressionMemberAccess(expression), + TypedNodeExpressionStringLength expression => EmitExpressionStringLength(expression), + TypedNodeExpressionStringPointer expression => EmitExpressionStringPointer(expression), + TypedNodeExpressionArrayCount expression => EmitExpressionArrayCount(expression), + TypedNodeExpressionArrayPointer expression => EmitExpressionArrayPointer(expression), + TypedNodeExpressionLocalIdent expression => expression.Name, + TypedNodeExpressionGlobalIdent expression => EmitNodeExpressionGlobalIdent(expression), + TypedNodeExpressionFuncCall expression => EmitExpressionFuncCall(expression), + _ => throw new ArgumentOutOfRangeException(nameof(node), node, null) + }; + } + + private string EmitExpressionBinary(TypedNodeExpressionBinary expression) + { + var left = EmitExpression(expression.Left); + var right = EmitExpression(expression.Right); + + var name = Tmp(); + + if (expression.Operation == TypedNodeExpressionBinary.Op.Add && expression.Left.Type is NubTypeString && expression.Right.Type is NubTypeString) + { + scopes.Peek().DeconstructableNames.Add((name, expression.Type)); + writer.WriteLine($"{TypeName(NubTypeString.Instance)} {name} = string_concat({left}, {right});"); + return name; + } + + var op = expression.Operation switch + { + TypedNodeExpressionBinary.Op.Add => $"({left} + {right})", + TypedNodeExpressionBinary.Op.Subtract => $"({left} - {right})", + TypedNodeExpressionBinary.Op.Multiply => $"({left} * {right})", + TypedNodeExpressionBinary.Op.Divide => $"({left} / {right})", + TypedNodeExpressionBinary.Op.Modulo => $"({left} % {right})", + TypedNodeExpressionBinary.Op.Equal => $"({left} == {right})", + TypedNodeExpressionBinary.Op.NotEqual => $"({left} != {right})", + TypedNodeExpressionBinary.Op.LessThan => $"({left} < {right})", + TypedNodeExpressionBinary.Op.LessThanOrEqual => $"({left} <= {right})", + TypedNodeExpressionBinary.Op.GreaterThan => $"({left} > {right})", + TypedNodeExpressionBinary.Op.GreaterThanOrEqual => $"({left} >= {right})", + TypedNodeExpressionBinary.Op.LeftShift => $"({left} << {right})", + TypedNodeExpressionBinary.Op.RightShift => $"({left} >> {right})", + TypedNodeExpressionBinary.Op.LogicalAnd => $"({left} && {right})", + TypedNodeExpressionBinary.Op.LogicalOr => $"({left} || {right})", + _ => throw new ArgumentOutOfRangeException() + }; + + writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};"); + + return name; + } + + private string EmitExpressionUnary(TypedNodeExpressionUnary expression) + { + var target = EmitExpression(expression.Target); + + var name = Tmp(); + + var op = expression.Operation switch + { + TypedNodeExpressionUnary.Op.Negate => $"(-{target})", + TypedNodeExpressionUnary.Op.Invert => $"(!{target})", + _ => throw new ArgumentOutOfRangeException() + }; + + writer.WriteLine($"{TypeName(expression.Type)} {name} = {op};"); + + return name; + } + + private string EmitExpressionStringLiteral(TypedNodeExpressionStringLiteral expression) + { + var name = Tmp(); + referencedStringLiterals.Add(name, expression.Value.Value); + return $"(&{name})"; + } + + private string EmitExpressionStructLiteral(TypedNodeExpressionStructLiteral expression) + { + var name = Tmp(); + scopes.Peek().DeconstructableNames.Add((name, expression.Type)); + + var initializerValues = new Dictionary(); + + foreach (var initializer in expression.Initializers) + { + var value = EmitExpression(initializer.Value); + EmitCopyConstructor(value, initializer.Value.Type); + initializerValues[initializer.Name.Ident] = value; + } + + var initializerStrings = initializerValues.Select(x => $".{x.Key} = {x.Value}"); + + writer.WriteLine($"{TypeName(expression.Type)} {name} = ({TypeName(expression.Type)}){{ {string.Join(", ", initializerStrings)} }};"); + + return name; + } + + private string EmitExpressionEnumLiteral(TypedNodeExpressionEnumLiteral expression) + { + var name = Tmp(); + scopes.Peek().DeconstructableNames.Add((name, expression.Type)); + + var enumVariantType = (NubTypeEnumVariant)expression.Type; + + if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info)) + throw new UnreachableException(); + + var enumInfo = (Module.TypeInfoEnum)info; + var tag = enumInfo.Variants.ToList().FindIndex(x => x.Name == enumVariantType.Variant); + + string? value = null; + if (expression.Value != null) + { + value = EmitExpression(expression.Value); + EmitCopyConstructor(value, expression.Value.Type); + } + + writer.Write($"{TypeName(expression.Type)} {name} = ({TypeName(expression.Type)}){{ .tag = {tag}"); + + if (value != null) + writer.WriteLine($", .{enumVariantType.Variant} = {value} }};"); + else + writer.WriteLine(" };"); + + return name; + } + + private string EmitNodeExpressionArrayLiteral(TypedNodeExpressionArrayLiteral expression) + { + var name = Tmp(); + scopes.Peek().DeconstructableNames.Add((name, expression.Type)); + + writer.WriteLine($"{TypeName(expression.Type)} {name} = {TypeName(expression.Type)}_make();"); + + foreach (var value in expression.Values) + { + var valueName = EmitExpression(value); + writer.WriteLine($"da_append({name}, {valueName});"); + } + + return name; + } + + private string EmitExpressionStringConstructor(TypedNodeExpressionStringConstructor expression) + { + var name = Tmp(); + scopes.Peek().DeconstructableNames.Add((name, expression.Type)); + var value = EmitExpression(expression.Value); + writer.WriteLine($"{TypeName(expression.Type)} {name} = string_from_cstr({value});"); + return name; + } + + private string EmitExpressionMemberAccess(TypedNodeExpressionStructMemberAccess expression) + { + var target = EmitExpression(expression.Target); + return $"{target}.{expression.Name.Ident}"; + } + + private string EmitExpressionStringLength(TypedNodeExpressionStringLength expression) + { + var target = EmitExpression(expression.Target); + return $"{target}->length"; + } + + private string EmitExpressionStringPointer(TypedNodeExpressionStringPointer expression) + { + var target = EmitExpression(expression.Target); + return $"{target}->data"; + } + + private string EmitExpressionArrayCount(TypedNodeExpressionArrayCount expression) + { + var target = EmitExpression(expression.Target); + return $"{target}->count"; + } + + private string EmitExpressionArrayPointer(TypedNodeExpressionArrayPointer expression) + { + var target = EmitExpression(expression.Target); + return $"{target}->items"; + } + + private string EmitNodeExpressionGlobalIdent(TypedNodeExpressionGlobalIdent expression) + { + if (!moduleGraph.TryResolveIdentifier(expression.Module, expression.Name, true, out var info)) + throw new UnreachableException($"Module graph does not have info about identifier {expression.Module}::{expression.Name}. This should have been caught earlier"); + + return info.MangledName; + } + + private string EmitExpressionFuncCall(TypedNodeExpressionFuncCall expression) + { + var name = EmitExpression(expression.Target); + var parameterValues = expression.Parameters.Select(EmitExpression).ToList(); + + var tmp = Tmp(); + writer.WriteLine($"{TypeName(expression.Type)} {tmp} = {name}({string.Join(", ", parameterValues)});"); + return tmp; + } + + private readonly Dictionary typeNames = []; + + private string TypeName(NubType type) + { + if (!typeNames.TryGetValue(type, out var name)) + { + name = type switch + { + NubTypeVoid => "void", + NubTypeBool => "bool", + NubTypeStruct => Tmp(), + NubTypeAnonymousStruct => Tmp(), + NubTypeEnum => Tmp(), + NubTypeEnumVariant t => TypeName(t.EnumType), + NubTypeSInt t => $"int{t.Width}_t", + NubTypeUInt t => $"uint{t.Width}_t", + NubTypePointer => Tmp(), + NubTypeString => "string_ptr", + NubTypeChar => "char", + NubTypeFunc => Tmp(), + NubTypeArray => Tmp(), + _ => throw new NotImplementedException(), + }; + + typeNames[type] = name; + } + + return name; + } + + private string Tmp() + { + return $"_tmp{tmpNameIndex++}"; + } + + private void EmitCleanupAllScopes() + { + foreach (var scope in scopes.Reverse()) + { + for (int i = scope.DeconstructableNames.Count - 1; i >= 0; i--) + { + var (name, type) = scope.DeconstructableNames[i]; + EmitCopyDestructor(name, type); + } + } + } + + private void EmitCleanupCurrentScope(Scope scope) + { + for (int i = scope.DeconstructableNames.Count - 1; i >= 0; i--) + { + var (name, type) = scope.DeconstructableNames[i]; + EmitCopyDestructor(name, type); + } + } + + private void EmitCopyConstructor(string value, NubType type) + { + switch (type) + { + case NubTypeArray arrayType: + { + writer.WriteLine($"{TypeName(type)}_rc_inc({value});"); + break; + } + case NubTypeString: + { + writer.WriteLine($"string_rc_inc({value});"); + break; + } + case NubTypeStruct structType: + { + if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo) + throw new UnreachableException(); + + foreach (var field in structInfo.Fields) + { + EmitCopyConstructor($"{value}.{field.Name}", field.Type); + } + break; + } + case NubTypeAnonymousStruct anonymousStructType: + { + foreach (var field in anonymousStructType.Fields) + { + EmitCopyConstructor($"{value}.{field.Name}", field.Type); + } + break; + } + case NubTypeEnum enumType: + { + if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo) + throw new UnreachableException(); + + writer.WriteLine($"switch ({value}.tag)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + for (int i = 0; i < enumInfo.Variants.Count; i++) + { + Module.TypeInfoEnum.Variant variant = enumInfo.Variants[i]; + + if (variant.Type is not null) + { + writer.WriteLine($"case {i}:"); + writer.WriteLine("{"); + using (writer.Indent()) + { + EmitCopyConstructor($"{value}.{variant.Name}", variant.Type); + writer.WriteLine("break;"); + } + writer.WriteLine("}"); + } + } + } + writer.WriteLine("}"); + break; + } + case NubTypeEnumVariant enumVariantType: + { + if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo) + throw new UnreachableException(); + + var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant); + if (variant.Type is not null) + EmitCopyConstructor($"{value}.{variant.Name}", variant.Type); + + break; + } + } + } + + private void EmitCopyDestructor(string value, NubType type) + { + switch (type) + { + case NubTypeArray arrayType: + { + writer.WriteLine($"{TypeName(type)}_rc_dec({value});"); + break; + } + case NubTypeString: + { + writer.WriteLine($"string_rc_dec({value});"); + break; + } + case NubTypeStruct structType: + { + if (!moduleGraph.TryResolveType(structType.Module, structType.Name, true, out var info) || info is not Module.TypeInfoStruct structInfo) + throw new UnreachableException(); + + foreach (var field in structInfo.Fields) + { + EmitCopyDestructor($"{value}.{field.Name}", field.Type); + } + break; + } + case NubTypeAnonymousStruct anonymousStructType: + { + foreach (var field in anonymousStructType.Fields) + { + EmitCopyDestructor($"{value}.{field.Name}", field.Type); + } + break; + } + case NubTypeEnum enumType: + { + if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo) + throw new UnreachableException(); + + writer.WriteLine($"switch ({value}.tag)"); + writer.WriteLine("{"); + using (writer.Indent()) + { + for (int i = 0; i < enumInfo.Variants.Count; i++) + { + var variant = enumInfo.Variants[i]; + if (variant.Type is not null) + { + writer.WriteLine($"case {i}:"); + writer.WriteLine("{"); + using (writer.Indent()) + { + EmitCopyDestructor($"{value}.{variant.Name}", variant.Type); + writer.WriteLine("break;"); + } + writer.WriteLine("}"); + } + } + } + writer.WriteLine("}"); + break; + } + case NubTypeEnumVariant enumVariantType: + { + if (!moduleGraph.TryResolveType(enumVariantType.EnumType.Module, enumVariantType.EnumType.Name, true, out var info) || info is not Module.TypeInfoEnum enumInfo) + throw new UnreachableException(); + + var variant = enumInfo.Variants.First(x => x.Name == enumVariantType.Variant); + if (variant.Type is not null) + EmitCopyDestructor($"{value}.{variant.Name}", variant.Type); + + break; + } + } + } + + private void PushScope() + { + scopes.Push(new Scope()); + } + + private void PopScope() + { + var scope = scopes.Pop(); + if (!scope.Unreachable) + EmitCleanupCurrentScope(scope); + } + + private class Scope + { + public List<(string Name, NubType Type)> DeconstructableNames { get; } = []; + public bool Unreachable { get; set; } + } +} + +internal class IndentedTextWriter +{ + private readonly StringBuilder builder = new(); + private int indentLevel; + + public IDisposable Indent() + { + indentLevel++; + return new IndentScope(this); + } + + public void WriteLine(string text) + { + WriteIndent(); + builder.AppendLine(text); + } + + public void Write(string text) + { + WriteIndent(); + builder.Append(text); + } + + public void WriteLine() + { + builder.AppendLine(); + } + + public override string ToString() + { + return builder.ToString(); + } + + private void WriteIndent() + { + if (builder.Length > 0) + { + var lastChar = builder[^1]; + if (lastChar != '\n' && lastChar != '\r') + return; + } + + for (var i = 0; i < indentLevel; i++) + { + builder.Append(" "); + } + } + + private class IndentScope(IndentedTextWriter writer) : IDisposable + { + private bool disposed; + + public void Dispose() + { + if (disposed) return; + writer.indentLevel--; + disposed = true; + } + } +} diff --git a/compiler/ModuleGraph.cs b/compiler/ModuleGraph.cs new file mode 100644 index 0000000..d09013d --- /dev/null +++ b/compiler/ModuleGraph.cs @@ -0,0 +1,446 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Compiler; + +public class ModuleGraph +{ + public static Builder CreateBuilder() => new(); + + private ModuleGraph(Dictionary modules) + { + this.modules = modules; + } + + private readonly Dictionary modules; + + public List GetModules() + { + return modules.Values.ToList(); + } + + public bool TryResolveIdentifier(string moduleName, string identifierName, bool searchPrivate, [NotNullWhen(true)] out Module.IdentifierInfo? info) + { + if (!TryResolveModule(moduleName, out var module)) + { + info = null; + return false; + } + + if (!module.TryResolveIdentifier(identifierName, searchPrivate, out info)) + return false; + + return true; + } + + public bool TryResolveType(string moduleName, string typeName, bool searchPrivate, [NotNullWhen(true)] out Module.TypeInfo? info) + { + if (!TryResolveModule(moduleName, out var module)) + { + info = null; + return false; + } + + if (!module.TryResolveType(typeName, searchPrivate, out info)) + return false; + + return true; + } + + public bool TryResolveModule(string moduleName, [NotNullWhen(true)] out Module? module) + { + module = modules.GetValueOrDefault(moduleName); + return module != null; + } + + public class Builder + { + private readonly List asts = []; + private readonly List manifests = []; + + public void AddAst(Ast ast) + { + asts.Add(ast); + } + + public void AddManifest(Manifest manifest) + { + manifests.Add(manifest); + } + + public ModuleGraph? Build(out List diagnostics) + { + diagnostics = []; + + var modules = new Dictionary(); + + foreach (var manifest in manifests) + { + foreach (var (moduleName, manifestModule) in manifest.Modules) + { + var module = GetOrCreateModule(moduleName); + + foreach (var (name, type) in manifestModule.Types) + { + switch (type) + { + case Manifest.Module.TypeInfoStruct s: + { + var info = new Module.TypeInfoStruct(Module.DefinitionSource.Imported, s.Exported, s.Packed); + var fields = s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList(); + info.SetFields(fields); + module.AddType(name, info); + break; + } + case Manifest.Module.TypeInfoEnum e: + { + var info = new Module.TypeInfoEnum(Module.DefinitionSource.Imported, e.Exported); + var variants = e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList(); + info.SetVariants(variants); + module.AddType(name, info); + break; + } + default: + throw new ArgumentOutOfRangeException(nameof(type)); + } + } + + foreach (var (name, identifier) in manifestModule.Identifiers) + { + module.AddIdentifier(name, new Module.IdentifierInfo(Module.DefinitionSource.Imported, identifier.Exported, identifier.Extern, identifier.Type, identifier.MangledName)); + } + } + } + + foreach (var ast in asts) + { + var module = GetOrCreateModule(ast.ModuleName.Ident); + + foreach (var structDef in ast.Definitions.OfType()) + { + module.AddType(structDef.Name.Ident, new Module.TypeInfoStruct(Module.DefinitionSource.Internal, structDef.Exported, structDef.Packed)); + } + + foreach (var enumDef in ast.Definitions.OfType()) + { + module.AddType(enumDef.Name.Ident, new Module.TypeInfoEnum(Module.DefinitionSource.Internal, enumDef.Exported)); + } + } + + foreach (var ast in asts) + { + var module = GetOrCreateModule(ast.ModuleName.Ident); + + foreach (var structDef in ast.Definitions.OfType()) + { + if (!module.TryResolveType(structDef.Name.Ident, true, out var typeInfo)) + throw new UnreachableException($"{nameof(typeInfo)} should always be registered"); + + if (typeInfo is Module.TypeInfoStruct structType) + { + var fields = structDef.Fields.Select(f => new Module.TypeInfoStruct.Field(f.Name.Ident, ResolveType(f.Type, module.Name))).ToList(); + structType.SetFields(fields); + } + } + + foreach (var enumDef in ast.Definitions.OfType()) + { + if (!module.TryResolveType(enumDef.Name.Ident, true, out var typeInfo)) + throw new UnreachableException($"{nameof(typeInfo)} should always be registered"); + + if (typeInfo is Module.TypeInfoEnum enumType) + { + var variants = enumDef.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name.Ident, v.Type == null ? null : ResolveType(v.Type, module.Name))).ToList(); + enumType.SetVariants(variants); + } + } + } + + foreach (var ast in asts) + { + var module = GetOrCreateModule(ast.ModuleName.Ident); + + foreach (var funcDef in ast.Definitions.OfType()) + { + var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList(); + var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name); + var funcType = NubTypeFunc.Get(parameters, returnType); + var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, false, funcType, NameMangler.Mangle(module.Name, funcDef.Name.Ident, funcType)); + module.AddIdentifier(funcDef.Name.Ident, info); + } + + foreach (var funcDef in ast.Definitions.OfType()) + { + var parameters = funcDef.Parameters.Select(x => ResolveType(x.Type, module.Name)).ToList(); + var returnType = funcDef.ReturnType == null ? NubTypeVoid.Instance : ResolveType(funcDef.ReturnType, module.Name); + var funcType = NubTypeFunc.Get(parameters, returnType); + var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, funcDef.Exported, true, funcType, funcDef.Name.Ident); + module.AddIdentifier(funcDef.Name.Ident, info); + } + + foreach (var globalVariable in ast.Definitions.OfType()) + { + var type = ResolveType(globalVariable.Type, module.Name); + var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, false, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type)); + module.AddIdentifier(globalVariable.Name.Ident, info); + } + + foreach (var globalVariable in ast.Definitions.OfType()) + { + var type = ResolveType(globalVariable.Type, module.Name); + var info = new Module.IdentifierInfo(Module.DefinitionSource.Internal, globalVariable.Exported, true, type, NameMangler.Mangle(module.Name, globalVariable.Name.Ident, type)); + module.AddIdentifier(globalVariable.Name.Ident, info); + } + } + + if (diagnostics.Any(x => x.Severity == Diagnostic.DiagnosticSeverity.Error)) + return null; + + return new ModuleGraph(modules); + + NubType ResolveType(NodeType node, string currentModule) + { + return node switch + { + NodeTypeBool => NubTypeBool.Instance, + NodeTypeNamed type => ResolveNamedType(type, currentModule), + NodeTypeAnonymousStruct type => NubTypeAnonymousStruct.Get(type.Fields.Select(x => new NubTypeAnonymousStruct.Field(x.Name.Ident, ResolveType(x.Type, currentModule))).ToList()), + NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(x => ResolveType(x, currentModule)).ToList(), ResolveType(type.ReturnType, currentModule)), + NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To, currentModule)), + NodeTypeSInt type => NubTypeSInt.Get(type.Width), + NodeTypeUInt type => NubTypeUInt.Get(type.Width), + NodeTypeString => NubTypeString.Instance, + NodeTypeChar => NubTypeChar.Instance, + NodeTypeVoid => NubTypeVoid.Instance, + NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType, currentModule)), + _ => throw new ArgumentOutOfRangeException(nameof(node)) + }; + } + + NubType ResolveNamedType(NodeTypeNamed type, string currentModule) + { + return type.Sections.Count switch + { + 3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2], currentModule), + 2 => ResolveTwoPartType(type.Sections[0], type.Sections[1], currentModule), + 1 => ResolveOnePartType(type.Sections[0], currentModule), + _ => throw BasicError("Invalid type name") + }; + } + + NubType ResolveThreePartType(TokenIdent first, TokenIdent second, TokenIdent third, string currentModule) + { + var module = ResolveModule(first); + if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo)) + throw BasicError($"Named type '{module.Name}::{second.Ident}' not found"); + + if (typeInfo is not Module.TypeInfoEnum enumInfo) + throw BasicError($"'{module.Name}::{second.Ident}' is not an enum"); + + var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == third.Ident); + if (variant == null) + throw BasicError($"Enum '{module.Name}::{second.Ident}' does not have a variant named '{third.Ident}'"); + + return NubTypeEnumVariant.Get(NubTypeEnum.Get(module.Name, second.Ident), third.Ident); + } + + NubType ResolveTwoPartType(TokenIdent first, TokenIdent second, string currentModule) + { + if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variant)) + return variant; + + var module = ResolveModule(first); + if (!module.TryResolveType(second.Ident, currentModule == module.Name, out var typeInfo)) + throw BasicError($"Named type '{module.Name}::{second.Ident}' not found"); + + return typeInfo switch + { + Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, second.Ident), + Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, second.Ident), + _ => throw new ArgumentOutOfRangeException(nameof(typeInfo)) + }; + } + + NubType ResolveOnePartType(TokenIdent name, string currentModule) + { + if (!modules.TryGetValue(currentModule, out var module)) + throw BasicError($"Module '{currentModule}' not found"); + + if (!module.TryResolveType(name.Ident, true, out var typeInfo)) + throw BasicError($"Named type '{module.Name}::{name.Ident}' not found"); + + return typeInfo switch + { + Module.TypeInfoStruct => NubTypeStruct.Get(module.Name, name.Ident), + Module.TypeInfoEnum => NubTypeEnum.Get(module.Name, name.Ident), + _ => throw new ArgumentOutOfRangeException(nameof(typeInfo)) + }; + } + + Module ResolveModule(TokenIdent name) + { + if (!modules.TryGetValue(name.Ident, out var module)) + throw BasicError($"Module '{name.Ident}' not found"); + + return module; + } + + bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result) + { + result = null; + + if (!modules.TryGetValue(moduleName, out var module)) + return false; + + if (!module.TryResolveType(enumName, true, out var typeInfo)) + return false; + + if (typeInfo is not Module.TypeInfoEnum enumInfo) + return false; + + var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName); + if (variant == null) + return false; + + result = NubTypeEnumVariant.Get( + NubTypeEnum.Get(moduleName, enumName), + variantName); + + return true; + } + + Exception BasicError(string message) + { + return new CompileException(Diagnostic.Error(message).Build()); + } + + Module GetOrCreateModule(string name) + { + if (!modules.TryGetValue(name, out var module)) + { + module = new Module(name); + modules.Add(name, module); + } + + return module; + } + } + } +} + +public class Module(string name) +{ + public string Name { get; } = name; + + private Dictionary types = new(); + private Dictionary identifiers = new(); + + public IReadOnlyDictionary GetTypes() => types; + public IReadOnlyDictionary GetIdentifiers() => identifiers; + + public bool TryResolveType(string name, bool searchPrivate, [NotNullWhen(true)] out TypeInfo? customType) + { + var info = types.GetValueOrDefault(name); + if (info == null) + { + customType = null; + return false; + } + + if (searchPrivate || info.Source == DefinitionSource.Internal) + { + customType = info; + return true; + } + + customType = null; + return false; + } + + public bool TryResolveIdentifier(string name, bool searchPrivate, [NotNullWhen(true)] out IdentifierInfo? identifierType) + { + var info = identifiers.GetValueOrDefault(name); + if (info == null) + { + identifierType = null; + return false; + } + + if (searchPrivate || info.Source == DefinitionSource.Internal) + { + identifierType = info; + return true; + } + + identifierType = null; + return false; + } + + public void AddType(string name, TypeInfo info) + { + types.Add(name, info); + } + + public void AddIdentifier(string name, IdentifierInfo info) + { + identifiers.Add(name, info); + } + + public enum DefinitionSource + { + Internal, + Imported, + } + + public class IdentifierInfo(DefinitionSource source, bool exported, bool @extern, NubType type, string mangledName) + { + public DefinitionSource Source { get; } = source; + public bool Exported { get; } = exported; + public bool Extern { get; } = @extern; + public NubType Type { get; } = type; + public string MangledName { get; } = mangledName; + } + + public abstract class TypeInfo(DefinitionSource source, bool exported) + { + public DefinitionSource Source { get; } = source; + public bool Exported { get; } = exported; + } + + public class TypeInfoStruct(DefinitionSource source, bool exported, bool packed) : TypeInfo(source, exported) + { + private IReadOnlyList? fields; + + public bool Packed { get; } = packed; + public IReadOnlyList Fields => fields ?? throw new InvalidOperationException("Fields has not been set yet"); + + public void SetFields(IReadOnlyList fields) + { + this.fields = fields; + } + + public class Field(string name, NubType type) + { + public string Name { get; } = name; + public NubType Type { get; } = type; + } + } + + public class TypeInfoEnum(DefinitionSource source, bool exported) : TypeInfo(source, exported) + { + private IReadOnlyList? variants; + + public IReadOnlyList Variants => variants ?? throw new InvalidOperationException("Fields has not been set yet"); + + public void SetVariants(IReadOnlyList variants) + { + this.variants = variants; + } + + public class Variant(string name, NubType? type) + { + public string Name { get; } = name; + public NubType? Type { get; } = type; + } + } +} diff --git a/compiler/NubLang.CLI/NubLang.CLI.csproj b/compiler/NubLang.CLI/NubLang.CLI.csproj deleted file mode 100644 index 0550d0f..0000000 --- a/compiler/NubLang.CLI/NubLang.CLI.csproj +++ /dev/null @@ -1,16 +0,0 @@ - - - - nubc - Exe - net9.0 - enable - enable - true - - - - - - - diff --git a/compiler/NubLang.CLI/Program.cs b/compiler/NubLang.CLI/Program.cs deleted file mode 100644 index fb51798..0000000 --- a/compiler/NubLang.CLI/Program.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System.Diagnostics; -using NubLang.Ast; -using NubLang.Diagnostics; -using NubLang.Generation; -using NubLang.Syntax; - -var diagnostics = new List(); -var syntaxTrees = new List(); - -foreach (var file in args) -{ - var tokenizer = new Tokenizer(file, File.ReadAllText(file)); - tokenizer.Tokenize(); - diagnostics.AddRange(tokenizer.Diagnostics); - - var parser = new Parser(); - var syntaxTree = parser.Parse(tokenizer.Tokens); - diagnostics.AddRange(parser.Diagnostics); - - syntaxTrees.Add(syntaxTree); -} - -var modules = Module.Collect(syntaxTrees); -var compilationUnits = new List(); - -for (var i = 0; i < args.Length; i++) -{ - var typeChecker = new TypeChecker(syntaxTrees[i], modules); - var compilationUnit = typeChecker.Check(); - - compilationUnits.Add(compilationUnit); - diagnostics.AddRange(typeChecker.Diagnostics); -} - -foreach (var diagnostic in diagnostics) -{ - Console.Error.WriteLine(diagnostic.FormatANSI()); -} - -if (diagnostics.Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) -{ - return 1; -} - -var cPaths = new List(); - -Directory.CreateDirectory(".build"); - -for (var i = 0; i < args.Length; i++) -{ - var file = args[i]; - var compilationUnit = compilationUnits[i]; - - var generator = new Generator(compilationUnit); - var directory = Path.GetDirectoryName(file); - if (!string.IsNullOrWhiteSpace(directory)) - { - Directory.CreateDirectory(Path.Combine(".build", directory)); - } - - var path = Path.Combine(".build", Path.ChangeExtension(file, "c")); - File.WriteAllText(path, generator.Emit()); - cPaths.Add(path); -} - -var objectPaths = new List(); - -foreach (var cPath in cPaths) -{ - var objectPath = Path.ChangeExtension(cPath, "o"); - using var compileProcess = Process.Start("clang", [ - "-ffreestanding", "-std=c23", - "-g", "-c", - "-o", objectPath, - cPath, - ]); - - compileProcess.WaitForExit(); - - if (compileProcess.ExitCode != 0) - { - Console.Error.WriteLine($"clang failed with exit code {compileProcess.ExitCode}"); - return 1; - } - - objectPaths.Add(objectPath); -} - -Console.Out.WriteLine(string.Join(' ', objectPaths)); - -return 0; \ No newline at end of file diff --git a/compiler/NubLang.LSP/AstExtensions.cs b/compiler/NubLang.LSP/AstExtensions.cs deleted file mode 100644 index e0b2477..0000000 --- a/compiler/NubLang.LSP/AstExtensions.cs +++ /dev/null @@ -1,77 +0,0 @@ -using NubLang.Ast; -using NubLang.Syntax; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; - -namespace NubLang.LSP; - -public static class AstExtensions -{ - public static Location ToLocation(this Node node) - { - if (node.Tokens.Count == 0) - { - return new Location(); - } - - return new Location - { - Uri = node.Tokens.First().Span.FilePath, - Range = new Range(node.Tokens.First().Span.Start.Line - 1, node.Tokens.First().Span.Start.Column - 1, node.Tokens.Last().Span.End.Line - 1, node.Tokens.Last().Span.End.Column - 1) - }; - } - - public static bool ContainsPosition(this Node node, int line, int character) - { - if (node.Tokens.Count == 0) - { - return false; - } - - var start = node.Tokens.First().Span.Start; - var end = node.Tokens.Last().Span.End; - - var startLine = start.Line - 1; - var startChar = start.Column - 1; - var endLine = end.Line - 1; - var endChar = end.Column - 1; - - if (line < startLine || line > endLine) return false; - - if (line > startLine && line < endLine) return true; - - if (startLine == endLine) - { - return character >= startChar && character <= endChar; - } - - if (line == startLine) - { - return character >= startChar; - } - - if (line == endLine) - { - return character <= endChar; - } - - return false; - } - - public static FuncNode? FunctionAtPosition(this CompilationUnit compilationUnit, int line, int character) - { - return compilationUnit - .Functions - .FirstOrDefault(x => x.ContainsPosition(line, character)); - } - - public static Node? DeepestNodeAtPosition(this CompilationUnit compilationUnit, int line, int character) - { - return compilationUnit.Functions - .SelectMany(x => x.DescendantsAndSelf()) - .Where(n => n.ContainsPosition(line, character)) - .OrderBy(n => n.Tokens.First().Span.Start.Line) - .ThenBy(n => n.Tokens.First().Span.Start.Column) - .LastOrDefault(); - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/CompletionHandler.cs b/compiler/NubLang.LSP/CompletionHandler.cs deleted file mode 100644 index 8155328..0000000 --- a/compiler/NubLang.LSP/CompletionHandler.cs +++ /dev/null @@ -1,180 +0,0 @@ -using NubLang.Ast; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; - -namespace NubLang.LSP; - -internal class CompletionHandler(WorkspaceManager workspaceManager) : CompletionHandlerBase -{ - private readonly CompletionItem[] _definitionSnippets = - [ - new() - { - Kind = CompletionItemKind.Keyword, - Label = "func", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "func ${1:name}(${2:params})\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "struct", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "struct ${1:name}\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "module", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "module \"$0\"", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "import", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "import \"$0\"", - } - ]; - - private readonly CompletionItem[] _statementSnippets = - [ - new() - { - Kind = CompletionItemKind.Keyword, - Label = "let", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "let ${1:name} = $0", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "if", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "if ${1:condition}\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "else if", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "else if ${1:condition}\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "else", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "else\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "while", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "while ${1:condition}\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "for", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "for ${1:name}, ${2:index} in ${3:array}\n{\n $0\n}", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "return", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "return $0", - }, - new() - { - Kind = CompletionItemKind.Keyword, - Label = "defer", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = "defer $0", - } - ]; - - protected override CompletionRegistrationOptions CreateRegistrationOptions(CompletionCapability capability, ClientCapabilities clientCapabilities) - { - return new CompletionRegistrationOptions(); - } - - public override Task Handle(CompletionParams request, CancellationToken cancellationToken) - { - return Task.FromResult(HandleSync(request, cancellationToken)); - } - - private CompletionList HandleSync(CompletionParams request, CancellationToken cancellationToken) - { - var completions = new List(); - var position = request.Position; - - var uri = request.TextDocument.Uri; - var compilationUnit = workspaceManager.GetCompilationUnit(uri); - if (compilationUnit != null) - { - var function = compilationUnit.Functions.FirstOrDefault(x => x.Body != null && x.Body.ContainsPosition(position.Line, position.Character)); - if (function != null) - { - completions.AddRange(_statementSnippets); - - foreach (var prototype in compilationUnit.ImportedFunctions) - { - var parameterStrings = new List(); - foreach (var (index, parameter) in prototype.Parameters.Index()) - { - parameterStrings.AddRange($"${{{index + 1}:{parameter.Name}}}"); - } - - completions.Add(new CompletionItem - { - Kind = CompletionItemKind.Function, - Label = $"{prototype.Module}::{prototype.Name}", - InsertTextFormat = InsertTextFormat.Snippet, - InsertText = $"{prototype.Module}::{prototype.Name}({string.Join(", ", parameterStrings)})", - }); - } - - foreach (var parameter in function.Prototype.Parameters) - { - completions.Add(new CompletionItem - { - Kind = CompletionItemKind.Variable, - Label = parameter.Name, - InsertText = parameter.Name, - }); - } - - var variables = function.Body! - .Descendants() - .OfType(); - - foreach (var variable in variables) - { - completions.Add(new CompletionItem - { - Kind = CompletionItemKind.Variable, - Label = variable.Name, - InsertText = variable.Name, - }); - } - } - else - { - completions.AddRange(_definitionSnippets); - } - } - - return new CompletionList(completions, false); - } - - public override Task Handle(CompletionItem request, CancellationToken cancellationToken) - { - return Task.FromResult(new CompletionItem()); - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/DefinitionHandler.cs b/compiler/NubLang.LSP/DefinitionHandler.cs deleted file mode 100644 index d354e9d..0000000 --- a/compiler/NubLang.LSP/DefinitionHandler.cs +++ /dev/null @@ -1,74 +0,0 @@ -using NubLang.Ast; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; - -namespace NubLang.LSP; - -internal class DefinitionHandler(WorkspaceManager workspaceManager) : DefinitionHandlerBase -{ - protected override DefinitionRegistrationOptions CreateRegistrationOptions(DefinitionCapability capability, ClientCapabilities clientCapabilities) - { - return new DefinitionRegistrationOptions(); - } - - public override Task Handle(DefinitionParams request, CancellationToken cancellationToken) - { - return Task.FromResult(HandleSync(request, cancellationToken)); - } - - private LocationOrLocationLinks? HandleSync(DefinitionParams request, CancellationToken cancellationToken) - { - var uri = request.TextDocument.Uri; - var compilationUnit = workspaceManager.GetCompilationUnit(uri); - if (compilationUnit == null) - { - return null; - } - - var line = request.Position.Line; - var character = request.Position.Character; - - var node = compilationUnit.DeepestNodeAtPosition(line, character); - - switch (node) - { - case VariableIdentifierNode variableIdentifierNode: - { - var function = compilationUnit.FunctionAtPosition(line, character); - - var parameter = function?.Prototype.Parameters.FirstOrDefault(x => x.Name == variableIdentifierNode.Name); - if (parameter != null) - { - return new LocationOrLocationLinks(parameter.ToLocation()); - } - - var variable = function?.Body? - .Descendants() - .OfType() - .FirstOrDefault(x => x.Name == variableIdentifierNode.Name); - - if (variable != null) - { - return new LocationOrLocationLinks(variable.ToLocation()); - } - - return null; - } - case FuncIdentifierNode funcIdentifierNode: - { - var prototype = compilationUnit.ImportedFunctions.FirstOrDefault(x => x.Module == funcIdentifierNode.Module && x.Name == funcIdentifierNode.Name); - if (prototype != null) - { - return new LocationOrLocationLinks(prototype.ToLocation()); - } - - return null; - } - default: - { - return null; - } - } - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/DiagnosticsPublisher.cs b/compiler/NubLang.LSP/DiagnosticsPublisher.cs deleted file mode 100644 index 7364396..0000000 --- a/compiler/NubLang.LSP/DiagnosticsPublisher.cs +++ /dev/null @@ -1,44 +0,0 @@ -using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; -using OmniSharp.Extensions.LanguageServer.Protocol.Server; -using Range = OmniSharp.Extensions.LanguageServer.Protocol.Models.Range; - -namespace NubLang.LSP; - -public class DiagnosticsPublisher -{ - private readonly ILanguageServerFacade _server; - - public DiagnosticsPublisher(ILanguageServerFacade server) - { - _server = server; - } - - public void Publish(DocumentUri uri, IEnumerable diagnostics) - { - _server.TextDocument.PublishDiagnostics(new PublishDiagnosticsParams - { - Uri = uri, - Diagnostics = new Container(diagnostics.Select(MapDiagnostic)) - }); - } - - private static Diagnostic MapDiagnostic(Diagnostics.Diagnostic nubDiagnostic) - { - return new Diagnostic - { - Severity = nubDiagnostic.Severity switch - { - Diagnostics.DiagnosticSeverity.Info => DiagnosticSeverity.Information, - Diagnostics.DiagnosticSeverity.Warning => DiagnosticSeverity.Warning, - Diagnostics.DiagnosticSeverity.Error => DiagnosticSeverity.Error, - _ => null - }, - Message = $"{nubDiagnostic.Message}\n{(nubDiagnostic.Help == null ? "" : $"help: {nubDiagnostic.Help}")}", - Range = nubDiagnostic.Span.HasValue - ? new Range(nubDiagnostic.Span.Value.Start.Line - 1, nubDiagnostic.Span.Value.Start.Column - 1, nubDiagnostic.Span.Value.End.Line - 1, nubDiagnostic.Span.Value.End.Column - 1) - : new Range(), - }; - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/HoverHandler.cs b/compiler/NubLang.LSP/HoverHandler.cs deleted file mode 100644 index f90e6c0..0000000 --- a/compiler/NubLang.LSP/HoverHandler.cs +++ /dev/null @@ -1,142 +0,0 @@ -using System.Globalization; -using NubLang.Ast; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; - -namespace NubLang.LSP; - -internal class HoverHandler(WorkspaceManager workspaceManager) : HoverHandlerBase -{ - protected override HoverRegistrationOptions CreateRegistrationOptions(HoverCapability capability, ClientCapabilities clientCapabilities) - { - return new HoverRegistrationOptions - { - DocumentSelector = TextDocumentSelector.ForLanguage("nub") - }; - } - - public override Task Handle(HoverParams request, CancellationToken cancellationToken) - { - return Task.FromResult(HandleSync(request, cancellationToken)); - } - - private Hover? HandleSync(HoverParams request, CancellationToken cancellationToken) - { - var compilationUnit = workspaceManager.GetCompilationUnit(request.TextDocument.Uri); - if (compilationUnit == null) - { - return null; - } - - var line = request.Position.Line; - var character = request.Position.Character; - - var hoveredNode = compilationUnit.DeepestNodeAtPosition(line, character); - - if (hoveredNode == null) - { - return null; - } - - var message = CreateMessage(hoveredNode, compilationUnit); - if (message == null) - { - return null; - } - - return new Hover - { - Contents = new MarkedStringsOrMarkupContent(new MarkupContent - { - Value = message, - Kind = MarkupKind.Markdown, - }) - }; - } - - private static string? CreateMessage(Node hoveredNode, CompilationUnit compilationUnit) - { - return hoveredNode switch - { - FuncNode funcNode => CreateFuncPrototypeMessage(funcNode.Prototype), - FuncPrototypeNode funcPrototypeNode => CreateFuncPrototypeMessage(funcPrototypeNode), - FuncIdentifierNode funcIdentifierNode => CreateFuncIdentifierMessage(funcIdentifierNode, compilationUnit), - FuncParameterNode funcParameterNode => CreateTypeNameMessage("Function parameter", funcParameterNode.Name, funcParameterNode.Type), - VariableIdentifierNode variableIdentifierNode => CreateTypeNameMessage("Variable", variableIdentifierNode.Name, variableIdentifierNode.Type), - VariableDeclarationNode variableDeclarationNode => CreateTypeNameMessage("Variable declaration", variableDeclarationNode.Name, variableDeclarationNode.Type), - StructFieldAccessNode structFieldAccessNode => CreateTypeNameMessage("Struct field", $"{structFieldAccessNode.Target.Type}.{structFieldAccessNode.Field}", structFieldAccessNode.Type), - CStringLiteralNode cStringLiteralNode => CreateLiteralMessage(cStringLiteralNode.Type, '"' + cStringLiteralNode.Value + '"'), - StringLiteralNode stringLiteralNode => CreateLiteralMessage(stringLiteralNode.Type, '"' + stringLiteralNode.Value + '"'), - BoolLiteralNode boolLiteralNode => CreateLiteralMessage(boolLiteralNode.Type, boolLiteralNode.Value.ToString()), - Float32LiteralNode float32LiteralNode => CreateLiteralMessage(float32LiteralNode.Type, float32LiteralNode.Value.ToString(CultureInfo.InvariantCulture)), - Float64LiteralNode float64LiteralNode => CreateLiteralMessage(float64LiteralNode.Type, float64LiteralNode.Value.ToString(CultureInfo.InvariantCulture)), - I8LiteralNode i8LiteralNode => CreateLiteralMessage(i8LiteralNode.Type, i8LiteralNode.Value.ToString()), - I16LiteralNode i16LiteralNode => CreateLiteralMessage(i16LiteralNode.Type, i16LiteralNode.Value.ToString()), - I32LiteralNode i32LiteralNode => CreateLiteralMessage(i32LiteralNode.Type, i32LiteralNode.Value.ToString()), - I64LiteralNode i64LiteralNode => CreateLiteralMessage(i64LiteralNode.Type, i64LiteralNode.Value.ToString()), - U8LiteralNode u8LiteralNode => CreateLiteralMessage(u8LiteralNode.Type, u8LiteralNode.Value.ToString()), - U16LiteralNode u16LiteralNode => CreateLiteralMessage(u16LiteralNode.Type, u16LiteralNode.Value.ToString()), - U32LiteralNode u32LiteralNode => CreateLiteralMessage(u32LiteralNode.Type, u32LiteralNode.Value.ToString()), - U64LiteralNode u64LiteralNode => CreateLiteralMessage(u64LiteralNode.Type, u64LiteralNode.Value.ToString()), - // Expressions can have a generic fallback showing the resulting type - ExpressionNode expressionNode => $""" - **Expression** `{expressionNode.GetType().Name}` - ```nub - {expressionNode.Type} - ``` - """, - BlockNode => null, - _ => hoveredNode.GetType().Name - }; - } - - private static string CreateLiteralMessage(NubType type, string value) - { - return $""" - **Literal** `{type}` - ```nub - {value}: {type} - ``` - """; - } - - private static string CreateTypeNameMessage(string description, string name, NubType type) - { - return $""" - **{description}** `{name}` - ```nub - {name}: {type} - ``` - """; - } - - private static string CreateFuncIdentifierMessage(FuncIdentifierNode funcIdentifierNode, CompilationUnit compilationUnit) - { - var func = compilationUnit.ImportedFunctions.FirstOrDefault(x => x.Module == funcIdentifierNode.Module && x.Name == funcIdentifierNode.Name); - if (func == null) - { - return $""" - **Function** `{funcIdentifierNode.Module}::{funcIdentifierNode.Name}` - ```nub - // Declaration not found - ``` - """; - } - - return CreateFuncPrototypeMessage(func); - } - - private static string CreateFuncPrototypeMessage(FuncPrototypeNode funcPrototypeNode) - { - var parameterText = string.Join(", ", funcPrototypeNode.Parameters.Select(x => $"{x.Name}: {x.Type}")); - var externText = funcPrototypeNode.ExternSymbol != null ? $"extern \"{funcPrototypeNode.ExternSymbol}\" " : ""; - - return $""" - **Function** `{funcPrototypeNode.Module}::{funcPrototypeNode.Name}` - ```nub - {externText}func {funcPrototypeNode.Module}::{funcPrototypeNode.Name}({parameterText}): {funcPrototypeNode.ReturnType} - ``` - """; - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/NubLang.LSP.csproj b/compiler/NubLang.LSP/NubLang.LSP.csproj deleted file mode 100644 index 720f388..0000000 --- a/compiler/NubLang.LSP/NubLang.LSP.csproj +++ /dev/null @@ -1,21 +0,0 @@ - - - - nublsp - Exe - net9.0 - enable - enable - true - true - - - - - - - - - - - diff --git a/compiler/NubLang.LSP/Program.cs b/compiler/NubLang.LSP/Program.cs deleted file mode 100644 index 095630f..0000000 --- a/compiler/NubLang.LSP/Program.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using NubLang.LSP; -using OmniSharp.Extensions.LanguageServer.Server; - -var server = await LanguageServer.From(options => options - .WithInput(Console.OpenStandardInput()) - .WithOutput(Console.OpenStandardOutput()) - .WithServices(services => - { - services.AddSingleton(); - services.AddSingleton(); - }) - .ConfigureLogging(x => x - .AddLanguageProtocolLogging() - .SetMinimumLevel(LogLevel.Debug)) - .WithHandler() - .WithHandler() - .WithHandler() - .WithHandler() - .OnInitialize((server, request, ct) => - { - var workspaceManager = server.GetRequiredService(); - - if (request.RootPath != null) - { - workspaceManager.Init(request.RootPath); - } - - return Task.CompletedTask; - }) -); - -await server.WaitForExit; \ No newline at end of file diff --git a/compiler/NubLang.LSP/TextDocumentSyncHandler.cs b/compiler/NubLang.LSP/TextDocumentSyncHandler.cs deleted file mode 100644 index e29aa44..0000000 --- a/compiler/NubLang.LSP/TextDocumentSyncHandler.cs +++ /dev/null @@ -1,44 +0,0 @@ -using MediatR; -using OmniSharp.Extensions.LanguageServer.Protocol; -using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; -using OmniSharp.Extensions.LanguageServer.Protocol.Document; -using OmniSharp.Extensions.LanguageServer.Protocol.Models; - -namespace NubLang.LSP; - -internal class TextDocumentSyncHandler(WorkspaceManager workspaceManager) : TextDocumentSyncHandlerBase -{ - public override TextDocumentAttributes GetTextDocumentAttributes(DocumentUri uri) - { - return new TextDocumentAttributes(uri, "nub"); - } - - public override Task Handle(DidOpenTextDocumentParams request, CancellationToken cancellationToken) - { - workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath()); - return Unit.Task; - } - - public override Task Handle(DidChangeTextDocumentParams request, CancellationToken cancellationToken) - { - workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath()); - return Unit.Task; - } - - public override Task Handle(DidSaveTextDocumentParams request, CancellationToken cancellationToken) - { - workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath()); - return Unit.Task; - } - - public override Task Handle(DidCloseTextDocumentParams request, CancellationToken cancellationToken) - { - workspaceManager.UpdateFile(request.TextDocument.Uri.GetFileSystemPath()); - return Unit.Task; - } - - protected override TextDocumentSyncRegistrationOptions CreateRegistrationOptions(TextSynchronizationCapability capability, ClientCapabilities clientCapabilities) - { - return new TextDocumentSyncRegistrationOptions(); - } -} \ No newline at end of file diff --git a/compiler/NubLang.LSP/WorkspaceManager.cs b/compiler/NubLang.LSP/WorkspaceManager.cs deleted file mode 100644 index a897e13..0000000 --- a/compiler/NubLang.LSP/WorkspaceManager.cs +++ /dev/null @@ -1,74 +0,0 @@ -using NubLang.Ast; -using NubLang.Syntax; -using OmniSharp.Extensions.LanguageServer.Protocol; - -namespace NubLang.LSP; - -public class WorkspaceManager(DiagnosticsPublisher diagnosticsPublisher) -{ - private readonly Dictionary _syntaxTrees = new(); - private readonly Dictionary _compilationUnits = new(); - - public void Init(string rootPath) - { - var files = Directory.GetFiles(rootPath, "*.nub", SearchOption.AllDirectories); - foreach (var path in files) - { - var text = File.ReadAllText(path); - var tokenizer = new Tokenizer(path, text); - - tokenizer.Tokenize(); - diagnosticsPublisher.Publish(path, tokenizer.Diagnostics); - - var parser = new Parser(); - var parseResult = parser.Parse(tokenizer.Tokens); - diagnosticsPublisher.Publish(path, parser.Diagnostics); - - _syntaxTrees[path] = parseResult; - } - - foreach (var (fsPath, syntaxTree) in _syntaxTrees) - { - var modules = Module.Collect(_syntaxTrees.Select(x => x.Value).ToList()); - - var typeChecker = new TypeChecker(syntaxTree, modules); - var result = typeChecker.Check(); - diagnosticsPublisher.Publish(fsPath, typeChecker.Diagnostics); - _compilationUnits[fsPath] = result; - } - } - - public void UpdateFile(DocumentUri path) - { - var fsPath = path.GetFileSystemPath(); - - var text = File.ReadAllText(fsPath); - var tokenizer = new Tokenizer(fsPath, text); - tokenizer.Tokenize(); - diagnosticsPublisher.Publish(path, tokenizer.Diagnostics); - - var parser = new Parser(); - var syntaxTree = parser.Parse(tokenizer.Tokens); - diagnosticsPublisher.Publish(path, parser.Diagnostics); - _syntaxTrees[fsPath] = syntaxTree; - - var modules = Module.Collect(_syntaxTrees.Select(x => x.Value).ToList()); - - var typeChecker = new TypeChecker(syntaxTree, modules); - var result = typeChecker.Check(); - diagnosticsPublisher.Publish(fsPath, typeChecker.Diagnostics); - _compilationUnits[fsPath] = result; - } - - public void RemoveFile(DocumentUri path) - { - var fsPath = path.GetFileSystemPath(); - _syntaxTrees.Remove(fsPath); - _compilationUnits.Remove(fsPath); - } - - public CompilationUnit? GetCompilationUnit(DocumentUri path) - { - return _compilationUnits.GetValueOrDefault(path.GetFileSystemPath()); - } -} \ No newline at end of file diff --git a/compiler/NubLang/Ast/CompilationUnit.cs b/compiler/NubLang/Ast/CompilationUnit.cs deleted file mode 100644 index f2115c1..0000000 --- a/compiler/NubLang/Ast/CompilationUnit.cs +++ /dev/null @@ -1,15 +0,0 @@ -namespace NubLang.Ast; - -public sealed class CompilationUnit -{ - public CompilationUnit(List functions, List importedStructTypes, List importedFunctions) - { - Functions = functions; - ImportedStructTypes = importedStructTypes; - ImportedFunctions = importedFunctions; - } - - public List Functions { get; } - public List ImportedStructTypes { get; } - public List ImportedFunctions { get; } -} \ No newline at end of file diff --git a/compiler/NubLang/Ast/Node.cs b/compiler/NubLang/Ast/Node.cs deleted file mode 100644 index aca79fd..0000000 --- a/compiler/NubLang/Ast/Node.cs +++ /dev/null @@ -1,590 +0,0 @@ -using NubLang.Syntax; - -namespace NubLang.Ast; - -public abstract class Node(List tokens) -{ - public List Tokens { get; } = tokens; - - public abstract IEnumerable Children(); - - public IEnumerable Descendants() - { - foreach (var child in Children()) - { - foreach (var descendant in child.DescendantsAndSelf()) - { - yield return descendant; - } - } - } - - public IEnumerable DescendantsAndSelf() - { - yield return this; - foreach (var descendant in Descendants()) - { - yield return descendant; - } - } -} - -#region Definitions - -public abstract class DefinitionNode(List tokens, string module, string name) : Node(tokens) -{ - public string Module { get; } = module; - public string Name { get; } = name; -} - -public class FuncParameterNode(List tokens, string name, NubType type) : Node(tokens) -{ - public string Name { get; } = name; - public NubType Type { get; } = type; - - public override IEnumerable Children() - { - return []; - } -} - -public class FuncPrototypeNode(List tokens, string module, string name, string? externSymbol, List parameters, NubType returnType) : Node(tokens) -{ - public string Module { get; } = module; - public string Name { get; } = name; - public string? ExternSymbol { get; } = externSymbol; - public List Parameters { get; } = parameters; - public NubType ReturnType { get; } = returnType; - - public override IEnumerable Children() - { - return Parameters; - } -} - -public class FuncNode(List tokens, FuncPrototypeNode prototype, BlockNode? body) : DefinitionNode(tokens, prototype.Module, prototype.Name) -{ - public FuncPrototypeNode Prototype { get; } = prototype; - public BlockNode? Body { get; } = body; - - public override IEnumerable Children() - { - yield return Prototype; - if (Body != null) - { - yield return Body; - } - } -} - -#endregion - -#region Statements - -public abstract class StatementNode(List tokens) : Node(tokens); - -public abstract class TerminalStatementNode(List tokens) : StatementNode(tokens); - -public class BlockNode(List tokens, List statements) : StatementNode(tokens) -{ - public List Statements { get; } = statements; - - public override IEnumerable Children() - { - return Statements; - } -} - -public class StatementFuncCallNode(List tokens, FuncCallNode funcCall) : StatementNode(tokens) -{ - public FuncCallNode FuncCall { get; } = funcCall; - - public override IEnumerable Children() - { - yield return FuncCall; - } -} - -public class ReturnNode(List tokens, ExpressionNode? value) : TerminalStatementNode(tokens) -{ - public ExpressionNode? Value { get; } = value; - - public override IEnumerable Children() - { - if (Value != null) yield return Value; - } -} - -public class AssignmentNode(List tokens, LValueExpressionNode target, ExpressionNode value) : StatementNode(tokens) -{ - public LValueExpressionNode Target { get; } = target; - public ExpressionNode Value { get; } = value; - - public override IEnumerable Children() - { - yield return Target; - yield return Value; - } -} - -public class IfNode(List tokens, ExpressionNode condition, BlockNode body, Variant? @else) : StatementNode(tokens) -{ - public ExpressionNode Condition { get; } = condition; - public BlockNode Body { get; } = body; - public Variant? Else { get; } = @else; - - public override IEnumerable Children() - { - yield return Condition; - yield return Body; - if (Else.HasValue) - { - yield return Else.Value.Match(x => x, x => x); - } - } -} - -public class VariableDeclarationNode(List tokens, string name, ExpressionNode? assignment, NubType type) : StatementNode(tokens) -{ - public string Name { get; } = name; - public ExpressionNode? Assignment { get; } = assignment; - public NubType Type { get; } = type; - - public override IEnumerable Children() - { - if (Assignment != null) yield return Assignment; - } -} - -public class ContinueNode(List tokens) : TerminalStatementNode(tokens) -{ - public override IEnumerable Children() - { - return []; - } -} - -public class BreakNode(List tokens) : TerminalStatementNode(tokens) -{ - public override IEnumerable Children() - { - return []; - } -} - -public class WhileNode(List tokens, ExpressionNode condition, BlockNode body) : StatementNode(tokens) -{ - public ExpressionNode Condition { get; } = condition; - public BlockNode Body { get; } = body; - - public override IEnumerable Children() - { - yield return Condition; - yield return Body; - } -} - -public class ForSliceNode(List tokens, string elementName, string? indexName, ExpressionNode target, BlockNode body) : StatementNode(tokens) -{ - public string ElementName { get; } = elementName; - public string? IndexName { get; } = indexName; - public ExpressionNode Target { get; } = target; - public BlockNode Body { get; } = body; - - public override IEnumerable Children() - { - yield return Target; - yield return Body; - } -} - -public class ForConstArrayNode(List tokens, string elementName, string? indexName, ExpressionNode target, BlockNode body) : StatementNode(tokens) -{ - public string ElementName { get; } = elementName; - public string? IndexName { get; } = indexName; - public ExpressionNode Target { get; } = target; - public BlockNode Body { get; } = body; - - public override IEnumerable Children() - { - yield return Target; - yield return Body; - } -} - -public class DeferNode(List tokens, StatementNode statement) : StatementNode(tokens) -{ - public StatementNode Statement { get; } = statement; - - public override IEnumerable Children() - { - yield return Statement; - } -} - -#endregion - -#region Expressions - -public enum UnaryOperator -{ - Negate, - Invert -} - -public enum BinaryOperator -{ - Equal, - NotEqual, - GreaterThan, - GreaterThanOrEqual, - LessThan, - LessThanOrEqual, - LogicalAnd, - LogicalOr, - Plus, - Minus, - Multiply, - Divide, - Modulo, - LeftShift, - RightShift, - BitwiseAnd, - BitwiseXor, - BitwiseOr -} - -public abstract class ExpressionNode(List tokens, NubType type) : Node(tokens) -{ - public NubType Type { get; } = type; -} - -public abstract class LValueExpressionNode(List tokens, NubType type) : ExpressionNode(tokens, type); - -public abstract class RValueExpressionNode(List tokens, NubType type) : ExpressionNode(tokens, type); - -public abstract class IntermediateExpression(List tokens) : ExpressionNode(tokens, new NubVoidType()); - -public class StringLiteralNode(List tokens, string value) : RValueExpressionNode(tokens, new NubStringType()) -{ - public string Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class CStringLiteralNode(List tokens, string value) : RValueExpressionNode(tokens, new NubPointerType(new NubIntType(true, 8))) -{ - public string Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class I8LiteralNode(List tokens, sbyte value) : RValueExpressionNode(tokens, new NubIntType(true, 8)) -{ - public sbyte Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class I16LiteralNode(List tokens, short value) : RValueExpressionNode(tokens, new NubIntType(true, 16)) -{ - public short Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class I32LiteralNode(List tokens, int value) : RValueExpressionNode(tokens, new NubIntType(true, 32)) -{ - public int Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class I64LiteralNode(List tokens, long value) : RValueExpressionNode(tokens, new NubIntType(true, 64)) -{ - public long Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class U8LiteralNode(List tokens, byte value) : RValueExpressionNode(tokens, new NubIntType(false, 8)) -{ - public byte Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class U16LiteralNode(List tokens, ushort value) : RValueExpressionNode(tokens, new NubIntType(false, 16)) -{ - public ushort Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class U32LiteralNode(List tokens, uint value) : RValueExpressionNode(tokens, new NubIntType(false, 32)) -{ - public uint Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class U64LiteralNode(List tokens, ulong value) : RValueExpressionNode(tokens, new NubIntType(false, 64)) -{ - public ulong Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class Float32LiteralNode(List tokens, float value) : RValueExpressionNode(tokens, new NubFloatType(32)) -{ - public float Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class Float64LiteralNode(List tokens, double value) : RValueExpressionNode(tokens, new NubFloatType(64)) -{ - public double Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class BoolLiteralNode(List tokens, NubType type, bool value) : RValueExpressionNode(tokens, type) -{ - public bool Value { get; } = value; - - public override IEnumerable Children() - { - return []; - } -} - -public class BinaryExpressionNode(List tokens, NubType type, ExpressionNode left, BinaryOperator @operator, ExpressionNode right) : RValueExpressionNode(tokens, type) -{ - public ExpressionNode Left { get; } = left; - public BinaryOperator Operator { get; } = @operator; - public ExpressionNode Right { get; } = right; - - public override IEnumerable Children() - { - yield return Left; - yield return Right; - } -} - -public class UnaryExpressionNode(List tokens, NubType type, UnaryOperator @operator, ExpressionNode operand) : RValueExpressionNode(tokens, type) -{ - public UnaryOperator Operator { get; } = @operator; - public ExpressionNode Operand { get; } = operand; - - public override IEnumerable Children() - { - yield return Operand; - } -} - -public class FuncCallNode(List tokens, NubType type, ExpressionNode expression, List parameters) : RValueExpressionNode(tokens, type) -{ - public ExpressionNode Expression { get; } = expression; - public List Parameters { get; } = parameters; - - public override IEnumerable Children() - { - yield return Expression; - foreach (var expressionNode in Parameters) - { - yield return expressionNode; - } - } -} - -public class VariableIdentifierNode(List tokens, NubType type, string name) : LValueExpressionNode(tokens, type) -{ - public string Name { get; } = name; - - public override IEnumerable Children() - { - return []; - } -} - -public class FuncIdentifierNode(List tokens, NubType type, string module, string name, string? externSymbol) : RValueExpressionNode(tokens, type) -{ - public string Module { get; } = module; - public string Name { get; } = name; - public string? ExternSymbol { get; } = externSymbol; - - public override IEnumerable Children() - { - return []; - } -} - -public class ArrayInitializerNode(List tokens, NubType type, List values) : RValueExpressionNode(tokens, type) -{ - public List Values { get; } = values; - - public override IEnumerable Children() - { - return Values; - } -} - -public class ConstArrayInitializerNode(List tokens, NubType type, List values) : RValueExpressionNode(tokens, type) -{ - public List Values { get; } = values; - - public override IEnumerable Children() - { - return Values; - } -} - -public class ArrayIndexAccessNode(List tokens, NubType type, ExpressionNode target, ExpressionNode index) : LValueExpressionNode(tokens, type) -{ - public ExpressionNode Target { get; } = target; - public ExpressionNode Index { get; } = index; - - public override IEnumerable Children() - { - yield return Target; - yield return Index; - } -} - -public class ConstArrayIndexAccessNode(List tokens, NubType type, ExpressionNode target, ExpressionNode index) : LValueExpressionNode(tokens, type) -{ - public ExpressionNode Target { get; } = target; - public ExpressionNode Index { get; } = index; - - public override IEnumerable Children() - { - yield return Target; - yield return Index; - } -} - -public class SliceIndexAccessNode(List tokens, NubType type, ExpressionNode target, ExpressionNode index) : LValueExpressionNode(tokens, type) -{ - public ExpressionNode Target { get; } = target; - public ExpressionNode Index { get; } = index; - - public override IEnumerable Children() - { - yield return Target; - yield return Index; - } -} - -public class AddressOfNode(List tokens, NubType type, LValueExpressionNode lValue) : RValueExpressionNode(tokens, type) -{ - public LValueExpressionNode LValue { get; } = lValue; - - public override IEnumerable Children() - { - yield return LValue; - } -} - -public class StructFieldAccessNode(List tokens, NubType type, ExpressionNode target, string field) : LValueExpressionNode(tokens, type) -{ - public ExpressionNode Target { get; } = target; - public string Field { get; } = field; - - public override IEnumerable Children() - { - yield return Target; - } -} - -public class StructInitializerNode(List tokens, NubType type, Dictionary initializers) : RValueExpressionNode(tokens, type) -{ - public Dictionary Initializers { get; } = initializers; - - public override IEnumerable Children() - { - foreach (var initializer in Initializers) - { - yield return initializer.Value; - } - } -} - -public class DereferenceNode(List tokens, NubType type, ExpressionNode target) : LValueExpressionNode(tokens, type) -{ - public ExpressionNode Target { get; } = target; - - public override IEnumerable Children() - { - yield return Target; - } -} - -public class SizeNode(List tokens, NubType TargetType) : RValueExpressionNode(tokens, new NubIntType(false, 64)) -{ - public NubType TargetType { get; } = TargetType; - - public override IEnumerable Children() - { - return []; - } -} - -public class CastNode(List tokens, NubType type, ExpressionNode value) : RValueExpressionNode(tokens, type) -{ - public ExpressionNode Value { get; } = value; - - public override IEnumerable Children() - { - yield return Value; - } -} - -public class EnumReferenceIntermediateNode(List tokens, string module, string name) : IntermediateExpression(tokens) -{ - public string Module { get; } = module; - public string Name { get; } = name; - - public override IEnumerable Children() - { - return []; - } -} - -#endregion \ No newline at end of file diff --git a/compiler/NubLang/Ast/NubType.cs b/compiler/NubLang/Ast/NubType.cs deleted file mode 100644 index ef0981b..0000000 --- a/compiler/NubLang/Ast/NubType.cs +++ /dev/null @@ -1,165 +0,0 @@ -using System.Security.Cryptography; -using System.Text; - -namespace NubLang.Ast; - -public abstract class NubType : IEquatable -{ - public override bool Equals(object? obj) => obj is NubType other && Equals(other); - public abstract bool Equals(NubType? other); - - public abstract override int GetHashCode(); - public abstract override string ToString(); - - public static bool operator ==(NubType? left, NubType? right) => Equals(left, right); - public static bool operator !=(NubType? left, NubType? right) => !Equals(left, right); -} - -public class NubVoidType : NubType -{ - public override string ToString() => "void"; - public override bool Equals(NubType? other) => other is NubVoidType; - public override int GetHashCode() => HashCode.Combine(typeof(NubVoidType)); -} - -public sealed class NubIntType(bool signed, int width) : NubType -{ - public bool Signed { get; } = signed; - public int Width { get; } = width; - - public override string ToString() => $"{(Signed ? "i" : "u")}{Width}"; - public override bool Equals(NubType? other) => other is NubIntType @int && @int.Width == Width && @int.Signed == Signed; - public override int GetHashCode() => HashCode.Combine(typeof(NubIntType), Signed, Width); -} - -public sealed class NubFloatType(int width) : NubType -{ - public int Width { get; } = width; - - public override string ToString() => $"f{Width}"; - public override bool Equals(NubType? other) => other is NubFloatType @float && @float.Width == Width; - public override int GetHashCode() => HashCode.Combine(typeof(NubFloatType), Width); -} - -public class NubBoolType : NubType -{ - public override string ToString() => "bool"; - public override bool Equals(NubType? other) => other is NubBoolType; - public override int GetHashCode() => HashCode.Combine(typeof(NubBoolType)); -} - -public sealed class NubPointerType(NubType baseType) : NubType -{ - public NubType BaseType { get; } = baseType; - - public override string ToString() => "^" + BaseType; - public override bool Equals(NubType? other) => other is NubPointerType pointer && BaseType.Equals(pointer.BaseType); - public override int GetHashCode() => HashCode.Combine(typeof(NubPointerType), BaseType); -} - -public class NubFuncType(List parameters, NubType returnType) : NubType -{ - public List Parameters { get; } = parameters; - public NubType ReturnType { get; } = returnType; - - public override string ToString() => $"func({string.Join(", ", Parameters)}): {ReturnType}"; - public override bool Equals(NubType? other) => other is NubFuncType func && ReturnType.Equals(func.ReturnType) && Parameters.SequenceEqual(func.Parameters); - - public override int GetHashCode() - { - var hash = new HashCode(); - hash.Add(typeof(NubFuncType)); - hash.Add(ReturnType); - foreach (var param in Parameters) - { - hash.Add(param); - } - - return hash.ToHashCode(); - } -} - -public class NubStructType(string module, string name, List fields) : NubType -{ - public string Module { get; } = module; - public string Name { get; } = name; - public List Fields { get; set; } = fields; - - public override string ToString() => $"{Module}::{Name}"; - public override bool Equals(NubType? other) => other is NubStructType structType && Name == structType.Name && Module == structType.Module; - public override int GetHashCode() => HashCode.Combine(typeof(NubStructType), Module, Name); -} - -public class NubStructFieldType(string name, NubType type, bool hasDefaultValue) -{ - public string Name { get; } = name; - public NubType Type { get; } = type; - public bool HasDefaultValue { get; } = hasDefaultValue; -} - -public class NubSliceType(NubType elementType) : NubType -{ - public NubType ElementType { get; } = elementType; - - public override string ToString() => "[]" + ElementType; - public override bool Equals(NubType? other) => other is NubSliceType slice && ElementType.Equals(slice.ElementType); - public override int GetHashCode() => HashCode.Combine(typeof(NubSliceType), ElementType); -} - -public class NubConstArrayType(NubType elementType, long size) : NubType -{ - public NubType ElementType { get; } = elementType; - public long Size { get; } = size; - - public override string ToString() => $"[{Size}]{ElementType}"; - public override bool Equals(NubType? other) => other is NubConstArrayType array && ElementType.Equals(array.ElementType) && Size == array.Size; - public override int GetHashCode() => HashCode.Combine(typeof(NubConstArrayType), ElementType, Size); -} - -public class NubArrayType(NubType elementType) : NubType -{ - public NubType ElementType { get; } = elementType; - - public override string ToString() => $"[?]{ElementType}"; - public override bool Equals(NubType? other) => other is NubArrayType array && ElementType.Equals(array.ElementType); - public override int GetHashCode() => HashCode.Combine(typeof(NubArrayType), ElementType); -} - -public class NubStringType : NubType -{ - public override string ToString() => "string"; - public override bool Equals(NubType? other) => other is NubStringType; - public override int GetHashCode() => HashCode.Combine(typeof(NubStringType)); -} - -public static class NameMangler -{ - public static string Mangle(params IEnumerable types) - { - var readable = string.Join(":", types.Select(EncodeType)); - return ComputeShortHash(readable); - } - - private static string EncodeType(NubType node) => node switch - { - NubVoidType => "V", - NubBoolType => "B", - NubIntType i => (i.Signed ? "I" : "U") + i.Width, - NubFloatType f => "F" + f.Width, - NubStringType => "S", - NubArrayType a => $"A({EncodeType(a.ElementType)})", - NubConstArrayType ca => $"CA({EncodeType(ca.ElementType)})", - NubSliceType a => $"SL{EncodeType(a.ElementType)}()", - NubPointerType p => $"P({EncodeType(p.BaseType)})", - NubFuncType fn => $"FN({string.Join(":", fn.Parameters.Select(EncodeType))}:{EncodeType(fn.ReturnType)})", - NubStructType st => $"ST({st.Module}:{st.Name})", - _ => throw new NotSupportedException($"Cannot encode type: {node}") - }; - - private static string ComputeShortHash(string input) - { - var bytes = Encoding.UTF8.GetBytes(input); - var hash = SHA256.HashData(bytes); - return Convert.ToHexString(hash[..8]).ToLower(); - } -} \ No newline at end of file diff --git a/compiler/NubLang/Ast/TypeChecker.cs b/compiler/NubLang/Ast/TypeChecker.cs deleted file mode 100644 index 4224115..0000000 --- a/compiler/NubLang/Ast/TypeChecker.cs +++ /dev/null @@ -1,1167 +0,0 @@ -using System.Diagnostics; -using NubLang.Diagnostics; -using NubLang.Syntax; - -namespace NubLang.Ast; - -public sealed class TypeChecker -{ - private readonly SyntaxTree _syntaxTree; - private readonly Dictionary _importedModules; - - private readonly Stack _scopes = []; - private readonly Dictionary<(string Module, string Name), NubType> _typeCache = new(); - private readonly HashSet<(string Module, string Name)> _resolvingTypes = []; - - private Scope Scope => _scopes.Peek(); - - public List Diagnostics { get; } = []; - - public TypeChecker(SyntaxTree syntaxTree, Dictionary modules) - { - _syntaxTree = syntaxTree; - _importedModules = modules - .Where(x => syntaxTree.Imports.Contains(x.Key) || _syntaxTree.ModuleName == x.Key) - .ToDictionary(); - } - - public CompilationUnit Check() - { - _scopes.Clear(); - _typeCache.Clear(); - _resolvingTypes.Clear(); - - var functions = new List(); - - using (BeginRootScope(_syntaxTree.ModuleName)) - { - foreach (var funcSyntax in _syntaxTree.Definitions.OfType()) - { - try - { - functions.Add(CheckFuncDefinition(funcSyntax)); - } - catch (TypeCheckerException e) - { - Diagnostics.Add(e.Diagnostic); - } - } - } - - var importedStructTypes = new List(); - var importedFunctions = new List(); - - foreach (var (name, module) in _importedModules) - { - using (BeginRootScope(name)) - { - foreach (var structSyntax in module.Structs(true)) - { - try - { - var fields = structSyntax.Fields - .Select(f => new NubStructFieldType(f.Name, ResolveType(f.Type), f.Value != null)) - .ToList(); - - importedStructTypes.Add(new NubStructType(name, structSyntax.Name, fields)); - } - catch (TypeCheckerException e) - { - Diagnostics.Add(e.Diagnostic); - } - } - - foreach (var funcSyntax in module.Functions(true)) - { - try - { - importedFunctions.Add(CheckFuncPrototype(funcSyntax.Prototype)); - } - catch (TypeCheckerException e) - { - Diagnostics.Add(e.Diagnostic); - } - } - } - } - - return new CompilationUnit(functions, importedStructTypes, importedFunctions); - } - - private ScopeDisposer BeginScope() - { - _scopes.Push(Scope.SubScope()); - return new ScopeDisposer(this); - } - - private ScopeDisposer BeginRootScope(string moduleName) - { - _scopes.Push(new Scope(moduleName)); - return new ScopeDisposer(this); - } - - private sealed class ScopeDisposer(TypeChecker owner) : IDisposable - { - private bool _disposed; - - public void Dispose() - { - if (_disposed) return; - owner._scopes.Pop(); - _disposed = true; - } - } - - private FuncNode CheckFuncDefinition(FuncSyntax node) - { - using (BeginScope()) - { - var prototype = CheckFuncPrototype(node.Prototype); - - Scope.SetReturnType(prototype.ReturnType); - foreach (var parameter in prototype.Parameters) - { - Scope.DeclareVariable(new Variable(parameter.Name, parameter.Type)); - } - - var body = node.Body == null ? null : CheckBlock(node.Body); - return new FuncNode(node.Tokens, prototype, body); - } - } - - private AssignmentNode CheckAssignment(AssignmentSyntax statement) - { - var target = CheckExpression(statement.Target); - if (target is not LValueExpressionNode lValue) - { - throw new TypeCheckerException(Diagnostic.Error("Cannot assign to an rvalue").At(statement).Build()); - } - - var value = CheckExpression(statement.Value, lValue.Type); - - if (value.Type != lValue.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Cannot assign {value.Type} to {lValue.Type}") - .At(statement.Value) - .Build()); - } - - return new AssignmentNode(statement.Tokens, lValue, value); - } - - private IfNode CheckIf(IfSyntax statement) - { - var condition = CheckExpression(statement.Condition); - var body = CheckBlock(statement.Body); - Variant? elseStatement = null; - if (statement.Else.HasValue) - { - elseStatement = statement.Else.Value.Match>(elif => CheckIf(elif), el => CheckBlock(el)); - } - - return new IfNode(statement.Tokens, condition, body, elseStatement); - } - - private ReturnNode CheckReturn(ReturnSyntax statement) - { - ExpressionNode? value = null; - - if (statement.Value != null) - { - var expectedReturnType = Scope.GetReturnType(); - value = CheckExpression(statement.Value, expectedReturnType); - } - - return new ReturnNode(statement.Tokens, value); - } - - private StatementNode CheckStatementExpression(StatementExpressionSyntax statement) - { - var expression = CheckExpression(statement.Expression); - - return expression switch - { - FuncCallNode funcCall => new StatementFuncCallNode(statement.Tokens, funcCall), - _ => throw new TypeCheckerException(Diagnostic.Error("Expressions statements can only be function calls").At(statement).Build()) - }; - } - - private VariableDeclarationNode CheckVariableDeclaration(VariableDeclarationSyntax statement) - { - NubType? type = null; - ExpressionNode? assignmentNode = null; - - if (statement.ExplicitType != null) - { - type = ResolveType(statement.ExplicitType); - } - - if (statement.Assignment != null) - { - assignmentNode = CheckExpression(statement.Assignment, type); - - if (type == null) - { - type = assignmentNode.Type; - } - else if (assignmentNode.Type != type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Cannot assign {assignmentNode.Type} to variable of type {type}") - .At(statement.Assignment) - .Build()); - } - } - - if (type == null) - { - throw new TypeCheckerException(Diagnostic - .Error($"Cannot infer type of variable {statement.Name}") - .At(statement) - .Build()); - } - - Scope.DeclareVariable(new Variable(statement.Name, type)); - - return new VariableDeclarationNode(statement.Tokens, statement.Name, assignmentNode, type); - } - - private WhileNode CheckWhile(WhileSyntax statement) - { - var condition = CheckExpression(statement.Condition); - var body = CheckBlock(statement.Body); - return new WhileNode(statement.Tokens, condition, body); - } - - private StatementNode CheckFor(ForSyntax forSyntax) - { - var target = CheckExpression(forSyntax.Target); - - - switch (target.Type) - { - case NubSliceType sliceType: - { - using (BeginScope()) - { - Scope.DeclareVariable(new Variable(forSyntax.ElementName, sliceType.ElementType)); - if (forSyntax.IndexName != null) - { - Scope.DeclareVariable(new Variable(forSyntax.IndexName, new NubIntType(false, 64))); - } - - var body = CheckBlock(forSyntax.Body); - return new ForSliceNode(forSyntax.Tokens, forSyntax.ElementName, forSyntax.IndexName, target, body); - } - } - case NubConstArrayType constArrayType: - { - using (BeginScope()) - { - Scope.DeclareVariable(new Variable(forSyntax.ElementName, constArrayType.ElementType)); - if (forSyntax.IndexName != null) - { - Scope.DeclareVariable(new Variable(forSyntax.IndexName, new NubIntType(false, 64))); - } - - var body = CheckBlock(forSyntax.Body); - return new ForConstArrayNode(forSyntax.Tokens, forSyntax.ElementName, forSyntax.IndexName, target, body); - } - } - default: - { - throw new TypeCheckerException(Diagnostic - .Error($"Cannot iterate over type {target.Type} which does not have size information") - .At(forSyntax.Target) - .Build()); - } - } - } - - private FuncPrototypeNode CheckFuncPrototype(FuncPrototypeSyntax statement) - { - var parameters = new List(); - foreach (var parameter in statement.Parameters) - { - parameters.Add(new FuncParameterNode(parameter.Tokens, parameter.Name, ResolveType(parameter.Type))); - } - - return new FuncPrototypeNode(statement.Tokens, Scope.Module, statement.Name, statement.ExternSymbol, parameters, ResolveType(statement.ReturnType)); - } - - private ExpressionNode CheckExpression(ExpressionSyntax node, NubType? expectedType = null) - { - var result = node switch - { - AddressOfSyntax expression => CheckAddressOf(expression, expectedType), - ArrayIndexAccessSyntax expression => CheckArrayIndexAccess(expression, expectedType), - ArrayInitializerSyntax expression => CheckArrayInitializer(expression, expectedType), - BinaryExpressionSyntax expression => CheckBinaryExpression(expression, expectedType), - UnaryExpressionSyntax expression => CheckUnaryExpression(expression, expectedType), - DereferenceSyntax expression => CheckDereference(expression, expectedType), - FuncCallSyntax expression => CheckFuncCall(expression, expectedType), - LocalIdentifierSyntax expression => CheckLocalIdentifier(expression, expectedType), - ModuleIdentifierSyntax expression => CheckModuleIdentifier(expression, expectedType), - BoolLiteralSyntax expression => CheckBoolLiteral(expression, expectedType), - StringLiteralSyntax expression => CheckStringLiteral(expression, expectedType), - IntLiteralSyntax expression => CheckIntLiteral(expression, expectedType), - FloatLiteralSyntax expression => CheckFloatLiteral(expression, expectedType), - MemberAccessSyntax expression => CheckMemberAccess(expression, expectedType), - StructInitializerSyntax expression => CheckStructInitializer(expression, expectedType), - SizeSyntax expression => new SizeNode(node.Tokens, ResolveType(expression.Type)), - CastSyntax expression => CheckCast(expression, expectedType), - _ => throw new ArgumentOutOfRangeException(nameof(node)) - }; - - if (expectedType != null) - { - if (result.Type == expectedType) - { - return result; - } - - if (IsCastAllowed(result.Type, expectedType)) - { - return new CastNode(result.Tokens, expectedType, result); - } - } - - return result; - } - - private ExpressionNode CheckCast(CastSyntax expression, NubType? expectedType) - { - if (expectedType == null) - { - throw new TypeCheckerException(Diagnostic - .Error("Unable to infer target type of cast") - .At(expression) - .WithHelp("Specify target type where value is used") - .Build()); - } - - var value = CheckExpression(expression.Value, expectedType); - - if (value.Type == expectedType) - { - Diagnostics.Add(Diagnostic - .Warning("Target type of cast is same as the value. Cast is unnecessary") - .At(expression) - .Build()); - - return value; - } - - if (!IsCastAllowed(value.Type, expectedType, false)) - { - throw new TypeCheckerException(Diagnostic - .Error($"Cannot cast from {value.Type} to {expectedType}") - .Build()); - } - - return new CastNode(expression.Tokens, expectedType, value); - } - - private static bool IsCastAllowed(NubType from, NubType to, bool strict = true) - { - // note(nub31): Implicit casts - switch (from) - { - case NubIntType fromInt when to is NubIntType toInt && fromInt.Width < toInt.Width: - case NubPointerType when to is NubPointerType { BaseType: NubVoidType }: - case NubConstArrayType constArrayType1 when to is NubArrayType arrayType && constArrayType1.ElementType == arrayType.ElementType: - case NubConstArrayType constArrayType3 when to is NubSliceType sliceType2 && constArrayType3.ElementType == sliceType2.ElementType: - { - return true; - } - } - - if (!strict) - { - // note(nub31): Explicit casts - switch (from) - { - case NubIntType when to is NubIntType: - case NubIntType when to is NubFloatType: - case NubFloatType when to is NubIntType: - case NubFloatType when to is NubFloatType: - case NubPointerType when to is NubPointerType: - case NubPointerType when to is NubIntType: - case NubIntType when to is NubPointerType: - { - return true; - } - } - } - - - return false; - } - - private AddressOfNode CheckAddressOf(AddressOfSyntax expression, NubType? expectedType) - { - var target = CheckExpression(expression.Target, (expectedType as NubPointerType)?.BaseType); - if (target is not LValueExpressionNode lvalue) - { - throw new TypeCheckerException(Diagnostic.Error("Cannot take address of an rvalue").At(expression).Build()); - } - - var type = new NubPointerType(target.Type); - return new AddressOfNode(expression.Tokens, type, lvalue); - } - - private ExpressionNode CheckArrayIndexAccess(ArrayIndexAccessSyntax expression, NubType? _) - { - var index = CheckExpression(expression.Index); - if (index.Type is not NubIntType) - { - throw new TypeCheckerException(Diagnostic - .Error("Array indexer must be of type int") - .At(expression.Index) - .Build()); - } - - var target = CheckExpression(expression.Target); - - return target.Type switch - { - NubArrayType arrayType => new ArrayIndexAccessNode(expression.Tokens, arrayType.ElementType, target, index), - NubConstArrayType constArrayType => new ConstArrayIndexAccessNode(expression.Tokens, constArrayType.ElementType, target, index), - NubSliceType sliceType => new SliceIndexAccessNode(expression.Tokens, sliceType.ElementType, target, index), - _ => throw new TypeCheckerException(Diagnostic.Error($"Cannot use array indexer on type {target.Type}").At(expression).Build()) - }; - } - - private ExpressionNode CheckArrayInitializer(ArrayInitializerSyntax expression, NubType? expectedType) - { - var elementType = expectedType switch - { - NubArrayType arrayType => arrayType.ElementType, - NubConstArrayType constArrayType => constArrayType.ElementType, - NubSliceType sliceType => sliceType.ElementType, - _ => null - }; - - if (elementType == null) - { - var firstValue = expression.Values.FirstOrDefault(); - if (firstValue != null) - { - elementType = CheckExpression(firstValue).Type; - } - } - - if (elementType == null) - { - throw new TypeCheckerException(Diagnostic - .Error("Unable to infer type of array initializer") - .At(expression) - .WithHelp("Provide a type for a variable assignment") - .Build()); - } - - var values = new List(); - foreach (var valueExpression in expression.Values) - { - var value = CheckExpression(valueExpression, elementType); - if (value.Type != elementType) - { - throw new TypeCheckerException(Diagnostic - .Error("Value in array initializer is not the same as the array type") - .At(valueExpression) - .Build()); - } - - values.Add(value); - } - - return expectedType switch - { - NubArrayType => new ArrayInitializerNode(expression.Tokens, new NubArrayType(elementType), values), - NubConstArrayType constArrayType => new ConstArrayInitializerNode(expression.Tokens, constArrayType, values), - _ => new ConstArrayInitializerNode(expression.Tokens, new NubConstArrayType(elementType, expression.Values.Count), values) - }; - } - - private BinaryExpressionNode CheckBinaryExpression(BinaryExpressionSyntax expression, NubType? expectedType) - { - var op = expression.Operator switch - { - BinaryOperatorSyntax.Equal => BinaryOperator.Equal, - BinaryOperatorSyntax.NotEqual => BinaryOperator.NotEqual, - BinaryOperatorSyntax.GreaterThan => BinaryOperator.GreaterThan, - BinaryOperatorSyntax.GreaterThanOrEqual => BinaryOperator.GreaterThanOrEqual, - BinaryOperatorSyntax.LessThan => BinaryOperator.LessThan, - BinaryOperatorSyntax.LessThanOrEqual => BinaryOperator.LessThanOrEqual, - BinaryOperatorSyntax.LogicalAnd => BinaryOperator.LogicalAnd, - BinaryOperatorSyntax.LogicalOr => BinaryOperator.LogicalOr, - BinaryOperatorSyntax.Plus => BinaryOperator.Plus, - BinaryOperatorSyntax.Minus => BinaryOperator.Minus, - BinaryOperatorSyntax.Multiply => BinaryOperator.Multiply, - BinaryOperatorSyntax.Divide => BinaryOperator.Divide, - BinaryOperatorSyntax.Modulo => BinaryOperator.Modulo, - BinaryOperatorSyntax.LeftShift => BinaryOperator.LeftShift, - BinaryOperatorSyntax.RightShift => BinaryOperator.RightShift, - BinaryOperatorSyntax.BitwiseAnd => BinaryOperator.BitwiseAnd, - BinaryOperatorSyntax.BitwiseXor => BinaryOperator.BitwiseXor, - BinaryOperatorSyntax.BitwiseOr => BinaryOperator.BitwiseOr, - _ => throw new ArgumentOutOfRangeException() - }; - - switch (expression.Operator) - { - case BinaryOperatorSyntax.Equal: - case BinaryOperatorSyntax.NotEqual: - { - var left = CheckExpression(expression.Left); - if (left.Type is not NubIntType and not NubFloatType and not NubBoolType) - { - throw new TypeCheckerException(Diagnostic - .Error("Equal and not equal operators must must be used with int, float or bool types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, new NubBoolType(), left, op, right); - } - case BinaryOperatorSyntax.GreaterThan: - case BinaryOperatorSyntax.GreaterThanOrEqual: - case BinaryOperatorSyntax.LessThan: - case BinaryOperatorSyntax.LessThanOrEqual: - { - var left = CheckExpression(expression.Left); - if (left.Type is not NubIntType and not NubFloatType) - { - throw new TypeCheckerException(Diagnostic - .Error("Greater than and less than operators must must be used with int or float types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, new NubBoolType(), left, op, right); - } - case BinaryOperatorSyntax.LogicalAnd: - case BinaryOperatorSyntax.LogicalOr: - { - var left = CheckExpression(expression.Left); - if (left.Type is not NubBoolType) - { - throw new TypeCheckerException(Diagnostic - .Error("Logical and/or must must be used with bool types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, new NubBoolType(), left, op, right); - } - case BinaryOperatorSyntax.Plus: - { - var left = CheckExpression(expression.Left, expectedType); - if (left.Type is not NubIntType and not NubFloatType) - { - throw new TypeCheckerException(Diagnostic - .Error("The plus operator must only be used with int and float types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, left.Type, left, op, right); - } - case BinaryOperatorSyntax.Minus: - case BinaryOperatorSyntax.Multiply: - case BinaryOperatorSyntax.Divide: - case BinaryOperatorSyntax.Modulo: - { - var left = CheckExpression(expression.Left, expectedType); - if (left.Type is not NubIntType and not NubFloatType) - { - throw new TypeCheckerException(Diagnostic - .Error("Math operators must be used with int or float types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, left.Type, left, op, right); - } - case BinaryOperatorSyntax.LeftShift: - case BinaryOperatorSyntax.RightShift: - case BinaryOperatorSyntax.BitwiseAnd: - case BinaryOperatorSyntax.BitwiseXor: - case BinaryOperatorSyntax.BitwiseOr: - { - var left = CheckExpression(expression.Left, expectedType); - if (left.Type is not NubIntType) - { - throw new TypeCheckerException(Diagnostic - .Error("Bitwise operators must be used with int types") - .At(expression.Left) - .Build()); - } - - var right = CheckExpression(expression.Right, left.Type); - if (right.Type != left.Type) - { - throw new TypeCheckerException(Diagnostic - .Error($"Expected type {left.Type} from left side of binary expression, but got {right.Type}") - .At(expression.Right) - .Build()); - } - - return new BinaryExpressionNode(expression.Tokens, left.Type, left, op, right); - } - default: - { - throw new ArgumentOutOfRangeException(); - } - } - } - - private UnaryExpressionNode CheckUnaryExpression(UnaryExpressionSyntax expression, NubType? expectedType) - { - switch (expression.Operator) - { - case UnaryOperatorSyntax.Negate: - { - var operand = CheckExpression(expression.Operand, expectedType); - if (operand.Type is not NubIntType { Signed: true } and not NubFloatType) - { - throw new TypeCheckerException(Diagnostic - .Error("Negation operator must be used with signed integer or float types") - .At(expression) - .Build()); - } - - return new UnaryExpressionNode(expression.Tokens, operand.Type, UnaryOperator.Negate, operand); - } - case UnaryOperatorSyntax.Invert: - { - var operand = CheckExpression(expression.Operand, expectedType); - if (operand.Type is not NubBoolType) - { - throw new TypeCheckerException(Diagnostic - .Error("Invert operator must be used with booleans") - .At(expression) - .Build()); - } - - return new UnaryExpressionNode(expression.Tokens, operand.Type, UnaryOperator.Invert, operand); - } - default: - { - throw new ArgumentOutOfRangeException(); - } - } - } - - private DereferenceNode CheckDereference(DereferenceSyntax expression, NubType? _) - { - var target = CheckExpression(expression.Target); - if (target.Type is not NubPointerType pointerType) - { - throw new TypeCheckerException(Diagnostic.Error($"Cannot dereference non-pointer type {target.Type}").At(expression).Build()); - } - - return new DereferenceNode(expression.Tokens, pointerType.BaseType, target); - } - - private FuncCallNode CheckFuncCall(FuncCallSyntax expression, NubType? _) - { - var accessor = CheckExpression(expression.Expression); - if (accessor.Type is not NubFuncType funcType) - { - throw new TypeCheckerException(Diagnostic.Error($"Cannot call non-function type {accessor.Type}").At(expression.Expression).Build()); - } - - if (expression.Parameters.Count != funcType.Parameters.Count) - { - throw new TypeCheckerException(Diagnostic - .Error($"Function {funcType} expects {funcType.Parameters.Count} parameters but got {expression.Parameters.Count}") - .At(expression.Parameters.LastOrDefault(expression)) - .Build()); - } - - var parameters = new List(); - for (var i = 0; i < expression.Parameters.Count; i++) - { - var parameter = expression.Parameters[i]; - var expectedParameterType = funcType.Parameters[i]; - - var parameterExpression = CheckExpression(parameter, expectedParameterType); - if (parameterExpression.Type != expectedParameterType) - { - throw new TypeCheckerException(Diagnostic - .Error($"Parameter {i + 1} does not match the type {expectedParameterType} for function {funcType}") - .At(parameter) - .Build()); - } - - parameters.Add(parameterExpression); - } - - return new FuncCallNode(expression.Tokens, funcType.ReturnType, accessor, parameters); - } - - private ExpressionNode? CheckIdentifier(ExpressionSyntax expression, string moduleName, string name) - { - if (!_importedModules.TryGetValue(moduleName, out var module)) - { - throw new TypeCheckerException(Diagnostic - .Error($"Module {moduleName} not found") - .WithHelp($"import \"{moduleName}\"") - .At(expression) - .Build()); - } - - var function = module.Functions(IsCurretModule(moduleName)).FirstOrDefault(x => x.Name == name); - if (function != null) - { - using (BeginRootScope(moduleName)) - { - var parameters = function.Prototype.Parameters.Select(x => ResolveType(x.Type)).ToList(); - var type = new NubFuncType(parameters, ResolveType(function.Prototype.ReturnType)); - return new FuncIdentifierNode(expression.Tokens, type, moduleName, name, function.Prototype.ExternSymbol); - } - } - - var enumDef = module.Enums(IsCurretModule(moduleName)).FirstOrDefault(x => x.Name == name); - if (enumDef != null) - { - return new EnumReferenceIntermediateNode(expression.Tokens, moduleName, name); - } - - return null; - } - - private ExpressionNode CheckLocalIdentifier(LocalIdentifierSyntax expression, NubType? _) - { - // note(nub31): Local identifiers can be variables or a symbol in a module - var scopeIdent = Scope.LookupVariable(expression.Name); - if (scopeIdent != null) - { - return new VariableIdentifierNode(expression.Tokens, scopeIdent.Type, expression.Name); - } - - var ident = CheckIdentifier(expression, Scope.Module, expression.Name); - if (ident == null) - { - throw new TypeCheckerException(Diagnostic - .Error($"There is no identifier named {expression.Name}") - .At(expression) - .Build()); - } - - return ident; - } - - private ExpressionNode CheckModuleIdentifier(ModuleIdentifierSyntax expression, NubType? _) - { - // note(nub31): Unlike local identifiers, module identifiers does not look for local variables - var ident = CheckIdentifier(expression, expression.Module, expression.Name); - if (ident == null) - { - throw new TypeCheckerException(Diagnostic - .Error($"Module {expression.Module} does not export a member named {expression.Name}") - .At(expression) - .Build()); - } - - return ident; - } - - private ExpressionNode CheckStringLiteral(StringLiteralSyntax expression, NubType? expectedType) - { - if (expectedType is NubPointerType { BaseType: NubIntType { Signed: true, Width: 8 } }) - { - return new CStringLiteralNode(expression.Tokens, expression.Value); - } - - return new StringLiteralNode(expression.Tokens, expression.Value); - } - - private ExpressionNode CheckIntLiteral(IntLiteralSyntax expression, NubType? expectedType) - { - if (expectedType is NubIntType intType) - { - return intType.Width switch - { - 8 => intType.Signed ? new I8LiteralNode(expression.Tokens, Convert.ToSByte(expression.Value, expression.Base)) : new U8LiteralNode(expression.Tokens, Convert.ToByte(expression.Value, expression.Base)), - 16 => intType.Signed ? new I16LiteralNode(expression.Tokens, Convert.ToInt16(expression.Value, expression.Base)) : new U16LiteralNode(expression.Tokens, Convert.ToUInt16(expression.Value, expression.Base)), - 32 => intType.Signed ? new I32LiteralNode(expression.Tokens, Convert.ToInt32(expression.Value, expression.Base)) : new U32LiteralNode(expression.Tokens, Convert.ToUInt32(expression.Value, expression.Base)), - 64 => intType.Signed ? new I64LiteralNode(expression.Tokens, Convert.ToInt64(expression.Value, expression.Base)) : new U64LiteralNode(expression.Tokens, Convert.ToUInt64(expression.Value, expression.Base)), - _ => throw new ArgumentOutOfRangeException() - }; - } - - if (expectedType is NubFloatType floatType) - { - return floatType.Width switch - { - 32 => new Float32LiteralNode(expression.Tokens, Convert.ToSingle(expression.Value)), - 64 => new Float64LiteralNode(expression.Tokens, Convert.ToDouble(expression.Value)), - _ => throw new ArgumentOutOfRangeException() - }; - } - - return new I64LiteralNode(expression.Tokens, Convert.ToInt64(expression.Value, expression.Base)); - } - - private ExpressionNode CheckFloatLiteral(FloatLiteralSyntax expression, NubType? expectedType) - { - if (expectedType is NubFloatType floatType) - { - return floatType.Width switch - { - 32 => new Float32LiteralNode(expression.Tokens, Convert.ToSingle(expression.Value)), - 64 => new Float64LiteralNode(expression.Tokens, Convert.ToDouble(expression.Value)), - _ => throw new ArgumentOutOfRangeException() - }; - } - - return new Float64LiteralNode(expression.Tokens, Convert.ToDouble(expression.Value)); - } - - private BoolLiteralNode CheckBoolLiteral(BoolLiteralSyntax expression, NubType? _) - { - return new BoolLiteralNode(expression.Tokens, new NubBoolType(), expression.Value); - } - - private ExpressionNode CheckMemberAccess(MemberAccessSyntax expression, NubType? _) - { - var target = CheckExpression(expression.Target); - - if (target is EnumReferenceIntermediateNode enumReferenceIntermediate) - { - var enumDef = _importedModules[enumReferenceIntermediate.Module] - .Enums(IsCurretModule(enumReferenceIntermediate.Module)) - .First(x => x.Name == enumReferenceIntermediate.Name); - - var field = enumDef.Fields.FirstOrDefault(x => x.Name == expression.Member); - if (field == null) - { - throw new TypeCheckerException(Diagnostic - .Error($"Enum {Scope.Module}::{enumReferenceIntermediate.Name} does not have a field named {expression.Member}") - .At(enumDef) - .Build()); - } - - var enumType = enumDef.Type != null ? ResolveType(enumDef.Type) : new NubIntType(false, 64); - if (enumType is not NubIntType enumIntType) - { - throw new TypeCheckerException(Diagnostic.Error("Enum type must be an int type").At(enumDef.Type).Build()); - } - - return enumIntType.Width switch - { - 8 => enumIntType.Signed ? new I8LiteralNode(expression.Tokens, (sbyte)field.Value) : new U8LiteralNode(expression.Tokens, (byte)field.Value), - 16 => enumIntType.Signed ? new I16LiteralNode(expression.Tokens, (short)field.Value) : new U16LiteralNode(expression.Tokens, (ushort)field.Value), - 32 => enumIntType.Signed ? new I32LiteralNode(expression.Tokens, (int)field.Value) : new U32LiteralNode(expression.Tokens, (uint)field.Value), - 64 => enumIntType.Signed ? new I64LiteralNode(expression.Tokens, field.Value) : new U64LiteralNode(expression.Tokens, (ulong)field.Value), - _ => throw new ArgumentOutOfRangeException() - }; - } - - if (target.Type is NubStructType structType) - { - var field = structType.Fields.FirstOrDefault(x => x.Name == expression.Member); - if (field == null) - { - throw new TypeCheckerException(Diagnostic - .Error($"Struct {target.Type} does not have a field with the name {expression.Member}") - .At(expression) - .Build()); - } - - return new StructFieldAccessNode(expression.Tokens, field.Type, target, expression.Member); - } - - throw new TypeCheckerException(Diagnostic - .Error($"Cannot access struct member {expression.Member} on type {target.Type}") - .At(expression) - .Build()); - } - - private StructInitializerNode CheckStructInitializer(StructInitializerSyntax expression, NubType? expectedType) - { - NubStructType? structType = null; - - if (expression.StructType != null) - { - var checkedType = ResolveType(expression.StructType); - if (checkedType is not NubStructType checkedStructType) - { - throw new UnreachableException("Parser fucked up"); - } - - structType = checkedStructType; - } - else if (expectedType is NubStructType expectedStructType) - { - structType = expectedStructType; - } - - if (structType == null) - { - throw new TypeCheckerException(Diagnostic - .Error("Cannot get implicit type of struct") - .WithHelp("Specify struct type with struct {type_name} syntax") - .At(expression) - .Build()); - } - - var initializers = new Dictionary(); - - foreach (var initializer in expression.Initializers) - { - var typeField = structType.Fields.FirstOrDefault(x => x.Name == initializer.Key); - if (typeField == null) - { - Diagnostics.AddRange(Diagnostic - .Error($"Struct {structType.Name} does not have a field named {initializer.Key}") - .At(initializer.Value) - .Build()); - - continue; - } - - initializers.Add(initializer.Key, CheckExpression(initializer.Value, typeField.Type)); - } - - var missingFields = structType.Fields - .Where(x => !x.HasDefaultValue && !initializers.ContainsKey(x.Name)) - .Select(x => x.Name) - .ToArray(); - - if (missingFields.Length != 0) - { - Diagnostics.Add(Diagnostic - .Warning($"Fields {string.Join(", ", missingFields)} are not initialized") - .At(expression) - .Build()); - } - - return new StructInitializerNode(expression.Tokens, structType, initializers); - } - - private BlockNode CheckBlock(BlockSyntax node) - { - using (BeginScope()) - { - var statements = new List(); - foreach (var statement in node.Statements) - { - try - { - statements.Add(CheckStatement(statement)); - } - catch (TypeCheckerException e) - { - Diagnostics.Add(e.Diagnostic); - } - } - - return new BlockNode(node.Tokens, statements); - } - } - - private StatementNode CheckStatement(StatementSyntax statement) - { - return statement switch - { - AssignmentSyntax assignmentStmt => CheckAssignment(assignmentStmt), - BlockSyntax blockStmt => CheckBlock(blockStmt), - BreakSyntax => new BreakNode(statement.Tokens), - ContinueSyntax => new ContinueNode(statement.Tokens), - IfSyntax ifStmt => CheckIf(ifStmt), - ReturnSyntax retStmt => CheckReturn(retStmt), - StatementExpressionSyntax stmtExpr => CheckStatementExpression(stmtExpr), - VariableDeclarationSyntax varDeclStmt => CheckVariableDeclaration(varDeclStmt), - WhileSyntax whileStmt => CheckWhile(whileStmt), - DeferSyntax defer => new DeferNode(statement.Tokens, CheckStatement(defer.Statement)), - ForSyntax forSyntax => CheckFor(forSyntax), - _ => throw new ArgumentOutOfRangeException(nameof(statement)) - }; - } - - private NubType ResolveType(TypeSyntax type) - { - return type switch - { - ArrayTypeSyntax arr => new NubArrayType(ResolveType(arr.BaseType)), - BoolTypeSyntax => new NubBoolType(), - IntTypeSyntax i => new NubIntType(i.Signed, i.Width), - FloatTypeSyntax f => new NubFloatType(f.Width), - FuncTypeSyntax func => new NubFuncType(func.Parameters.Select(ResolveType).ToList(), ResolveType(func.ReturnType)), - SliceTypeSyntax slice => new NubSliceType(ResolveType(slice.BaseType)), - ConstArrayTypeSyntax arr => new NubConstArrayType(ResolveType(arr.BaseType), arr.Size), - PointerTypeSyntax ptr => new NubPointerType(ResolveType(ptr.BaseType)), - StringTypeSyntax => new NubStringType(), - CustomTypeSyntax c => ResolveCustomType(c), - VoidTypeSyntax => new NubVoidType(), - _ => throw new NotSupportedException($"Unknown type syntax: {type}") - }; - } - - private NubType ResolveCustomType(CustomTypeSyntax customType) - { - if (!_importedModules.TryGetValue(customType.Module ?? Scope.Module, out var module)) - { - throw new TypeCheckerException(Diagnostic - .Error($"Module {customType.Module ?? Scope.Module} not found") - .WithHelp($"import \"{customType.Module ?? Scope.Module}\"") - .At(customType) - .Build()); - } - - var enumDef = module.Enums(IsCurretModule(customType.Module)).FirstOrDefault(x => x.Name == customType.Name); - if (enumDef != null) - { - return enumDef.Type != null ? ResolveType(enumDef.Type) : new NubIntType(false, 64); - } - - var structDef = module.Structs(IsCurretModule(customType.Module)).FirstOrDefault(x => x.Name == customType.Name); - if (structDef != null) - { - var key = (customType.Module ?? Scope.Module, customType.Name); - - if (_typeCache.TryGetValue(key, out var cachedType)) - { - return cachedType; - } - - if (!_resolvingTypes.Add(key)) - { - var placeholder = new NubStructType(customType.Module ?? Scope.Module, customType.Name, []); - _typeCache[key] = placeholder; - return placeholder; - } - - try - { - var result = new NubStructType(customType.Module ?? Scope.Module, structDef.Name, []); - _typeCache[key] = result; - - var fields = structDef.Fields - .Select(x => new NubStructFieldType(x.Name, ResolveType(x.Type), x.Value != null)) - .ToList(); - - result.Fields.AddRange(fields); - return result; - } - finally - { - _resolvingTypes.Remove(key); - } - } - - throw new TypeCheckerException(Diagnostic - .Error($"Type {customType.Name} not found in module {customType.Module ?? Scope.Module}") - .At(customType) - .Build()); - } - - private bool IsCurretModule(string? module) - { - if (module == null) - { - return true; - } - - return module == Scope.Module; - } -} - -public record Variable(string Name, NubType Type); - -public class Scope(string module, Scope? parent = null) -{ - private NubType? _returnType; - private readonly List _variables = []; - public string Module { get; } = module; - - public void DeclareVariable(Variable variable) - { - _variables.Add(variable); - } - - public void SetReturnType(NubType returnType) - { - _returnType = returnType; - } - - public NubType? GetReturnType() - { - return _returnType ?? parent?.GetReturnType(); - } - - public Variable? LookupVariable(string name) - { - var variable = _variables.FirstOrDefault(x => x.Name == name); - if (variable != null) - { - return variable; - } - - return parent?.LookupVariable(name); - } - - public Scope SubScope() - { - return new Scope(Module, this); - } -} - -public class TypeCheckerException : Exception -{ - public Diagnostic Diagnostic { get; } - - public TypeCheckerException(Diagnostic diagnostic) : base(diagnostic.Message) - { - Diagnostic = diagnostic; - } -} \ No newline at end of file diff --git a/compiler/NubLang/Diagnostics/Diagnostic.cs b/compiler/NubLang/Diagnostics/Diagnostic.cs deleted file mode 100644 index bf3cf54..0000000 --- a/compiler/NubLang/Diagnostics/Diagnostic.cs +++ /dev/null @@ -1,398 +0,0 @@ -using System.Text; -using NubLang.Syntax; - -namespace NubLang.Diagnostics; - -public class Diagnostic -{ - public class DiagnosticBuilder - { - private readonly DiagnosticSeverity _severity; - private readonly string _message; - private SourceSpan? _span; - private string? _help; - - public DiagnosticBuilder(DiagnosticSeverity severity, string message) - { - _severity = severity; - _message = message; - } - - public DiagnosticBuilder At(SyntaxNode? node) - { - if (node != null) - { - _span = SourceSpan.Merge(node.Tokens.Select(x => x.Span)); - } - - return this; - } - - public DiagnosticBuilder At(Token? token) - { - if (token != null) - { - At(token.Span); - } - - return this; - } - - public DiagnosticBuilder At(SourceSpan? span) - { - if (span != null) - { - _span = span; - } - - return this; - } - - public DiagnosticBuilder At(string filePath, int line, int column) - { - _span = new SourceSpan(filePath, new SourceLocation(line, column), new SourceLocation(line, column)); - return this; - } - - public DiagnosticBuilder WithHelp(string help) - { - _help = help; - return this; - } - - public Diagnostic Build() => new(_severity, _message, _help, _span); - } - - public static DiagnosticBuilder Error(string message) => new(DiagnosticSeverity.Error, message); - public static DiagnosticBuilder Warning(string message) => new(DiagnosticSeverity.Warning, message); - public static DiagnosticBuilder Info(string message) => new(DiagnosticSeverity.Info, message); - - public DiagnosticSeverity Severity { get; } - public string Message { get; } - public string? Help { get; } - public SourceSpan? Span { get; } - - private Diagnostic(DiagnosticSeverity severity, string message, string? help, SourceSpan? span) - { - Severity = severity; - Message = message; - Help = help; - Span = span; - } - - public string FormatANSI() - { - var sb = new StringBuilder(); - - sb.Append(Severity switch - { - DiagnosticSeverity.Error => ConsoleColors.Colorize("error", ConsoleColors.Bold + ConsoleColors.Red), - DiagnosticSeverity.Warning => ConsoleColors.Colorize("warning", ConsoleColors.Bold + ConsoleColors.Yellow), - DiagnosticSeverity.Info => ConsoleColors.Colorize("info", ConsoleColors.Bold + ConsoleColors.Blue), - _ => ConsoleColors.Colorize("unknown", ConsoleColors.Bold + ConsoleColors.White) - }); - - if (Span.HasValue) - { - sb.Append(ConsoleColors.Colorize($" at {Span.Value}", ConsoleColors.Faint)); - } - - sb.Append(": "); - sb.Append(ConsoleColors.Colorize(Message, ConsoleColors.BrightWhite)); - - if (Span.HasValue) - { - sb.AppendLine(); - var text = File.ReadAllText(Span.Value.FilePath); - - var tokenizer = new Tokenizer(Span.Value.FilePath, text); - tokenizer.Tokenize(); - - var lines = text.Split('\n'); - - var startLine = Span.Value.Start.Line; - var endLine = Span.Value.End.Line; - - const int CONTEXT_LINES = 3; - - var contextStartLine = Math.Max(1, startLine - CONTEXT_LINES); - var contextEndLine = Math.Min(lines.Length, endLine + CONTEXT_LINES); - - var numberPadding = contextEndLine.ToString().Length; - - var codePadding = 0; - for (var i = contextStartLine - 1; i < contextEndLine && i < lines.Length; i++) - { - var lineLength = lines[i].Length; - if (lineLength > codePadding) - { - codePadding = lineLength; - } - } - - sb.Append('╭'); - sb.Append(new string('─', numberPadding + 2)); - sb.Append('┬'); - sb.Append(new string('─', codePadding + 2)); - sb.Append('╮'); - sb.AppendLine(); - - for (var i = contextStartLine; i <= contextEndLine; i++) - { - var line = lines[i - 1]; - - sb.Append("│ "); - sb.Append(i.ToString().PadRight(numberPadding)); - sb.Append(" │ "); - sb.Append(ApplySyntaxHighlighting(line.PadRight(codePadding), i, tokenizer.Tokens)); - // sb.Append(line.PadRight(codePadding)); - sb.Append(" │"); - sb.AppendLine(); - - if (i >= startLine && i <= endLine) - { - var markerStartColumn = 1; - var markerEndColumn = line.Length; - - if (i == startLine) - { - markerStartColumn = Span.Value.Start.Column; - } - - if (i == endLine) - { - markerEndColumn = Span.Value.End.Column; - } - - var markerLength = markerEndColumn - markerStartColumn; - var marker = new string('^', markerLength); - - var markerColor = Severity switch - { - DiagnosticSeverity.Info => ConsoleColors.Blue, - DiagnosticSeverity.Warning => ConsoleColors.Yellow, - DiagnosticSeverity.Error => ConsoleColors.Red, - _ => ConsoleColors.White - }; - - sb.Append("│ "); - sb.Append(new string(' ', numberPadding)); - sb.Append(" │ "); - sb.Append(new string(' ', markerStartColumn - 1)); - sb.Append(ConsoleColors.Colorize(marker, markerColor)); - sb.Append(new string(' ', codePadding - (markerStartColumn - 1) - markerLength)); - sb.Append(" │"); - sb.AppendLine(); - } - } - - sb.Append('╰'); - sb.Append(new string('─', numberPadding + 2)); - sb.Append('┴'); - sb.Append(new string('─', codePadding + 2)); - sb.Append('╯'); - } - - if (Help != null) - { - sb.AppendLine(); - sb.Append(ConsoleColors.Colorize($"help: {Help}", ConsoleColors.Cyan)); - } - - return sb.ToString(); - } - - private static string ApplySyntaxHighlighting(string line, int lineNumber, List tokens) - { - var sb = new StringBuilder(); - var lineTokens = tokens - .Where(t => t.Span.Start.Line == lineNumber) - .OrderBy(t => t.Span.Start.Column) - .ToList(); - - if (lineTokens.Count == 0) - { - return line; - } - - var currentColumn = 1; - - foreach (var token in lineTokens) - { - var tokenStart = token.Span.Start.Column; - var tokenEnd = token.Span.End.Column; - - if (tokenStart > currentColumn && currentColumn - 1 < line.Length) - { - var beforeLength = Math.Min(tokenStart - currentColumn, line.Length - (currentColumn - 1)); - if (beforeLength > 0) - { - var beforeToken = line.Substring(currentColumn - 1, beforeLength); - sb.Append(beforeToken); - } - } - - var tokenLength = tokenEnd - tokenStart; - if (tokenStart >= 1 && tokenStart - 1 < line.Length && tokenLength > 0) - { - var availableLength = line.Length - (tokenStart - 1); - var actualLength = Math.Min(tokenLength, availableLength); - - if (actualLength > 0) - { - var tokenText = line.Substring(tokenStart - 1, actualLength); - var coloredToken = ColorizeToken(token, tokenText); - sb.Append(coloredToken); - } - } - - currentColumn = tokenEnd; - } - - if (currentColumn - 1 < line.Length) - { - var remaining = line[(currentColumn - 1)..]; - sb.Append(remaining); - } - - return sb.ToString(); - } - - private static string ColorizeToken(Token token, string tokenText) - { - switch (token) - { - case IdentifierToken: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.BrightWhite); - } - case StringLiteralToken: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.Green); - } - case IntLiteralToken: - case FloatLiteralToken: - case BoolLiteralToken: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.Magenta); - } - case SymbolToken symbolToken: - { - switch (symbolToken.Symbol) - { - case Symbol.Func: - case Symbol.Return: - case Symbol.If: - case Symbol.Else: - case Symbol.While: - case Symbol.Break: - case Symbol.Continue: - case Symbol.Struct: - case Symbol.Let: - case Symbol.Extern: - case Symbol.For: - case Symbol.In: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.Bold + ConsoleColors.Blue); - } - case Symbol.Assign: - case Symbol.Bang: - case Symbol.Equal: - case Symbol.NotEqual: - case Symbol.LessThan: - case Symbol.LessThanOrEqual: - case Symbol.GreaterThan: - case Symbol.GreaterThanOrEqual: - case Symbol.Plus: - case Symbol.Minus: - case Symbol.Star: - case Symbol.ForwardSlash: - case Symbol.Caret: - case Symbol.Ampersand: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.Yellow); - } - case Symbol.Colon: - case Symbol.OpenParen: - case Symbol.CloseParen: - case Symbol.OpenBrace: - case Symbol.CloseBrace: - case Symbol.OpenBracket: - case Symbol.CloseBracket: - case Symbol.Comma: - case Symbol.Period: - case Symbol.Semi: - { - return ConsoleColors.Colorize(tokenText, ConsoleColors.BrightBlack); - } - } - - break; - } - } - - return tokenText; - } -} - -public enum DiagnosticSeverity -{ - Info, - Warning, - Error -} - -public static class ConsoleColors -{ - public const string Reset = "\e[0m"; - public const string Bold = "\e[1m"; - public const string Faint = "\e[2m"; - public const string Italic = "\e[3m"; - public const string Underline = "\e[4m"; - public const string SlowBlink = "\e[5m"; - public const string RapidBlink = "\e[6m"; - public const string SwapBgAndFg = "\e[7m"; - public const string Conceal = "\e[8m"; - public const string CrossedOut = "\e[9m"; - - public const string DefaultFont = "\e[10m"; - public const string AltFont1 = "\e[11m"; - public const string AltFont2 = "\e[12m"; - public const string AltFont3 = "\e[13m"; - public const string AltFont4 = "\e[14m"; - public const string AltFont5 = "\e[15m"; - public const string AltFont6 = "\e[16m"; - public const string AltFont7 = "\e[17m"; - public const string AltFont8 = "\e[18m"; - public const string AltFont9 = "\e[19m"; - - public const string Black = "\e[30m"; - public const string Red = "\e[31m"; - public const string Green = "\e[32m"; - public const string Yellow = "\e[33m"; - public const string Blue = "\e[34m"; - public const string Magenta = "\e[35m"; - public const string Cyan = "\e[36m"; - public const string White = "\e[37m"; - - public const string BrightBlack = "\e[90m"; - public const string BrightRed = "\e[91m"; - public const string BrightGreen = "\e[92m"; - public const string BrightYellow = "\e[93m"; - public const string BrightBlue = "\e[94m"; - public const string BrightMagenta = "\e[95m"; - public const string BrightCyan = "\e[96m"; - public const string BrightWhite = "\e[97m"; - - private static bool IsColorSupported() - { - var term = Environment.GetEnvironmentVariable("TERM"); - var colorTerm = Environment.GetEnvironmentVariable("COLORTERM"); - return !string.IsNullOrEmpty(term) || !string.IsNullOrEmpty(colorTerm) || !Console.IsOutputRedirected; - } - - public static string Colorize(string text, string color) - { - return IsColorSupported() ? $"{color}{text}{Reset}" : text; - } -} \ No newline at end of file diff --git a/compiler/NubLang/Diagnostics/SourceSpan.cs b/compiler/NubLang/Diagnostics/SourceSpan.cs deleted file mode 100644 index 121fe6e..0000000 --- a/compiler/NubLang/Diagnostics/SourceSpan.cs +++ /dev/null @@ -1,112 +0,0 @@ -namespace NubLang.Diagnostics; - -public readonly struct SourceSpan : IEquatable, IComparable -{ - public static SourceSpan Merge(params IEnumerable spans) - { - var spanArray = spans as SourceSpan[] ?? spans.ToArray(); - if (spanArray.Length == 0) - { - return new SourceSpan(string.Empty, new SourceLocation(0, 0), new SourceLocation(0, 0)); - } - - var minStart = spanArray.Min(s => s.Start); - var maxEnd = spanArray.Max(s => s.End); - - return new SourceSpan(spanArray[0].FilePath, minStart, maxEnd); - } - - public SourceSpan(string filePath, SourceLocation start, SourceLocation end) - { - if (start > end) - { - throw new ArgumentException("Start location cannot be after end location"); - } - - FilePath = filePath; - Start = start; - End = end; - } - - public string FilePath { get; } - public SourceLocation Start { get; } - public SourceLocation End { get; } - - public override string ToString() - { - if (Start == End) - { - return $"{FilePath}:{Start}"; - } - - if (Start.Line == End.Line) - { - return Start.Column == End.Column ? $"{FilePath}:{Start}" : $"{FilePath}:{Start.Line}:{Start.Column}-{End.Column}"; - } - - return $"{FilePath}:{Start}-{End}"; - } - - public bool Equals(SourceSpan other) => Start == other.Start && End == other.End; - public override bool Equals(object? obj) => obj is SourceSpan other && Equals(other); - public override int GetHashCode() => HashCode.Combine(typeof(SourceSpan), Start, End); - - public static bool operator ==(SourceSpan left, SourceSpan right) => Equals(left, right); - public static bool operator !=(SourceSpan left, SourceSpan right) => !Equals(left, right); - - public static bool operator <(SourceSpan left, SourceSpan right) => left.CompareTo(right) < 0; - public static bool operator <=(SourceSpan left, SourceSpan right) => left.CompareTo(right) <= 0; - public static bool operator >(SourceSpan left, SourceSpan right) => left.CompareTo(right) > 0; - public static bool operator >=(SourceSpan left, SourceSpan right) => left.CompareTo(right) >= 0; - - public int CompareTo(SourceSpan other) - { - var startComparison = Start.CompareTo(other.Start); - return startComparison != 0 ? startComparison : End.CompareTo(other.End); - } -} - -public readonly struct SourceLocation : IEquatable, IComparable -{ - public SourceLocation(int line, int column) - { - Line = line; - Column = column; - } - - public int Line { get; } - public int Column { get; } - - public override string ToString() - { - return $"{Line}:{Column}"; - } - - public override bool Equals(object? obj) - { - return obj is SourceLocation other && Equals(other); - } - - public bool Equals(SourceLocation other) - { - return Line == other.Line && Column == other.Column; - } - - public override int GetHashCode() - { - return HashCode.Combine(typeof(SourceLocation), Line, Column); - } - - public static bool operator ==(SourceLocation left, SourceLocation right) => Equals(left, right); - public static bool operator !=(SourceLocation left, SourceLocation right) => !Equals(left, right); - public static bool operator <(SourceLocation left, SourceLocation right) => left.Line < right.Line || (left.Line == right.Line && left.Column < right.Column); - public static bool operator >(SourceLocation left, SourceLocation right) => left.Line > right.Line || (left.Line == right.Line && left.Column > right.Column); - public static bool operator <=(SourceLocation left, SourceLocation right) => left.Line <= right.Line || (left.Line == right.Line && left.Column <= right.Column); - public static bool operator >=(SourceLocation left, SourceLocation right) => left.Line >= right.Line || (left.Line == right.Line && left.Column >= right.Column); - - public int CompareTo(SourceLocation other) - { - var lineComparison = Line.CompareTo(other.Line); - return lineComparison != 0 ? lineComparison : Column.CompareTo(other.Column); - } -} \ No newline at end of file diff --git a/compiler/NubLang/Generation/CType.cs b/compiler/NubLang/Generation/CType.cs deleted file mode 100644 index 9fe4287..0000000 --- a/compiler/NubLang/Generation/CType.cs +++ /dev/null @@ -1,97 +0,0 @@ -using NubLang.Ast; - -namespace NubLang.Generation; - -public static class CType -{ - public static string Create(NubType type, string? variableName = null, bool constArraysAsPointers = true) - { - return type switch - { - NubVoidType => "void" + (variableName != null ? $" {variableName}" : ""), - NubBoolType => "bool" + (variableName != null ? $" {variableName}" : ""), - NubIntType intType => CreateIntType(intType, variableName), - NubFloatType floatType => CreateFloatType(floatType, variableName), - NubPointerType ptr => CreatePointerType(ptr, variableName), - NubSliceType => "struct nub_slice" + (variableName != null ? $" {variableName}" : ""), - NubStringType => "struct nub_string" + (variableName != null ? $" {variableName}" : ""), - NubConstArrayType arr => CreateConstArrayType(arr, variableName, constArraysAsPointers), - NubArrayType arr => CreateArrayType(arr, variableName), - NubFuncType fn => CreateFuncType(fn, variableName), - NubStructType st => $"struct {st.Module}_{st.Name}_{NameMangler.Mangle(st)}" + (variableName != null ? $" {variableName}" : ""), - _ => throw new NotSupportedException($"C type generation not supported for: {type}") - }; - } - - private static string CreateIntType(NubIntType intType, string? varName) - { - var cType = intType.Width switch - { - 8 => intType.Signed ? "char" : "unsigned char", - 16 => intType.Signed ? "short" : "unsigned short", - 32 => intType.Signed ? "int" : "unsigned int", - 64 => intType.Signed ? "long long" : "unsigned long long", - _ => throw new NotSupportedException($"Unsupported integer width: {intType.Width}") - }; - return cType + (varName != null ? $" {varName}" : ""); - } - - private static string CreateFloatType(NubFloatType floatType, string? varName) - { - var cType = floatType.Width switch - { - 32 => "float", - 64 => "double", - _ => throw new NotSupportedException($"Unsupported float width: {floatType.Width}") - }; - return cType + (varName != null ? $" {varName}" : ""); - } - - private static string CreatePointerType(NubPointerType ptr, string? varName) - { - var baseType = Create(ptr.BaseType); - return baseType + "*" + (varName != null ? $" {varName}" : ""); - } - - private static string CreateConstArrayType(NubConstArrayType arr, string? varName, bool inStructDef) - { - var elementType = Create(arr.ElementType); - - // Treat const arrays as pointers unless in a struct definition - if (!inStructDef) - { - return elementType + "*" + (varName != null ? $" {varName}" : ""); - } - - if (varName != null) - { - return $"{elementType} {varName}[{arr.Size}]"; - } - - return $"{elementType}[{arr.Size}]"; - } - - private static string CreateArrayType(NubArrayType arr, string? varName) - { - var elementType = Create(arr.ElementType); - return elementType + "*" + (varName != null ? $" {varName}" : ""); - } - - private static string CreateFuncType(NubFuncType fn, string? varName) - { - var returnType = Create(fn.ReturnType); - var parameters = string.Join(", ", fn.Parameters.Select(p => Create(p))); - - if (string.IsNullOrEmpty(parameters)) - { - parameters = "void"; - } - - if (varName != null) - { - return $"{returnType} (*{varName})({parameters})"; - } - - return $"{returnType} (*)({parameters})"; - } -} \ No newline at end of file diff --git a/compiler/NubLang/Generation/Generator.cs b/compiler/NubLang/Generation/Generator.cs deleted file mode 100644 index e7fc18e..0000000 --- a/compiler/NubLang/Generation/Generator.cs +++ /dev/null @@ -1,590 +0,0 @@ -using System.Diagnostics; -using System.Text; -using NubLang.Ast; -using NubLang.Syntax; - -namespace NubLang.Generation; - -public class Generator -{ - private readonly CompilationUnit _compilationUnit; - private readonly IndentedTextWriter _writer; - private readonly Stack> _deferStack = []; - private int _tmpIndex; - - public Generator(CompilationUnit compilationUnit) - { - _compilationUnit = compilationUnit; - _writer = new IndentedTextWriter(); - } - - // todo(nub31): Handle name collisions - private string NewTmp() - { - return $"_t{++_tmpIndex}"; - } - - private static string FuncName(string module, string name, string? externSymbol) - { - return externSymbol ?? $"{module}_{name}"; - } - - public string Emit() - { - _writer.WriteLine(""" - struct nub_string - { - unsigned long long length; - char *data; - }; - - struct nub_slice - { - unsigned long long length; - void *data; - }; - - """); - - foreach (var structType in _compilationUnit.ImportedStructTypes) - { - _writer.WriteLine(CType.Create(structType)); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - foreach (var field in structType.Fields) - { - _writer.WriteLine($"{CType.Create(field.Type, field.Name, constArraysAsPointers: false)};"); - } - } - - _writer.WriteLine("};"); - _writer.WriteLine(); - } - - // note(nub31): Forward declarations - foreach (var prototype in _compilationUnit.ImportedFunctions) - { - EmitLine(prototype.Tokens.FirstOrDefault()); - var parameters = prototype.Parameters.Count != 0 - ? string.Join(", ", prototype.Parameters.Select(x => CType.Create(x.Type, x.Name))) - : "void"; - - var name = FuncName(prototype.Module, prototype.Name, prototype.ExternSymbol); - _writer.WriteLine($"{CType.Create(prototype.ReturnType, name)}({parameters});"); - _writer.WriteLine(); - } - - // note(nub31): Normal functions - foreach (var funcNode in _compilationUnit.Functions) - { - if (funcNode.Body == null) continue; - - EmitLine(funcNode.Tokens.FirstOrDefault()); - var parameters = funcNode.Prototype.Parameters.Count != 0 - ? string.Join(", ", funcNode.Prototype.Parameters.Select(x => CType.Create(x.Type, x.Name))) - : "void"; - - var name = FuncName(funcNode.Module, funcNode.Name, funcNode.Prototype.ExternSymbol); - _writer.WriteLine($"{CType.Create(funcNode.Prototype.ReturnType, name)}({parameters})"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - EmitBlock(funcNode.Body); - } - - _writer.WriteLine("}"); - _writer.WriteLine(); - } - - return _writer.ToString(); - } - - private void EmitStatement(StatementNode statementNode) - { - EmitLine(statementNode.Tokens.FirstOrDefault()); - switch (statementNode) - { - case AssignmentNode assignmentNode: - EmitAssignment(assignmentNode); - break; - case BlockNode blockNode: - _writer.WriteLine("{"); - using (_writer.Indent()) - { - EmitBlock(blockNode); - } - - _writer.WriteLine("}"); - break; - case BreakNode breakNode: - EmitBreak(breakNode); - break; - case ContinueNode continueNode: - EmitContinue(continueNode); - break; - case DeferNode deferNode: - EmitDefer(deferNode); - break; - case ForConstArrayNode forConstArrayNode: - EmitForConstArray(forConstArrayNode); - break; - case ForSliceNode forSliceNode: - EmitForSlice(forSliceNode); - break; - case IfNode ifNode: - EmitIf(ifNode); - break; - case ReturnNode returnNode: - EmitReturn(returnNode); - break; - case StatementFuncCallNode statementFuncCallNode: - EmitStatementFuncCall(statementFuncCallNode); - break; - case VariableDeclarationNode variableDeclarationNode: - EmitVariableDeclaration(variableDeclarationNode); - break; - case WhileNode whileNode: - EmitWhile(whileNode); - break; - default: - throw new ArgumentOutOfRangeException(nameof(statementNode)); - } - } - - private void EmitLine(Token? token) - { - if (token == null) return; - var file = token.Span.FilePath; - var line = token.Span.Start.Line; - _writer.WriteLine($"#line {line} \"{file}\""); - } - - private void EmitAssignment(AssignmentNode assignmentNode) - { - var target = EmitExpression(assignmentNode.Target); - var value = EmitExpression(assignmentNode.Value); - _writer.WriteLine($"{target} = {value};"); - } - - private void EmitBreak(BreakNode _) - { - // todo(nub31): Emit deferred statements - _writer.WriteLine("break;"); - } - - private void EmitContinue(ContinueNode _) - { - // todo(nub31): Emit deferred statements - _writer.WriteLine("continue;"); - } - - private void EmitDefer(DeferNode deferNode) - { - _deferStack.Peek().Add(deferNode); - } - - private void EmitForSlice(ForSliceNode forSliceNode) - { - var targetType = (NubSliceType)forSliceNode.Target.Type; - var target = EmitExpression(forSliceNode.Target); - var indexName = forSliceNode.IndexName ?? NewTmp(); - - _writer.WriteLine($"for (unsigned long long {indexName} = 0; {indexName} < {target}.length; ++{indexName})"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - _writer.WriteLine($"{CType.Create(targetType.ElementType, forSliceNode.ElementName)} = (({CType.Create(targetType.ElementType)}*){target}.data)[{indexName}];"); - EmitBlock(forSliceNode.Body); - } - - _writer.WriteLine("}"); - } - - private void EmitForConstArray(ForConstArrayNode forConstArrayNode) - { - var targetType = (NubConstArrayType)forConstArrayNode.Target.Type; - var target = EmitExpression(forConstArrayNode.Target); - var indexName = forConstArrayNode.IndexName ?? NewTmp(); - - _writer.WriteLine($"for (unsigned long long {indexName} = 0; {indexName} < {targetType.Size}; ++{indexName})"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - _writer.WriteLine($"{CType.Create(targetType.ElementType, forConstArrayNode.ElementName)} = {target}[{indexName}];"); - EmitBlock(forConstArrayNode.Body); - } - - _writer.WriteLine("}"); - } - - private void EmitIf(IfNode ifNode, bool elseIf = false) - { - var condition = EmitExpression(ifNode.Condition); - _writer.WriteLine($"{(elseIf ? "else " : "")}if ({condition})"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - EmitBlock(ifNode.Body); - } - - _writer.WriteLine("}"); - ifNode.Else?.Match - ( - elseIfNode => EmitIf(elseIfNode, true), - elseNode => - { - _writer.WriteLine("else"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - EmitBlock(elseNode); - } - - _writer.WriteLine("}"); - } - ); - } - - private void EmitReturn(ReturnNode returnNode) - { - if (returnNode.Value == null) - { - var blockDefers = _deferStack.Peek(); - for (var i = blockDefers.Count - 1; i >= 0; i--) - { - EmitStatement(blockDefers[i].Statement); - } - - _writer.WriteLine("return;"); - } - else - { - var returnValue = EmitExpression(returnNode.Value); - - if (_deferStack.Peek().Count != 0) - { - var tmp = NewTmp(); - _writer.WriteLine($"{CType.Create(returnNode.Value.Type, tmp)} = {returnValue};"); - - var blockDefers = _deferStack.Peek(); - for (var i = blockDefers.Count - 1; i >= 0; i--) - { - EmitStatement(blockDefers[i].Statement); - } - - EmitLine(returnNode.Tokens.FirstOrDefault()); - _writer.WriteLine($"return {tmp};"); - } - else - { - EmitLine(returnNode.Tokens.FirstOrDefault()); - _writer.WriteLine($"return {returnValue};"); - } - } - } - - private void EmitStatementFuncCall(StatementFuncCallNode statementFuncCallNode) - { - var funcCall = EmitFuncCall(statementFuncCallNode.FuncCall); - _writer.WriteLine($"{funcCall};"); - } - - private void EmitVariableDeclaration(VariableDeclarationNode variableDeclarationNode) - { - if (variableDeclarationNode.Assignment != null) - { - var value = EmitExpression(variableDeclarationNode.Assignment); - _writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.Name)} = {value};"); - } - else - { - _writer.WriteLine($"{CType.Create(variableDeclarationNode.Type, variableDeclarationNode.Name)};"); - } - } - - private void EmitWhile(WhileNode whileNode) - { - var condition = EmitExpression(whileNode.Condition); - _writer.WriteLine($"while ({condition})"); - _writer.WriteLine("{"); - using (_writer.Indent()) - { - EmitBlock(whileNode.Body); - } - - _writer.WriteLine("}"); - } - - private string EmitExpression(ExpressionNode expressionNode) - { - if (expressionNode is IntermediateExpression) - { - throw new UnreachableException("Type checker fucked up"); - } - - var expr = expressionNode switch - { - ArrayIndexAccessNode arrayIndexAccessNode => EmitArrayIndexAccess(arrayIndexAccessNode), - ArrayInitializerNode arrayInitializerNode => EmitArrayInitializer(arrayInitializerNode), - BinaryExpressionNode binaryExpressionNode => EmitBinaryExpression(binaryExpressionNode), - BoolLiteralNode boolLiteralNode => boolLiteralNode.Value ? "true" : "false", - ConstArrayIndexAccessNode constArrayIndexAccessNode => EmitConstArrayIndexAccess(constArrayIndexAccessNode), - ConstArrayInitializerNode constArrayInitializerNode => EmitConstArrayInitializer(constArrayInitializerNode), - CStringLiteralNode cStringLiteralNode => $"\"{cStringLiteralNode.Value}\"", - DereferenceNode dereferenceNode => EmitDereference(dereferenceNode), - Float32LiteralNode float32LiteralNode => EmitFloat32Literal(float32LiteralNode), - Float64LiteralNode float64LiteralNode => EmitFloat64Literal(float64LiteralNode), - CastNode castNode => EmitCast(castNode), - FuncCallNode funcCallNode => EmitFuncCall(funcCallNode), - FuncIdentifierNode funcIdentifierNode => FuncName(funcIdentifierNode.Module, funcIdentifierNode.Name, funcIdentifierNode.ExternSymbol), - AddressOfNode addressOfNode => EmitAddressOf(addressOfNode), - SizeNode sizeBuiltinNode => $"sizeof({CType.Create(sizeBuiltinNode.TargetType)})", - SliceIndexAccessNode sliceIndexAccessNode => EmitSliceArrayIndexAccess(sliceIndexAccessNode), - StringLiteralNode stringLiteralNode => EmitStringLiteral(stringLiteralNode), - StructFieldAccessNode structFieldAccessNode => EmitStructFieldAccess(structFieldAccessNode), - StructInitializerNode structInitializerNode => EmitStructInitializer(structInitializerNode), - I8LiteralNode i8LiteralNode => EmitI8Literal(i8LiteralNode), - I16LiteralNode i16LiteralNode => EmitI16Literal(i16LiteralNode), - I32LiteralNode i32LiteralNode => EmitI32Literal(i32LiteralNode), - I64LiteralNode i64LiteralNode => EmitI64Literal(i64LiteralNode), - U8LiteralNode u8LiteralNode => EmitU8Literal(u8LiteralNode), - U16LiteralNode u16LiteralNode => EmitU16Literal(u16LiteralNode), - U32LiteralNode u32LiteralNode => EmitU32Literal(u32LiteralNode), - U64LiteralNode u64LiteralNode => EmitU64Literal(u64LiteralNode), - UnaryExpressionNode unaryExpressionNode => EmitUnaryExpression(unaryExpressionNode), - VariableIdentifierNode variableIdentifierNode => variableIdentifierNode.Name, - _ => throw new ArgumentOutOfRangeException(nameof(expressionNode)) - }; - - return $"({expr})"; - } - - private string EmitArrayIndexAccess(ArrayIndexAccessNode arrayIndexAccessNode) - { - var target = EmitExpression(arrayIndexAccessNode.Target); - var index = EmitExpression(arrayIndexAccessNode.Index); - return $"{target}[{index}]"; - } - - private string EmitArrayInitializer(ArrayInitializerNode arrayInitializerNode) - { - var values = new List(); - foreach (var value in arrayInitializerNode.Values) - { - values.Add(EmitExpression(value)); - } - - var arrayType = (NubArrayType)arrayInitializerNode.Type; - return $"({CType.Create(arrayType.ElementType)}[]){{{string.Join(", ", values)}}}"; - } - - private string EmitBinaryExpression(BinaryExpressionNode binaryExpressionNode) - { - var left = EmitExpression(binaryExpressionNode.Left); - var right = EmitExpression(binaryExpressionNode.Right); - - var op = binaryExpressionNode.Operator switch - { - BinaryOperator.Plus => "+", - BinaryOperator.Minus => "-", - BinaryOperator.Multiply => "*", - BinaryOperator.Divide => "/", - BinaryOperator.Modulo => "%", - BinaryOperator.Equal => "==", - BinaryOperator.NotEqual => "!=", - BinaryOperator.LessThan => "<", - BinaryOperator.LessThanOrEqual => "<=", - BinaryOperator.GreaterThan => ">", - BinaryOperator.GreaterThanOrEqual => ">=", - BinaryOperator.LogicalAnd => "&&", - BinaryOperator.LogicalOr => "||", - BinaryOperator.BitwiseAnd => "&", - BinaryOperator.BitwiseOr => "|", - BinaryOperator.BitwiseXor => "^", - BinaryOperator.LeftShift => "<<", - BinaryOperator.RightShift => ">>", - _ => throw new ArgumentOutOfRangeException() - }; - - return $"{left} {op} {right}"; - } - - private string EmitConstArrayIndexAccess(ConstArrayIndexAccessNode constArrayIndexAccessNode) - { - var target = EmitExpression(constArrayIndexAccessNode.Target); - var index = EmitExpression(constArrayIndexAccessNode.Index); - // todo(nub31): We can emit bounds checking here - return $"{target}[{index}]"; - } - - private string EmitConstArrayInitializer(ConstArrayInitializerNode arrayInitializerNode) - { - var values = new List(); - foreach (var value in arrayInitializerNode.Values) - { - values.Add(EmitExpression(value)); - } - - var arrayType = (NubConstArrayType)arrayInitializerNode.Type; - return $"({CType.Create(arrayType.ElementType)}[{arrayType.Size}]){{{string.Join(", ", values)}}}"; - } - - private string EmitDereference(DereferenceNode dereferenceNode) - { - var pointer = EmitExpression(dereferenceNode.Target); - return $"*{pointer}"; - } - - private string EmitFloat32Literal(Float32LiteralNode float32LiteralNode) - { - var str = float32LiteralNode.Value.ToString("G9", System.Globalization.CultureInfo.InvariantCulture); - if (!str.Contains('.') && !str.Contains('e') && !str.Contains('E')) - { - str += ".0"; - } - - return str + "f"; - } - - private string EmitFloat64Literal(Float64LiteralNode float64LiteralNode) - { - var str = float64LiteralNode.Value.ToString("G17", System.Globalization.CultureInfo.InvariantCulture); - if (!str.Contains('.') && !str.Contains('e') && !str.Contains('E')) - { - str += ".0"; - } - - return str; - } - - private string EmitCast(CastNode castNode) - { - var value = EmitExpression(castNode.Value); - - if (castNode is { Type: NubSliceType sliceType, Value.Type: NubConstArrayType arrayType }) - { - return $"({CType.Create(sliceType)}){{.length = {arrayType.Size}, .data = (void*){value}}}"; - } - - return $"({CType.Create(castNode.Type)}){value}"; - } - - private string EmitFuncCall(FuncCallNode funcCallNode) - { - var name = EmitExpression(funcCallNode.Expression); - var parameterNames = funcCallNode.Parameters.Select(EmitExpression).ToList(); - return $"{name}({string.Join(", ", parameterNames)})"; - } - - private string EmitAddressOf(AddressOfNode addressOfNode) - { - var value = EmitExpression(addressOfNode.LValue); - return $"&{value}"; - } - - private string EmitSliceArrayIndexAccess(SliceIndexAccessNode sliceIndexAccessNode) - { - var targetType = (NubSliceType)sliceIndexAccessNode.Target.Type; - var target = EmitExpression(sliceIndexAccessNode.Target); - var index = EmitExpression(sliceIndexAccessNode.Index); - // todo(nub31): We can emit bounds checking here - return $"(({CType.Create(targetType.ElementType)}*){target}.data)[{index}]"; - } - - private string EmitStringLiteral(StringLiteralNode stringLiteralNode) - { - var length = Encoding.UTF8.GetByteCount(stringLiteralNode.Value); - return $"(nub_string){{.length = {length}, .data = \"{stringLiteralNode.Value}\"}}"; - } - - private string EmitStructFieldAccess(StructFieldAccessNode structFieldAccessNode) - { - var structExpr = EmitExpression(structFieldAccessNode.Target); - return $"{structExpr}.{structFieldAccessNode.Field}"; - } - - private string EmitStructInitializer(StructInitializerNode structInitializerNode) - { - var initValues = new List(); - foreach (var initializer in structInitializerNode.Initializers) - { - var value = EmitExpression(initializer.Value); - initValues.Add($".{initializer.Key} = {value}"); - } - - var initString = initValues.Count == 0 - ? "0" - : string.Join(", ", initValues); - - return $"({CType.Create(structInitializerNode.Type)}){{{initString}}}"; - } - - private string EmitI8Literal(I8LiteralNode i8LiteralNode) - { - return i8LiteralNode.Value.ToString(); - } - - private string EmitI16Literal(I16LiteralNode i16LiteralNode) - { - return i16LiteralNode.Value.ToString(); - } - - private string EmitI32Literal(I32LiteralNode i32LiteralNode) - { - return i32LiteralNode.Value.ToString(); - } - - private string EmitI64Literal(I64LiteralNode i64LiteralNode) - { - return i64LiteralNode.Value + "LL"; - } - - private string EmitU8Literal(U8LiteralNode u8LiteralNode) - { - return u8LiteralNode.Value.ToString(); - } - - private string EmitU16Literal(U16LiteralNode u16LiteralNode) - { - return u16LiteralNode.Value.ToString(); - } - - private string EmitU32Literal(U32LiteralNode u32LiteralNode) - { - return u32LiteralNode.Value.ToString(); - } - - private string EmitU64Literal(U64LiteralNode u64LiteralNode) - { - return u64LiteralNode.Value + "ULL"; - } - - private string EmitUnaryExpression(UnaryExpressionNode unaryExpressionNode) - { - var value = EmitExpression(unaryExpressionNode.Operand); - - return unaryExpressionNode.Operator switch - { - UnaryOperator.Negate => $"-{value}", - UnaryOperator.Invert => $"!{value}", - _ => throw new ArgumentOutOfRangeException() - }; - } - - private void EmitBlock(BlockNode blockNode) - { - _deferStack.Push([]); - - foreach (var statementNode in blockNode.Statements) - { - EmitStatement(statementNode); - } - - var blockDefers = _deferStack.Pop(); - for (var i = blockDefers.Count - 1; i >= 0; i--) - { - EmitStatement(blockDefers[i].Statement); - } - } -} \ No newline at end of file diff --git a/compiler/NubLang/Generation/IndentedTextWriter.cs b/compiler/NubLang/Generation/IndentedTextWriter.cs deleted file mode 100644 index 5ec5274..0000000 --- a/compiler/NubLang/Generation/IndentedTextWriter.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Text; - -namespace NubLang.Generation; - -internal class IndentedTextWriter -{ - private readonly StringBuilder _builder = new(); - private int _indentLevel; - - public IDisposable Indent() - { - _indentLevel++; - return new IndentScope(this); - } - - public void WriteLine(string text) - { - WriteIndent(); - _builder.AppendLine(text); - } - - public void Write(string text) - { - WriteIndent(); - _builder.Append(text); - } - - public void WriteLine() - { - _builder.AppendLine(); - } - - public override string ToString() - { - return _builder.ToString(); - } - - private void WriteIndent() - { - if (_builder.Length > 0) - { - var lastChar = _builder[^1]; - if (lastChar != '\n' && lastChar != '\r') - return; - } - - for (var i = 0; i < _indentLevel; i++) - { - _builder.Append(" "); - } - } - - private class IndentScope : IDisposable - { - private readonly IndentedTextWriter _writer; - private bool _disposed; - - public IndentScope(IndentedTextWriter writer) - { - _writer = writer; - } - - public void Dispose() - { - if (_disposed) return; - _writer._indentLevel--; - _disposed = true; - } - } -} \ No newline at end of file diff --git a/compiler/NubLang/Syntax/Module.cs b/compiler/NubLang/Syntax/Module.cs deleted file mode 100644 index b5776ae..0000000 --- a/compiler/NubLang/Syntax/Module.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace NubLang.Syntax; - -public sealed class Module -{ - public static Dictionary Collect(List syntaxTrees) - { - var modules = new Dictionary(); - foreach (var syntaxTree in syntaxTrees) - { - if (!modules.TryGetValue(syntaxTree.ModuleName, out var module)) - { - module = new Module(); - modules.Add(syntaxTree.ModuleName, module); - } - - module._definitions.AddRange(syntaxTree.Definitions); - } - - return modules; - } - - private readonly List _definitions = []; - - public List Structs(bool includePrivate) - { - return _definitions - .OfType() - .Where(x => x.Exported || includePrivate) - .ToList(); - } - - public List Functions(bool includePrivate) - { - return _definitions - .OfType() - .Where(x => x.Exported || includePrivate) - .ToList(); - } - - public List Enums(bool includePrivate) - { - return _definitions - .OfType() - .Where(x => x.Exported || includePrivate) - .ToList(); - } -} \ No newline at end of file diff --git a/compiler/NubLang/Syntax/Parser.cs b/compiler/NubLang/Syntax/Parser.cs deleted file mode 100644 index b6aacd6..0000000 --- a/compiler/NubLang/Syntax/Parser.cs +++ /dev/null @@ -1,951 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using NubLang.Diagnostics; - -namespace NubLang.Syntax; - -public sealed class Parser -{ - private List _tokens = []; - private int _tokenIndex; - - private Token? CurrentToken => _tokenIndex < _tokens.Count ? _tokens[_tokenIndex] : null; - private bool HasToken => CurrentToken != null; - - public List Diagnostics { get; } = []; - - public SyntaxTree Parse(List tokens) - { - Diagnostics.Clear(); - _tokens = tokens; - _tokenIndex = 0; - - string? moduleName = null; - var imports = new List(); - var definitions = new List(); - - while (HasToken) - { - try - { - var startIndex = _tokenIndex; - - if (TryExpectSymbol(Symbol.Import)) - { - var name = ExpectStringLiteral(); - if (imports.Contains(name.Value)) - { - Diagnostics.Add(Diagnostic - .Warning($"Module {name.Value} is imported twice") - .At(name) - .WithHelp($"Remove duplicate import \"{name.Value}\"") - .Build()); - } - else - { - imports.Add(name.Value); - } - - continue; - } - - if (TryExpectSymbol(Symbol.Module)) - { - if (moduleName != null) - { - throw new ParseException(Diagnostic - .Error("Module is declared more than once") - .At(CurrentToken) - .WithHelp("Remove duplicate module declaration") - .Build()); - } - - moduleName = ExpectStringLiteral().Value; - continue; - } - - var exported = TryExpectSymbol(Symbol.Export); - - if (TryExpectSymbol(Symbol.Extern)) - { - var externSymbol = ExpectStringLiteral(); - ExpectSymbol(Symbol.Func); - definitions.Add(ParseFunc(startIndex, exported, externSymbol.Value)); - continue; - } - - var keyword = ExpectSymbol(); - DefinitionSyntax definition = keyword.Symbol switch - { - Symbol.Func => ParseFunc(startIndex, exported, null), - Symbol.Struct => ParseStruct(startIndex, exported), - Symbol.Enum => ParseEnum(startIndex, exported), - _ => throw new ParseException(Diagnostic - .Error($"Expected 'func', 'struct', 'enum', 'import' or 'module' but found '{keyword.Symbol}'") - .WithHelp("Valid top level statements are 'func', 'struct', 'enum', 'import' and 'module'") - .At(keyword) - .Build()) - }; - - definitions.Add(definition); - } - catch (ParseException e) - { - Diagnostics.Add(e.Diagnostic); - while (HasToken) - { - if (CurrentToken is SymbolToken { Symbol: Symbol.Extern or Symbol.Func or Symbol.Struct }) - { - break; - } - - Next(); - } - } - } - - return new SyntaxTree(definitions, moduleName ?? "default", imports); - } - - private FuncParameterSyntax ParseFuncParameter() - { - var startIndex = _tokenIndex; - var name = ExpectIdentifier(); - ExpectSymbol(Symbol.Colon); - var type = ParseType(); - - return new FuncParameterSyntax(GetTokens(startIndex), name.Value, type); - } - - private FuncSyntax ParseFunc(int startIndex, bool exported, string? externSymbol) - { - var name = ExpectIdentifier(); - List parameters = []; - - ExpectSymbol(Symbol.OpenParen); - - while (!TryExpectSymbol(Symbol.CloseParen)) - { - parameters.Add(ParseFuncParameter()); - - if (!TryExpectSymbol(Symbol.Comma)) - { - ExpectSymbol(Symbol.CloseParen); - break; - } - } - - var returnType = TryExpectSymbol(Symbol.Colon) ? ParseType() : new VoidTypeSyntax([]); - - var prototype = new FuncPrototypeSyntax(GetTokens(startIndex), name.Value, exported, externSymbol, parameters, returnType); - - BlockSyntax? body = null; - var bodyStartIndex = _tokenIndex; - if (TryExpectSymbol(Symbol.OpenBrace)) - { - body = ParseBlock(bodyStartIndex); - } - - return new FuncSyntax(GetTokens(startIndex), prototype, body); - } - - private StructSyntax ParseStruct(int startIndex, bool exported) - { - var name = ExpectIdentifier(); - - ExpectSymbol(Symbol.OpenBrace); - - List fields = []; - - while (!TryExpectSymbol(Symbol.CloseBrace)) - { - var memberStartIndex = _tokenIndex; - - var fieldName = ExpectIdentifier().Value; - ExpectSymbol(Symbol.Colon); - var fieldType = ParseType(); - - ExpressionSyntax? fieldValue = null; - - if (TryExpectSymbol(Symbol.Assign)) - { - fieldValue = ParseExpression(); - } - - fields.Add(new StructFieldSyntax(GetTokens(memberStartIndex), fieldName, fieldType, fieldValue)); - } - - return new StructSyntax(GetTokens(startIndex), name.Value, exported, fields); - } - - private EnumSyntax ParseEnum(int startIndex, bool exported) - { - var name = ExpectIdentifier(); - - TypeSyntax? type = null; - - if (TryExpectSymbol(Symbol.Colon)) - { - type = ParseType(); - } - - List fields = []; - - ExpectSymbol(Symbol.OpenBrace); - - long value = -1; - - while (!TryExpectSymbol(Symbol.CloseBrace)) - { - var memberStartIndex = _tokenIndex; - var fieldName = ExpectIdentifier().Value; - long fieldValue; - - if (TryExpectSymbol(Symbol.Assign)) - { - if (!TryExpectIntLiteral(out var intLiteralToken)) - { - throw new ParseException(Diagnostic - .Error("Value of enum field must be an integer literal") - .At(CurrentToken) - .Build()); - } - - fieldValue = Convert.ToInt64(intLiteralToken.Value, intLiteralToken.Base); - value = fieldValue; - } - else - { - fieldValue = value + 1; - value = fieldValue; - } - - fields.Add(new EnumFieldSyntax(GetTokens(memberStartIndex), fieldName, fieldValue)); - } - - return new EnumSyntax(GetTokens(startIndex), name.Value, exported, type, fields); - } - - private StatementSyntax ParseStatement() - { - var startIndex = _tokenIndex; - - if (TryExpectSymbol(out var symbol)) - { - switch (symbol) - { - case Symbol.OpenBrace: - return ParseBlock(startIndex); - case Symbol.Return: - return ParseReturn(startIndex); - case Symbol.If: - return ParseIf(startIndex); - case Symbol.While: - return ParseWhile(startIndex); - case Symbol.For: - return ParseFor(startIndex); - case Symbol.Let: - return ParseVariableDeclaration(startIndex); - case Symbol.Defer: - return ParseDefer(startIndex); - case Symbol.Break: - return new BreakSyntax(GetTokens(startIndex)); - case Symbol.Continue: - return new ContinueSyntax(GetTokens(startIndex)); - } - } - - var expr = ParseExpression(); - - if (TryExpectSymbol(Symbol.Assign)) - { - var value = ParseExpression(); - return new AssignmentSyntax(GetTokens(startIndex), expr, value); - } - - return new StatementExpressionSyntax(GetTokens(startIndex), expr); - } - - private VariableDeclarationSyntax ParseVariableDeclaration(int startIndex) - { - var name = ExpectIdentifier().Value; - - TypeSyntax? explicitType = null; - if (TryExpectSymbol(Symbol.Colon)) - { - explicitType = ParseType(); - } - - ExpressionSyntax? assignment = null; - if (TryExpectSymbol(Symbol.Assign)) - { - assignment = ParseExpression(); - } - - return new VariableDeclarationSyntax(GetTokens(startIndex), name, explicitType, assignment); - } - - private DeferSyntax ParseDefer(int startIndex) - { - var statement = ParseStatement(); - return new DeferSyntax(GetTokens(startIndex), statement); - } - - private ReturnSyntax ParseReturn(int startIndex) - { - ExpressionSyntax? value = null; - - if (!TryExpectSymbol(Symbol.Semi)) - { - value = ParseExpression(); - } - - return new ReturnSyntax(GetTokens(startIndex), value); - } - - private IfSyntax ParseIf(int startIndex) - { - var condition = ParseExpression(); - var body = ParseBlock(); - - Variant? elseStatement = null; - - var elseStartIndex = _tokenIndex; - if (TryExpectSymbol(Symbol.Else)) - { - if (TryExpectSymbol(Symbol.If)) - { - elseStatement = (Variant)ParseIf(elseStartIndex); - } - else - { - elseStatement = (Variant)ParseBlock(); - } - } - - return new IfSyntax(GetTokens(startIndex), condition, body, elseStatement); - } - - private WhileSyntax ParseWhile(int startIndex) - { - var condition = ParseExpression(); - var body = ParseBlock(); - return new WhileSyntax(GetTokens(startIndex), condition, body); - } - - private ForSyntax ParseFor(int startIndex) - { - var itemName = ExpectIdentifier().Value; - string? indexName = null; - - if (TryExpectSymbol(Symbol.Comma)) - { - indexName = ExpectIdentifier().Value; - } - - ExpectSymbol(Symbol.In); - var target = ParseExpression(); - var body = ParseBlock(); - - return new ForSyntax(GetTokens(startIndex), itemName, indexName, target, body); - } - - private ExpressionSyntax ParseExpression(int precedence = 0) - { - var startIndex = _tokenIndex; - var left = ParsePrimaryExpression(); - - while (CurrentToken is SymbolToken symbolToken && TryGetBinaryOperator(symbolToken.Symbol, out var op) && GetBinaryOperatorPrecedence(op.Value) >= precedence) - { - Next(); - var right = ParseExpression(GetBinaryOperatorPrecedence(op.Value) + 1); - left = new BinaryExpressionSyntax(GetTokens(startIndex), left, op.Value, right); - } - - return left; - } - - private static int GetBinaryOperatorPrecedence(BinaryOperatorSyntax operatorSyntax) - { - return operatorSyntax switch - { - BinaryOperatorSyntax.Multiply => 10, - BinaryOperatorSyntax.Divide => 10, - BinaryOperatorSyntax.Modulo => 10, - - BinaryOperatorSyntax.Plus => 9, - BinaryOperatorSyntax.Minus => 9, - - BinaryOperatorSyntax.LeftShift => 8, - BinaryOperatorSyntax.RightShift => 8, - - BinaryOperatorSyntax.GreaterThan => 7, - BinaryOperatorSyntax.GreaterThanOrEqual => 7, - BinaryOperatorSyntax.LessThan => 7, - BinaryOperatorSyntax.LessThanOrEqual => 7, - - BinaryOperatorSyntax.Equal => 7, - BinaryOperatorSyntax.NotEqual => 7, - - BinaryOperatorSyntax.BitwiseAnd => 6, - BinaryOperatorSyntax.BitwiseXor => 5, - BinaryOperatorSyntax.BitwiseOr => 4, - - BinaryOperatorSyntax.LogicalAnd => 3, - BinaryOperatorSyntax.LogicalOr => 2, - - _ => throw new ArgumentOutOfRangeException(nameof(operatorSyntax), operatorSyntax, null) - }; - } - - private bool TryGetBinaryOperator(Symbol symbol, [NotNullWhen(true)] out BinaryOperatorSyntax? binaryExpressionOperator) - { - switch (symbol) - { - case Symbol.Equal: - binaryExpressionOperator = BinaryOperatorSyntax.Equal; - return true; - case Symbol.NotEqual: - binaryExpressionOperator = BinaryOperatorSyntax.NotEqual; - return true; - case Symbol.LessThan: - binaryExpressionOperator = BinaryOperatorSyntax.LessThan; - return true; - case Symbol.LessThanOrEqual: - binaryExpressionOperator = BinaryOperatorSyntax.LessThanOrEqual; - return true; - case Symbol.GreaterThan: - binaryExpressionOperator = BinaryOperatorSyntax.GreaterThan; - return true; - case Symbol.GreaterThanOrEqual: - binaryExpressionOperator = BinaryOperatorSyntax.GreaterThanOrEqual; - return true; - case Symbol.And: - binaryExpressionOperator = BinaryOperatorSyntax.LogicalAnd; - return true; - case Symbol.Or: - binaryExpressionOperator = BinaryOperatorSyntax.LogicalOr; - return true; - case Symbol.Plus: - binaryExpressionOperator = BinaryOperatorSyntax.Plus; - return true; - case Symbol.Minus: - binaryExpressionOperator = BinaryOperatorSyntax.Minus; - return true; - case Symbol.Star: - binaryExpressionOperator = BinaryOperatorSyntax.Multiply; - return true; - case Symbol.ForwardSlash: - binaryExpressionOperator = BinaryOperatorSyntax.Divide; - return true; - case Symbol.Percent: - binaryExpressionOperator = BinaryOperatorSyntax.Modulo; - return true; - case Symbol.LeftShift: - binaryExpressionOperator = BinaryOperatorSyntax.LeftShift; - return true; - case Symbol.RightShift: - binaryExpressionOperator = BinaryOperatorSyntax.RightShift; - return true; - case Symbol.Ampersand: - binaryExpressionOperator = BinaryOperatorSyntax.BitwiseAnd; - return true; - case Symbol.Pipe: - binaryExpressionOperator = BinaryOperatorSyntax.BitwiseOr; - return true; - case Symbol.Caret: - binaryExpressionOperator = BinaryOperatorSyntax.BitwiseXor; - return true; - default: - binaryExpressionOperator = null; - return false; - } - } - - private ExpressionSyntax ParsePrimaryExpression() - { - var startIndex = _tokenIndex; - var token = ExpectToken(); - var expr = token switch - { - BoolLiteralToken boolLiteral => new BoolLiteralSyntax(GetTokens(startIndex), boolLiteral.Value), - StringLiteralToken stringLiteral => new StringLiteralSyntax(GetTokens(startIndex), stringLiteral.Value), - FloatLiteralToken floatLiteral => new FloatLiteralSyntax(GetTokens(startIndex), floatLiteral.Value), - IntLiteralToken intLiteral => new IntLiteralSyntax(GetTokens(startIndex), intLiteral.Value, intLiteral.Base), - IdentifierToken identifier => ParseIdentifier(startIndex, identifier), - SymbolToken symbolToken => symbolToken.Symbol switch - { - Symbol.OpenParen => ParseParenthesizedExpression(), - Symbol.Minus => new UnaryExpressionSyntax(GetTokens(startIndex), UnaryOperatorSyntax.Negate, ParsePrimaryExpression()), - Symbol.Bang => new UnaryExpressionSyntax(GetTokens(startIndex), UnaryOperatorSyntax.Invert, ParsePrimaryExpression()), - Symbol.OpenBracket => ParseArrayInitializer(startIndex), - Symbol.OpenBrace => new StructInitializerSyntax(GetTokens(startIndex), null, ParseStructInitializerBody()), - Symbol.Struct => ParseStructInitializer(startIndex), - Symbol.At => ParseBuiltinFunction(startIndex), - _ => throw new ParseException(Diagnostic - .Error($"Unexpected symbol '{symbolToken.Symbol}' in expression") - .WithHelp("Expected '(', '-', '!', '[' or '{'") - .At(symbolToken) - .Build()) - }, - _ => throw new ParseException(Diagnostic - .Error($"Unexpected token '{token.GetType().Name}' in expression") - .WithHelp("Expected literal, identifier, or parenthesized expression") - .At(token) - .Build()) - }; - - return ParsePostfixOperators(expr); - } - - private ExpressionSyntax ParseBuiltinFunction(int startIndex) - { - var name = ExpectIdentifier(); - ExpectSymbol(Symbol.OpenParen); - - switch (name.Value) - { - case "size": - { - var type = ParseType(); - ExpectSymbol(Symbol.CloseParen); - return new SizeSyntax(GetTokens(startIndex), type); - } - case "cast": - { - var expression = ParseExpression(); - ExpectSymbol(Symbol.CloseParen); - return new CastSyntax(GetTokens(startIndex), expression); - } - default: - { - throw new ParseException(Diagnostic.Error($"Unknown builtin {name.Value}").At(name).Build()); - } - } - } - - private ExpressionSyntax ParseIdentifier(int startIndex, IdentifierToken identifier) - { - if (TryExpectSymbol(Symbol.DoubleColon)) - { - var name = ExpectIdentifier(); - return new ModuleIdentifierSyntax(GetTokens(startIndex), identifier.Value, name.Value); - } - - return new LocalIdentifierSyntax(GetTokens(startIndex), identifier.Value); - } - - private ExpressionSyntax ParseParenthesizedExpression() - { - var expression = ParseExpression(); - ExpectSymbol(Symbol.CloseParen); - return expression; - } - - private ExpressionSyntax ParsePostfixOperators(ExpressionSyntax expr) - { - var startIndex = _tokenIndex; - while (HasToken) - { - if (TryExpectSymbol(Symbol.Ampersand)) - { - expr = new AddressOfSyntax(GetTokens(startIndex), expr); - continue; - } - - if (TryExpectSymbol(Symbol.Caret)) - { - expr = new DereferenceSyntax(GetTokens(startIndex), expr); - continue; - } - - if (TryExpectSymbol(Symbol.Period)) - { - var member = ExpectIdentifier().Value; - expr = new MemberAccessSyntax(GetTokens(startIndex), expr, member); - continue; - } - - if (TryExpectSymbol(Symbol.OpenBracket)) - { - var index = ParseExpression(); - ExpectSymbol(Symbol.CloseBracket); - expr = new ArrayIndexAccessSyntax(GetTokens(startIndex), expr, index); - continue; - } - - if (TryExpectSymbol(Symbol.OpenParen)) - { - var parameters = new List(); - - while (!TryExpectSymbol(Symbol.CloseParen)) - { - parameters.Add(ParseExpression()); - if (!TryExpectSymbol(Symbol.Comma)) - { - ExpectSymbol(Symbol.CloseParen); - break; - } - } - - expr = new FuncCallSyntax(GetTokens(startIndex), expr, parameters); - continue; - } - - break; - } - - return expr; - } - - private ExpressionSyntax ParseArrayInitializer(int startIndex) - { - var values = new List(); - while (!TryExpectSymbol(Symbol.CloseBracket)) - { - values.Add(ParseExpression()); - if (!TryExpectSymbol(Symbol.Comma)) - { - ExpectSymbol(Symbol.CloseBracket); - break; - } - } - - return new ArrayInitializerSyntax(GetTokens(startIndex), values); - } - - private StructInitializerSyntax ParseStructInitializer(int startIndex) - { - TypeSyntax? type = null; - if (!TryExpectSymbol(Symbol.OpenBrace)) - { - type = ParseType(); - ExpectSymbol(Symbol.OpenBrace); - } - - var initializers = ParseStructInitializerBody(); - - return new StructInitializerSyntax(GetTokens(startIndex), type, initializers); - } - - private Dictionary ParseStructInitializerBody() - { - Dictionary initializers = []; - while (!TryExpectSymbol(Symbol.CloseBrace)) - { - var name = ExpectIdentifier().Value; - ExpectSymbol(Symbol.Assign); - var value = ParseExpression(); - initializers.Add(name, value); - } - - return initializers; - } - - private BlockSyntax ParseBlock() - { - var startIndex = _tokenIndex; - ExpectSymbol(Symbol.OpenBrace); - return ParseBlock(startIndex); - } - - private BlockSyntax ParseBlock(int startIndex) - { - List statements = []; - - while (!TryExpectSymbol(Symbol.CloseBrace)) - { - try - { - statements.Add(ParseStatement()); - } - catch (ParseException ex) - { - Diagnostics.Add(ex.Diagnostic); - if (HasToken) - { - Next(); - } - else - { - break; - } - } - } - - return new BlockSyntax(GetTokens(startIndex), statements); - } - - private TypeSyntax ParseType() - { - var startIndex = _tokenIndex; - if (TryExpectIdentifier(out var name)) - { - if (name.Value[0] == 'u' && int.TryParse(name.Value[1..], out var size)) - { - if (size is not 8 and not 16 and not 32 and not 64) - { - throw new ParseException(Diagnostic - .Error("Arbitrary uint size is not supported") - .WithHelp("Use u8, u16, u32 or u64") - .At(name) - .Build()); - } - - return new IntTypeSyntax(GetTokens(startIndex), false, size); - } - - if (name.Value[0] == 'i' && int.TryParse(name.Value[1..], out size)) - { - if (size is not 8 and not 16 and not 32 and not 64) - { - throw new ParseException(Diagnostic - .Error("Arbitrary int size is not supported") - .WithHelp("Use i8, i16, i32 or i64") - .At(name) - .Build()); - } - - return new IntTypeSyntax(GetTokens(startIndex), true, size); - } - - if (name.Value[0] == 'f' && int.TryParse(name.Value[1..], out size)) - { - if (size is not 32 and not 64) - { - throw new ParseException(Diagnostic - .Error("Arbitrary float size is not supported") - .WithHelp("Use f32 or f64") - .At(name) - .Build()); - } - - return new FloatTypeSyntax(GetTokens(startIndex), size); - } - - switch (name.Value) - { - case "void": - return new VoidTypeSyntax(GetTokens(startIndex)); - case "string": - return new StringTypeSyntax(GetTokens(startIndex)); - case "bool": - return new BoolTypeSyntax(GetTokens(startIndex)); - default: - { - string? module = null; - - if (TryExpectSymbol(Symbol.DoubleColon)) - { - var customTypeName = ExpectIdentifier(); - module = name.Value; - name = customTypeName; - } - - return new CustomTypeSyntax(GetTokens(startIndex), module, name.Value); - } - } - } - - if (TryExpectSymbol(Symbol.Caret)) - { - var baseType = ParseType(); - return new PointerTypeSyntax(GetTokens(startIndex), baseType); - } - - if (TryExpectSymbol(Symbol.Func)) - { - ExpectSymbol(Symbol.OpenParen); - - List parameters = []; - while (!TryExpectSymbol(Symbol.CloseParen)) - { - parameters.Add(ParseType()); - if (!TryExpectSymbol(Symbol.Comma)) - { - ExpectSymbol(Symbol.CloseParen); - break; - } - } - - var returnType = TryExpectSymbol(Symbol.Colon) - ? ParseType() - : new VoidTypeSyntax([]); - - return new FuncTypeSyntax(GetTokens(startIndex), parameters, returnType); - } - - if (TryExpectSymbol(Symbol.OpenBracket)) - { - if (TryExpectIntLiteral(out var intLiteral)) - { - ExpectSymbol(Symbol.CloseBracket); - var baseType = ParseType(); - return new ConstArrayTypeSyntax(GetTokens(startIndex), baseType, Convert.ToInt64(intLiteral.Value, intLiteral.Base)); - } - else if (TryExpectSymbol(Symbol.QuestionMark)) - { - ExpectSymbol(Symbol.CloseBracket); - var baseType = ParseType(); - return new ArrayTypeSyntax(GetTokens(startIndex), baseType); - } - else - { - ExpectSymbol(Symbol.CloseBracket); - var baseType = ParseType(); - return new SliceTypeSyntax(GetTokens(startIndex), baseType); - } - } - - throw new ParseException(Diagnostic - .Error("Invalid type syntax") - .WithHelp("Expected type name, '^' for pointer, or '[]' for array") - .At(CurrentToken) - .Build()); - } - - private Token ExpectToken() - { - if (!HasToken) - { - throw new ParseException(Diagnostic - .Error("Unexpected end of file") - .WithHelp("Expected more tokens to complete the syntax") - .At(_tokens[^1]) - .Build()); - } - - var token = CurrentToken!; - Next(); - return token; - } - - private SymbolToken ExpectSymbol() - { - var token = ExpectToken(); - if (token is not SymbolToken symbol) - { - throw new ParseException(Diagnostic - .Error($"Expected symbol, but found {token.GetType().Name}") - .WithHelp("This position requires a symbol like '(', ')', '{', '}', etc.") - .At(token) - .Build()); - } - - return symbol; - } - - private void ExpectSymbol(Symbol expectedSymbol) - { - var token = ExpectSymbol(); - if (token.Symbol != expectedSymbol) - { - throw new ParseException(Diagnostic - .Error($"Expected '{expectedSymbol}', but found '{token.Symbol}'") - .WithHelp($"Insert '{expectedSymbol}' here") - .At(token) - .Build()); - } - } - - private bool TryExpectSymbol(out Symbol symbol) - { - if (CurrentToken is SymbolToken symbolToken) - { - Next(); - symbol = symbolToken.Symbol; - return true; - } - - symbol = default; - return false; - } - - private bool TryExpectSymbol(Symbol symbol) - { - if (CurrentToken is SymbolToken symbolToken && symbolToken.Symbol == symbol) - { - Next(); - return true; - } - - return false; - } - - private bool TryExpectIdentifier([NotNullWhen(true)] out IdentifierToken? identifier) - { - if (CurrentToken is IdentifierToken identifierToken) - { - identifier = identifierToken; - Next(); - return true; - } - - identifier = null; - return false; - } - - private IdentifierToken ExpectIdentifier() - { - var token = ExpectToken(); - if (token is not IdentifierToken identifier) - { - throw new ParseException(Diagnostic - .Error($"Expected identifier, but found {token.GetType().Name}") - .WithHelp("Provide a valid identifier name here") - .At(token) - .Build()); - } - - return identifier; - } - - private bool TryExpectIntLiteral([NotNullWhen(true)] out IntLiteralToken? stringLiteral) - { - if (CurrentToken is IntLiteralToken token) - { - stringLiteral = token; - Next(); - return true; - } - - stringLiteral = null; - return false; - } - - private StringLiteralToken ExpectStringLiteral() - { - var token = ExpectToken(); - if (token is not StringLiteralToken identifier) - { - throw new ParseException(Diagnostic - .Error($"Expected string literal, but found {token.GetType().Name}") - .WithHelp("Provide a valid string literal") - .At(token) - .Build()); - } - - return identifier; - } - - private void Next() - { - _tokenIndex++; - } - - private List GetTokens(int tokenStartIndex) - { - return _tokens.Skip(tokenStartIndex).Take(_tokenIndex - tokenStartIndex).ToList(); - } -} - -public record SyntaxTree(List Definitions, string ModuleName, List Imports); - -public class ParseException : Exception -{ - public Diagnostic Diagnostic { get; } - - public ParseException(Diagnostic diagnostic) : base(diagnostic.Message) - { - Diagnostic = diagnostic; - } -} \ No newline at end of file diff --git a/compiler/NubLang/Syntax/Syntax.cs b/compiler/NubLang/Syntax/Syntax.cs deleted file mode 100644 index 8d4472c..0000000 --- a/compiler/NubLang/Syntax/Syntax.cs +++ /dev/null @@ -1,147 +0,0 @@ -namespace NubLang.Syntax; - -public abstract record SyntaxNode(List Tokens); - -#region Definitions - -public abstract record DefinitionSyntax(List Tokens, string Name, bool Exported) : SyntaxNode(Tokens); - -public record FuncParameterSyntax(List Tokens, string Name, TypeSyntax Type) : SyntaxNode(Tokens); - -public record FuncPrototypeSyntax(List Tokens, string Name, bool Exported, string? ExternSymbol, List Parameters, TypeSyntax ReturnType) : SyntaxNode(Tokens); - -public record FuncSyntax(List Tokens, FuncPrototypeSyntax Prototype, BlockSyntax? Body) : DefinitionSyntax(Tokens, Prototype.Name, Prototype.Exported); - -public record StructFieldSyntax(List Tokens, string Name, TypeSyntax Type, ExpressionSyntax? Value) : SyntaxNode(Tokens); - -public record StructSyntax(List Tokens, string Name, bool Exported, List Fields) : DefinitionSyntax(Tokens, Name, Exported); - -public record EnumFieldSyntax(List Tokens, string Name, long Value) : SyntaxNode(Tokens); - -public record EnumSyntax(List Tokens, string Name, bool Exported, TypeSyntax? Type, List Fields) : DefinitionSyntax(Tokens, Name, Exported); - -public enum UnaryOperatorSyntax -{ - Negate, - Invert -} - -public enum BinaryOperatorSyntax -{ - Equal, - NotEqual, - GreaterThan, - GreaterThanOrEqual, - LessThan, - LessThanOrEqual, - LogicalAnd, - LogicalOr, - Plus, - Minus, - Multiply, - Divide, - Modulo, - LeftShift, - RightShift, - BitwiseAnd, - BitwiseXor, - BitwiseOr, -} - -#endregion - -#region Statements - -public abstract record StatementSyntax(List Tokens) : SyntaxNode(Tokens); - -public record BlockSyntax(List Tokens, List Statements) : StatementSyntax(Tokens); - -public record StatementExpressionSyntax(List Tokens, ExpressionSyntax Expression) : StatementSyntax(Tokens); - -public record ReturnSyntax(List Tokens, ExpressionSyntax? Value) : StatementSyntax(Tokens); - -public record AssignmentSyntax(List Tokens, ExpressionSyntax Target, ExpressionSyntax Value) : StatementSyntax(Tokens); - -public record IfSyntax(List Tokens, ExpressionSyntax Condition, BlockSyntax Body, Variant? Else) : StatementSyntax(Tokens); - -public record VariableDeclarationSyntax(List Tokens, string Name, TypeSyntax? ExplicitType, ExpressionSyntax? Assignment) : StatementSyntax(Tokens); - -public record ContinueSyntax(List Tokens) : StatementSyntax(Tokens); - -public record BreakSyntax(List Tokens) : StatementSyntax(Tokens); - -public record DeferSyntax(List Tokens, StatementSyntax Statement) : StatementSyntax(Tokens); - -public record WhileSyntax(List Tokens, ExpressionSyntax Condition, BlockSyntax Body) : StatementSyntax(Tokens); - -public record ForSyntax(List Tokens, string ElementName, string? IndexName, ExpressionSyntax Target, BlockSyntax Body) : StatementSyntax(Tokens); - -#endregion - -#region Expressions - -public abstract record ExpressionSyntax(List Tokens) : SyntaxNode(Tokens); - -public record BinaryExpressionSyntax(List Tokens, ExpressionSyntax Left, BinaryOperatorSyntax Operator, ExpressionSyntax Right) : ExpressionSyntax(Tokens); - -public record UnaryExpressionSyntax(List Tokens, UnaryOperatorSyntax Operator, ExpressionSyntax Operand) : ExpressionSyntax(Tokens); - -public record FuncCallSyntax(List Tokens, ExpressionSyntax Expression, List Parameters) : ExpressionSyntax(Tokens); - -public record LocalIdentifierSyntax(List Tokens, string Name) : ExpressionSyntax(Tokens); - -public record ModuleIdentifierSyntax(List Tokens, string Module, string Name) : ExpressionSyntax(Tokens); - -public record ArrayInitializerSyntax(List Tokens, List Values) : ExpressionSyntax(Tokens); - -public record ArrayIndexAccessSyntax(List Tokens, ExpressionSyntax Target, ExpressionSyntax Index) : ExpressionSyntax(Tokens); - -public record AddressOfSyntax(List Tokens, ExpressionSyntax Target) : ExpressionSyntax(Tokens); - -public record IntLiteralSyntax(List Tokens, string Value, int Base) : ExpressionSyntax(Tokens); - -public record StringLiteralSyntax(List Tokens, string Value) : ExpressionSyntax(Tokens); - -public record BoolLiteralSyntax(List Tokens, bool Value) : ExpressionSyntax(Tokens); - -public record FloatLiteralSyntax(List Tokens, string Value) : ExpressionSyntax(Tokens); - -public record MemberAccessSyntax(List Tokens, ExpressionSyntax Target, string Member) : ExpressionSyntax(Tokens); - -public record StructInitializerSyntax(List Tokens, TypeSyntax? StructType, Dictionary Initializers) : ExpressionSyntax(Tokens); - -public record DereferenceSyntax(List Tokens, ExpressionSyntax Target) : ExpressionSyntax(Tokens); - -public record SizeSyntax(List Tokens, TypeSyntax Type) : ExpressionSyntax(Tokens); - -public record CastSyntax(List Tokens, ExpressionSyntax Value) : ExpressionSyntax(Tokens); - -#endregion - -#region Types - -public abstract record TypeSyntax(List Tokens) : SyntaxNode(Tokens); - -public record FuncTypeSyntax(List Tokens, List Parameters, TypeSyntax ReturnType) : TypeSyntax(Tokens); - -public record PointerTypeSyntax(List Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens); - -public record VoidTypeSyntax(List Tokens) : TypeSyntax(Tokens); - -public record IntTypeSyntax(List Tokens, bool Signed, int Width) : TypeSyntax(Tokens); - -public record FloatTypeSyntax(List Tokens, int Width) : TypeSyntax(Tokens); - -public record BoolTypeSyntax(List Tokens) : TypeSyntax(Tokens); - -public record StringTypeSyntax(List Tokens) : TypeSyntax(Tokens); - -public record SliceTypeSyntax(List Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens); - -public record ArrayTypeSyntax(List Tokens, TypeSyntax BaseType) : TypeSyntax(Tokens); - -public record ConstArrayTypeSyntax(List Tokens, TypeSyntax BaseType, long Size) : TypeSyntax(Tokens); - -public record CustomTypeSyntax(List Tokens, string? Module, string Name) : TypeSyntax(Tokens); - -#endregion \ No newline at end of file diff --git a/compiler/NubLang/Syntax/Token.cs b/compiler/NubLang/Syntax/Token.cs deleted file mode 100644 index 66f0980..0000000 --- a/compiler/NubLang/Syntax/Token.cs +++ /dev/null @@ -1,77 +0,0 @@ -using NubLang.Diagnostics; - -namespace NubLang.Syntax; - -public enum Symbol -{ - // Control - If, - Else, - While, - For, - In, - Break, - Continue, - Return, - Let, - Defer, - - // Declaration - Func, - Struct, - Enum, - Import, - Module, - - // Modifier - Extern, - Export, - - Colon, - DoubleColon, - OpenParen, - CloseParen, - OpenBrace, - CloseBrace, - OpenBracket, - CloseBracket, - Comma, - Period, - Assign, - Bang, - Equal, - NotEqual, - LessThan, - LessThanOrEqual, - GreaterThan, - GreaterThanOrEqual, - Plus, - Minus, - Star, - ForwardSlash, - Caret, - Ampersand, - Semi, - Percent, - LeftShift, - RightShift, - Pipe, - And, - Or, - At, - QuestionMark, -} - -public abstract record Token(SourceSpan Span); - -public record IdentifierToken(SourceSpan Span, string Value) : Token(Span); - -public record IntLiteralToken(SourceSpan Span, string Value, int Base) : Token(Span); - -public record StringLiteralToken(SourceSpan Span, string Value) : Token(Span); - -public record BoolLiteralToken(SourceSpan Span, bool Value) : Token(Span); - -public record FloatLiteralToken(SourceSpan Span, string Value) : Token(Span); - -public record SymbolToken(SourceSpan Span, Symbol Symbol) : Token(Span); \ No newline at end of file diff --git a/compiler/NubLang/Syntax/Tokenizer.cs b/compiler/NubLang/Syntax/Tokenizer.cs deleted file mode 100644 index 565ab43..0000000 --- a/compiler/NubLang/Syntax/Tokenizer.cs +++ /dev/null @@ -1,331 +0,0 @@ -using NubLang.Diagnostics; - -namespace NubLang.Syntax; - -public sealed class Tokenizer -{ - private static readonly Dictionary Keywords = new() - { - ["func"] = Symbol.Func, - ["if"] = Symbol.If, - ["else"] = Symbol.Else, - ["while"] = Symbol.While, - ["for"] = Symbol.For, - ["in"] = Symbol.In, - ["break"] = Symbol.Break, - ["continue"] = Symbol.Continue, - ["return"] = Symbol.Return, - ["struct"] = Symbol.Struct, - ["let"] = Symbol.Let, - ["extern"] = Symbol.Extern, - ["module"] = Symbol.Module, - ["export"] = Symbol.Export, - ["import"] = Symbol.Import, - ["defer"] = Symbol.Defer, - ["enum"] = Symbol.Enum, - }; - - private static readonly Dictionary Symbols = new() - { - [['=', '=']] = Symbol.Equal, - [['!', '=']] = Symbol.NotEqual, - [['<', '=']] = Symbol.LessThanOrEqual, - [['>', '=']] = Symbol.GreaterThanOrEqual, - [['<', '<']] = Symbol.LeftShift, - [['>', '>']] = Symbol.RightShift, - [['&', '&']] = Symbol.And, - [['|', '|']] = Symbol.Or, - [[':', ':']] = Symbol.DoubleColon, - [[':']] = Symbol.Colon, - [['(']] = Symbol.OpenParen, - [[')']] = Symbol.CloseParen, - [['{']] = Symbol.OpenBrace, - [['}']] = Symbol.CloseBrace, - [['[']] = Symbol.OpenBracket, - [[']']] = Symbol.CloseBracket, - [[',']] = Symbol.Comma, - [['.']] = Symbol.Period, - [['=']] = Symbol.Assign, - [['<']] = Symbol.LessThan, - [['>']] = Symbol.GreaterThan, - [['+']] = Symbol.Plus, - [['-']] = Symbol.Minus, - [['*']] = Symbol.Star, - [['/']] = Symbol.ForwardSlash, - [['!']] = Symbol.Bang, - [['^']] = Symbol.Caret, - [['&']] = Symbol.Ampersand, - [[';']] = Symbol.Semi, - [['%']] = Symbol.Percent, - [['|']] = Symbol.Pipe, - [['@']] = Symbol.At, - [['?']] = Symbol.QuestionMark, - }; - - private static readonly (char[] Pattern, Symbol Symbol)[] OrderedSymbols = Symbols - .OrderByDescending(kvp => kvp.Key.Length) - .Select(kvp => (kvp.Key, kvp.Value)) - .ToArray(); - - private readonly string _fileName; - private readonly string _content; - private int _index = 0; - private int _line = 1; - private int _column = 1; - - public Tokenizer(string fileName, string content) - { - _fileName = fileName; - _content = content; - } - - public List Diagnostics { get; } = []; - public List Tokens { get; } = []; - - public void Tokenize() - { - Diagnostics.Clear(); - Tokens.Clear(); - _index = 0; - _line = 1; - _column = 1; - - while (Peek().HasValue) - { - try - { - var current = Peek()!.Value; - if (char.IsWhiteSpace(current)) - { - if (current is '\n') - { - _line += 1; - // note(nub31): Next increments the column, so 0 is correct here - _column = 0; - } - - Next(); - continue; - } - - if (current == '/' && Peek(1) == '/') - { - // note(nub31): Keep newline so next iteration increments the line counter - while (Peek() is not '\n') - { - Next(); - } - - continue; - } - - Tokens.Add(ParseToken(current, _line, _column)); - } - catch (TokenizerException e) - { - Diagnostics.Add(e.Diagnostic); - Next(); - } - } - } - - private Token ParseToken(char current, int lineStart, int columnStart) - { - if (char.IsLetter(current) || current == '_') - { - var buffer = string.Empty; - - while (Peek() != null && (char.IsLetterOrDigit(Peek()!.Value) || Peek() == '_')) - { - buffer += Peek(); - Next(); - } - - if (Keywords.TryGetValue(buffer, out var keywordSymbol)) - { - return new SymbolToken(CreateSpan(lineStart, columnStart), keywordSymbol); - } - - if (buffer is "true" or "false") - { - return new BoolLiteralToken(CreateSpan(lineStart, columnStart), Convert.ToBoolean(buffer)); - } - - return new IdentifierToken(CreateSpan(lineStart, columnStart), buffer); - } - - if (char.IsDigit(current)) - { - var buffer = string.Empty; - - if (current == '0' && Peek(1) is 'x') - { - buffer += "0x"; - Next(); - Next(); - while (Peek() != null && Uri.IsHexDigit(Peek()!.Value)) - { - buffer += Peek()!.Value; - Next(); - } - - if (buffer.Length <= 2) - { - throw new TokenizerException(Diagnostic - .Error("Invalid hex literal, no digits found") - .At(_fileName, _line, _column) - .Build()); - } - - return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 16); - } - - if (current == '0' && Peek(1) is 'b') - { - buffer += "0b"; - Next(); - Next(); - while (Peek() != null && (Peek() == '0' || Peek() == '1')) - { - buffer += Peek()!.Value; - Next(); - } - - if (buffer.Length <= 2) - { - throw new TokenizerException(Diagnostic - .Error("Invalid binary literal, no digits found") - .At(_fileName, _line, _column) - .Build()); - } - - return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 2); - } - - var isFloat = false; - while (Peek() != null) - { - var next = Peek()!.Value; - if (next == '.') - { - if (isFloat) - { - throw new TokenizerException(Diagnostic - .Error("More than one period found in float literal") - .At(_fileName, _line, _column) - .Build()); - } - - isFloat = true; - buffer += next; - Next(); - } - else if (char.IsDigit(next)) - { - buffer += next; - Next(); - } - else - { - break; - } - } - - if (isFloat) - { - return new FloatLiteralToken(CreateSpan(lineStart, columnStart), buffer); - } - else - { - return new IntLiteralToken(CreateSpan(lineStart, columnStart), buffer, 10); - } - } - - if (current == '"') - { - Next(); - var buffer = string.Empty; - - while (true) - { - var next = Peek(); - if (!next.HasValue) - { - throw new TokenizerException(Diagnostic - .Error("Unclosed string literal") - .At(_fileName, _line, _column) - .Build()); - } - - if (next is '\n') - { - _line += 1; - break; - } - - if (next is '"') - { - Next(); - break; - } - - buffer += next; - Next(); - } - - return new StringLiteralToken(CreateSpan(lineStart, columnStart), buffer); - } - - foreach (var (pattern, symbol) in OrderedSymbols) - { - for (var i = 0; i < pattern.Length; i++) - { - var c = Peek(i); - if (!c.HasValue || c.Value != pattern[i]) break; - - if (i == pattern.Length - 1) - { - for (var j = 0; j <= i; j++) - { - Next(); - } - - return new SymbolToken(CreateSpan(lineStart, columnStart), symbol); - } - } - } - - throw new TokenizerException(Diagnostic.Error($"Unknown token '{current}'").Build()); - } - - private SourceSpan CreateSpan(int lineStart, int columnStart) - { - return new SourceSpan(_fileName, new SourceLocation(lineStart, columnStart), new SourceLocation(_line, _column)); - } - - private char? Peek(int offset = 0) - { - if (_index + offset < _content.Length) - { - return _content[_index + offset]; - } - - return null; - } - - private void Next() - { - _index += 1; - _column += 1; - } -} - -public class TokenizerException : Exception -{ - public Diagnostic Diagnostic { get; } - - public TokenizerException(Diagnostic diagnostic) : base(diagnostic.Message) - { - Diagnostic = diagnostic; - } -} \ No newline at end of file diff --git a/compiler/NubLang/Variant.cs b/compiler/NubLang/Variant.cs deleted file mode 100644 index c9898b8..0000000 --- a/compiler/NubLang/Variant.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System.Diagnostics.CodeAnalysis; - -namespace NubLang; - -public readonly struct Variant where T1 : notnull where T2 : notnull -{ - public Variant() - { - throw new InvalidOperationException("Variant must be initialized with a value"); - } - - public Variant(T1 value) - { - _value = value; - } - - public Variant(T2 value) - { - _value = value; - } - - private readonly object _value; - - public void Match(Action on1, Action on2) - { - switch (_value) - { - case T1 v1: - on1(v1); - break; - case T2 v2: - on2(v2); - break; - default: - throw new InvalidCastException(); - } - } - - public T Match(Func on1, Func on2) - { - return _value switch - { - T1 v1 => on1(v1), - T2 v2 => on2(v2), - _ => throw new InvalidCastException() - }; - } - - public bool IsCase1([NotNullWhen(true)] out T1? value) - { - if (_value is T1 converted) - { - value = converted; - return true; - } - - value = default; - return false; - } - - public bool IsCase2([NotNullWhen(true)] out T2? value) - { - if (_value is T2 converted) - { - value = converted; - return true; - } - - value = default; - return false; - } - - public static implicit operator Variant(T1 value) => new(value); - public static implicit operator Variant(T2 value) => new(value); -} \ No newline at end of file diff --git a/compiler/NubLib.cs b/compiler/NubLib.cs new file mode 100644 index 0000000..9ed95cc --- /dev/null +++ b/compiler/NubLib.cs @@ -0,0 +1,110 @@ +using System.IO.Compression; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Compiler; + +public class NubLib +{ + private static readonly JsonSerializerOptions JsonOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + WriteIndented = true, + }; + + public static void Pack(string outputPath, string archivePath, Manifest manifest) + { + using var fs = new FileStream(outputPath, FileMode.Create); + using var zip = new ZipArchive(fs, ZipArchiveMode.Create); + + var manifestEntry = zip.CreateEntry("manifest.json"); + using (var writer = new StreamWriter(manifestEntry.Open())) + { + var serialized = JsonSerializer.Serialize(manifest, JsonOptions); + + writer.Write(serialized); + } + + var archiveEntry = zip.CreateEntry("lib.a"); + + using var entryStream = archiveEntry.Open(); + using var fileStream = File.OpenRead(archivePath); + + fileStream.CopyTo(entryStream); + } + + public static NubLibLoadResult Unpack(string nublibPath) + { + using var fs = new FileStream(nublibPath, FileMode.Open, FileAccess.Read); + using var zip = new ZipArchive(fs, ZipArchiveMode.Read); + + var manifestEntry = zip.GetEntry("manifest.json") ?? throw new FileNotFoundException("Manifest not found in nublib", "manifest.json"); + + Manifest manifest; + using (var reader = new StreamReader(manifestEntry.Open())) + { + var json = reader.ReadToEnd(); + manifest = JsonSerializer.Deserialize(json, JsonOptions) ?? throw new InvalidDataException("Failed to deserialize manifest.json"); + } + + var archiveEntry = zip.Entries.FirstOrDefault(e => e.Name.EndsWith(".a")) ?? throw new FileNotFoundException("Archive not found in nublib", "*.a"); + + string tempArchivePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".a"); + using (var entryStream = archiveEntry.Open()) + using (var tempFile = File.Create(tempArchivePath)) + { + entryStream.CopyTo(tempFile); + } + + return new NubLibLoadResult(manifest, tempArchivePath); + } + + public record NubLibLoadResult(Manifest Manifest, string ArchivePath); +} + +public record Manifest(Dictionary Modules) +{ + public static Manifest Create(ModuleGraph moduleGraph) + { + var modules = new Dictionary(); + + foreach (var module in moduleGraph.GetModules()) + { + var types = module.GetTypes().ToDictionary(x => x.Key, x => ConvertType(x.Value)); + var identifiers = module.GetIdentifiers().ToDictionary(x => x.Key, x => new Module.IdentifierInfo(x.Value.Type, x.Value.Exported, x.Value.Extern, x.Value.MangledName)); + modules[module.Name] = new Module(types, identifiers); + } + + return new Manifest(modules); + + static Module.TypeInfo ConvertType(Compiler.Module.TypeInfo typeInfo) + { + return typeInfo switch + { + Compiler.Module.TypeInfoStruct s => new Module.TypeInfoStruct(s.Exported, s.Packed, s.Fields.Select(x => new Module.TypeInfoStruct.Field(x.Name, x.Type)).ToList()), + Compiler.Module.TypeInfoEnum e => new Module.TypeInfoEnum(e.Exported, e.Variants.Select(v => new Module.TypeInfoEnum.Variant(v.Name, v.Type)).ToList()), + _ => throw new ArgumentOutOfRangeException(nameof(typeInfo)) + }; + } + } + + + public record Module(Dictionary Types, Dictionary Identifiers) + { + public record IdentifierInfo(NubType Type, bool Exported, bool Extern, string MangledName); + + [JsonDerivedType(typeof(TypeInfoStruct), "struct")] + [JsonDerivedType(typeof(TypeInfoEnum), "enum")] + public abstract record TypeInfo(bool Exported); + + public record TypeInfoStruct(bool Exported, bool Packed, IReadOnlyList Fields) : TypeInfo(Exported) + { + public record Field(string Name, NubType Type); + } + + public record TypeInfoEnum(bool Exported, IReadOnlyList Variants) : TypeInfo(Exported) + { + public record Variant(string Name, NubType? Type); + } + } +} \ No newline at end of file diff --git a/compiler/NubType.cs b/compiler/NubType.cs new file mode 100644 index 0000000..bab473c --- /dev/null +++ b/compiler/NubType.cs @@ -0,0 +1,708 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Compiler; + +[JsonConverter(typeof(NubTypeJsonConverter))] +public abstract class NubType +{ + public abstract override string ToString(); + + [Obsolete("Use IsAssignableTo instead of ==", error: true)] + public static bool operator ==(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo"); + + [Obsolete("Use IsAssignableTo instead of ==", error: true)] + public static bool operator !=(NubType? a, NubType? b) => throw new InvalidOperationException("Use IsAssignableTo"); + + public bool IsAssignableTo(NubType target) + { + return (this, target) switch + { + (NubTypeEnumVariant variant, NubTypeEnum targetEnum) => ReferenceEquals(variant.EnumType, targetEnum), + _ => ReferenceEquals(this, target), + }; + } +} + +public class NubTypeVoid : NubType +{ + public static readonly NubTypeVoid Instance = new(); + + private NubTypeVoid() + { + } + + public override string ToString() => "void"; +} + +public class NubTypeUInt : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypeUInt Get(int width) + { + if (!Cache.TryGetValue(width, out var type)) + Cache[width] = type = new NubTypeUInt(width); + + return type; + } + + public int Width { get; } + + private NubTypeUInt(int width) + { + Width = width; + } + + public override string ToString() => $"u{Width}"; +} + +public class NubTypeSInt : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypeSInt Get(int width) + { + if (!Cache.TryGetValue(width, out var type)) + Cache[width] = type = new NubTypeSInt(width); + + return type; + } + + public int Width { get; } + + private NubTypeSInt(int width) + { + Width = width; + } + + public override string ToString() => $"i{Width}"; +} + +public class NubTypeBool : NubType +{ + public static readonly NubTypeBool Instance = new(); + + private NubTypeBool() + { + } + + public override string ToString() => "bool"; +} + +public class NubTypeString : NubType +{ + public static readonly NubTypeString Instance = new(); + + private NubTypeString() + { + } + + public override string ToString() => "string"; +} + +public class NubTypeChar : NubType +{ + public static readonly NubTypeChar Instance = new(); + + private NubTypeChar() + { + } + + public override string ToString() => "char"; +} + +public class NubTypeStruct : NubType +{ + private static readonly Dictionary<(string Module, string Name), NubTypeStruct> Cache = new(); + + public static NubTypeStruct Get(string module, string name) + { + if (!Cache.TryGetValue((module, name), out var structType)) + Cache[(module, name)] = structType = new NubTypeStruct(module, name); + + return structType; + } + + private NubTypeStruct(string module, string name) + { + Module = module; + Name = name; + } + + public string Module { get; } + public string Name { get; } + + public override string ToString() => $"{Module}::{Name}"; +} + +public class NubTypeAnonymousStruct : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypeAnonymousStruct Get(List fields) + { + var sig = new Signature(fields); + + if (!Cache.TryGetValue(sig, out var func)) + Cache[sig] = func = new NubTypeAnonymousStruct(fields); + + return func; + } + + private NubTypeAnonymousStruct(IReadOnlyList fields) + { + Fields = fields; + } + + public IReadOnlyList Fields { get; } + + public override string ToString() => $"{{ {string.Join(", ", Fields.Select(x => $"{x.Name}: {x.Type}"))} }}"; + + public class Field(string name, NubType type) + { + public string Name { get; } = name; + public NubType Type { get; } = type; + } + + private record Signature(IReadOnlyList Fields); +} + +public class NubTypeEnum : NubType +{ + private static readonly Dictionary<(string Module, string Name), NubTypeEnum> Cache = new(); + + public static NubTypeEnum Get(string module, string name) + { + if (!Cache.TryGetValue((module, name), out var enumType)) + Cache[(module, name)] = enumType = new NubTypeEnum(module, name); + + return enumType; + } + + private NubTypeEnum(string module, string name) + { + Module = module; + Name = name; + } + + public string Module { get; } + public string Name { get; } + + public override string ToString() => $"{Module}::{Name}"; +} + +public class NubTypeEnumVariant : NubType +{ + private static readonly Dictionary<(NubTypeEnum EnumType, string Variant), NubTypeEnumVariant> Cache = new(); + + public static NubTypeEnumVariant Get(NubTypeEnum enumType, string variant) + { + if (!Cache.TryGetValue((enumType, variant), out var variantType)) + Cache[(enumType, variant)] = variantType = new NubTypeEnumVariant(enumType, variant); + + return variantType; + } + + private NubTypeEnumVariant(NubTypeEnum enumType, string variant) + { + EnumType = enumType; + Variant = variant; + } + + public NubTypeEnum EnumType { get; } + public string Variant { get; } + + public override string ToString() => $"{EnumType}.{Variant}"; +} + +public class NubTypePointer : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypePointer Get(NubType to) + { + if (!Cache.TryGetValue(to, out var ptr)) + Cache[to] = ptr = new NubTypePointer(to); + + return ptr; + } + + public NubType To { get; } + + private NubTypePointer(NubType to) + { + To = to; + } + + public override string ToString() => $"^{To}"; +} + +public class NubTypeFunc : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypeFunc Get(List parameters, NubType returnType) + { + var sig = new Signature(parameters, returnType); + + if (!Cache.TryGetValue(sig, out var func)) + Cache[sig] = func = new NubTypeFunc(parameters, returnType); + + return func; + } + + public IReadOnlyList Parameters { get; } + public NubType ReturnType { get; } + + private NubTypeFunc(List parameters, NubType returnType) + { + Parameters = parameters; + ReturnType = returnType; + } + + public override string ToString() => $"func({string.Join(' ', Parameters)}): {ReturnType}"; + + private record Signature(IReadOnlyList Parameters, NubType ReturnType); +} + +public class NubTypeArray : NubType +{ + private static readonly Dictionary Cache = new(); + + public static NubTypeArray Get(NubType to) + { + if (!Cache.TryGetValue(to, out var ptr)) + Cache[to] = ptr = new NubTypeArray(to); + + return ptr; + } + + public NubType ElementType { get; } + + private NubTypeArray(NubType elementType) + { + ElementType = elementType; + } + + public override string ToString() => $"[]{ElementType}"; +} + +public class TypeEncoder +{ + public static string Encode(NubType type) + { + return new TypeEncoder().EncodeRoot(type); + } + + private TypeEncoder() + { + } + + private string EncodeRoot(NubType type) + { + var sb = new StringBuilder(); + EncodeType(sb, type); + return sb.ToString(); + } + + private void EncodeType(StringBuilder sb, NubType type) + { + switch (type) + { + case NubTypeVoid: + sb.Append('V'); + break; + + case NubTypeBool: + sb.Append('B'); + break; + + case NubTypeUInt u: + sb.Append($"U("); + sb.Append(u.Width); + sb.Append(')'); + break; + + case NubTypeSInt s: + sb.Append($"I("); + sb.Append(s.Width); + sb.Append(')'); + break; + + case NubTypeString: + sb.Append('S'); + break; + + case NubTypeChar: + sb.Append('C'); + break; + + case NubTypePointer p: + sb.Append("P("); + EncodeType(sb, p.To); + sb.Append(')'); + break; + + case NubTypeStruct st: + sb.Append("TN("); + sb.Append(st.Module); + sb.Append(':'); + sb.Append(st.Name); + sb.Append(')'); + break; + + case NubTypeEnum e: + sb.Append("EN("); + sb.Append(e.Module); + sb.Append(':'); + sb.Append(e.Name); + sb.Append(')'); + break; + + case NubTypeEnumVariant ev: + sb.Append("EV("); + sb.Append(ev.EnumType.Module); + sb.Append(':'); + sb.Append(ev.EnumType.Name); + sb.Append(':'); + sb.Append(ev.Variant); + sb.Append(')'); + break; + + case NubTypeFunc fn: + sb.Append("F("); + for (int i = 0; i < fn.Parameters.Count; i++) + { + EncodeType(sb, fn.Parameters[i]); + } + EncodeType(sb, fn.ReturnType); + sb.Append(')'); + break; + + case NubTypeAnonymousStruct s: + sb.Append("TA("); + foreach (var field in s.Fields) + { + sb.Append(field.Name); + sb.Append(':'); + EncodeType(sb, field.Type); + } + sb.Append(')'); + break; + + case NubTypeArray a: + sb.Append("A("); + EncodeType(sb, a.ElementType); + sb.Append(')'); + break; + + default: + throw new NotSupportedException(type.GetType().Name); + } + } + + private class Definition(int index) + { + public int Index { get; } = index; + public string? Encoded { get; set; } + } +} + +public class TypeDecoder +{ + public static NubType Decode(string encoded) + { + return new TypeDecoder(encoded).DecodeType(); + } + + private TypeDecoder(string encoded) + { + this.encoded = encoded; + } + + private readonly string encoded; + private int index = 0; + + private NubType DecodeType() + { + var start = Consume(); + return start switch + { + 'V' => NubTypeVoid.Instance, + 'B' => NubTypeBool.Instance, + 'U' => DecodeUInt(), + 'I' => DecodeSInt(), + 'S' => NubTypeString.Instance, + 'C' => NubTypeChar.Instance, + 'P' => DecodePointer(), + 'F' => DecodeFunc(), + 'T' => DecodeStruct(), + 'E' => DecodeEnum(), + 'A' => DecodeArray(), + _ => throw new Exception($"'{start}' is not a valid start to a type") + }; + } + + private NubTypeUInt DecodeUInt() + { + Expect('('); + var width = ExpectInt(); + Expect(')'); + return NubTypeUInt.Get(width); + } + + private NubTypeSInt DecodeSInt() + { + Expect('('); + var width = ExpectInt(); + Expect(')'); + return NubTypeSInt.Get(width); + } + + private NubTypePointer DecodePointer() + { + Expect('('); + var to = DecodeType(); + Expect(')'); + return NubTypePointer.Get(to); + } + + private NubTypeFunc DecodeFunc() + { + var types = new List(); + + Expect('('); + while (!TryExpect(')')) + { + types.Add(DecodeType()); + } + + return NubTypeFunc.Get(types.Take(types.Count - 1).ToList(), types.Last()); + } + + private NubType DecodeStruct() + { + + if (TryExpect('A')) + { + var sb = new StringBuilder(); + var fields = new List(); + + Expect('('); + while (!TryExpect(')')) + { + while (!TryExpect(':')) + { + sb.Append(Consume()); + } + + var name = sb.ToString(); + sb.Clear(); + + var type = DecodeType(); + + fields.Add(new NubTypeAnonymousStruct.Field(name, type)); + } + + return NubTypeAnonymousStruct.Get(fields); + } + + if (TryExpect('N')) + { + var sb = new StringBuilder(); + + Expect('('); + while (!TryExpect(':')) + sb.Append(Consume()); + + var module = sb.ToString(); + sb.Clear(); + + while (!TryExpect(')')) + sb.Append(Consume()); + + var name = sb.ToString(); + + return NubTypeStruct.Get(module, name); + } + + throw new Exception("Expected 'A' or 'N'"); + } + + private NubType DecodeEnum() + { + var sb = new StringBuilder(); + + if (TryExpect('V')) + { + Expect('('); + while (!TryExpect(':')) + sb.Append(Consume()); + + var module = sb.ToString(); + sb.Clear(); + + while (!TryExpect(':')) + sb.Append(Consume()); + + var name = sb.ToString(); + + while (!TryExpect(')')) + sb.Append(Consume()); + + var variant = sb.ToString(); + + return NubTypeEnumVariant.Get(NubTypeEnum.Get(module, name), variant); + } + else if (TryExpect('N')) + { + Expect('('); + while (!TryExpect(':')) + sb.Append(Consume()); + + var module = sb.ToString(); + sb.Clear(); + + while (!TryExpect(')')) + sb.Append(Consume()); + + var name = sb.ToString(); + + return NubTypeEnum.Get(module, name); + } + + throw new Exception($"Expected 'V' or 'N'"); + } + + private NubTypeArray DecodeArray() + { + Expect('('); + var elementType = DecodeType(); + Expect(')'); + return NubTypeArray.Get(elementType); + } + + private bool TryPeek(out char c) + { + if (index >= encoded.Length) + { + c = '\0'; + return false; + } + + c = encoded[index]; + return true; + } + + private bool TryConsume(out char c) + { + if (index >= encoded.Length) + { + c = '\0'; + return false; + } + + c = encoded[index]; + index += 1; + + return true; + } + + private char Consume() + { + if (!TryConsume(out var c)) + throw new Exception("Unexpected end of string"); + + return c; + } + + private bool TryExpect(char c) + { + if (index >= encoded.Length) + return false; + + if (encoded[index] != c) + return false; + + Consume(); + return true; + } + + private void Expect(char c) + { + if (!TryExpect(c)) + throw new Exception($"Expected '{c}'"); + } + + private int ExpectInt() + { + var buf = string.Empty; + + while (TryPeek(out var c)) + { + if (!char.IsDigit(c)) + break; + + buf += Consume(); + } + + return int.Parse(buf); + } +} + +public class NubTypeJsonConverter : JsonConverter +{ + public override NubType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + return TypeDecoder.Decode(reader.GetString()!); + } + + public override void Write(Utf8JsonWriter writer, NubType value, JsonSerializerOptions options) + { + writer.WriteStringValue(TypeEncoder.Encode(value)); + } +} + +public static class Hashing +{ + public static ulong Fnv1a64(string text) + { + const ulong offset = 14695981039346656037UL; + const ulong prime = 1099511628211UL; + + ulong hash = offset; + foreach (var c in Encoding.UTF8.GetBytes(text)) + { + hash ^= c; + hash *= prime; + } + + return hash; + } +} + +public static class NameMangler +{ + public static string Mangle(string module, string name, NubType type) + { + var canonical = TypeEncoder.Encode(type); + var hash = Hashing.Fnv1a64(canonical); + + return $"nub_{Sanitize(module)}_{Sanitize(name)}_{hash:x16}"; + } + + private static string Sanitize(string s) + { + var sb = new StringBuilder(s.Length); + foreach (var c in s) + { + if (char.IsLetterOrDigit(c)) + sb.Append(c); + else + sb.Append('_'); + } + return sb.ToString(); + } +} diff --git a/compiler/Parser.cs b/compiler/Parser.cs new file mode 100644 index 0000000..0e3aecd --- /dev/null +++ b/compiler/Parser.cs @@ -0,0 +1,1101 @@ +using System.Diagnostics.CodeAnalysis; + +namespace Compiler; + +public class Parser +{ + public static Ast? Parse(string fileName, List tokens, out List diagnostics) + { + return new Parser(fileName, tokens).Parse(out diagnostics); + } + + private Parser(string fileName, List tokens) + { + this.fileName = fileName; + this.tokens = tokens; + } + + private readonly string fileName; + private readonly List tokens; + private int index; + + private Ast? Parse(out List diagnostics) + { + var definitions = new List(); + diagnostics = []; + + TokenIdent? moduleName = null; + + try + { + ExpectKeyword(Keyword.Module); + moduleName = ExpectIdent(); + + while (Peek() != null) + { + definitions.Add(ParseDefinition()); + } + } + catch (CompileException e) + { + diagnostics.Add(e.Diagnostic); + } + + if (moduleName == null || diagnostics.Any(x => x.Severity == Diagnostic.DiagnosticSeverity.Error)) + return null; + + return new Ast(fileName, moduleName, definitions); + } + + private NodeDefinition ParseDefinition() + { + var startIndex = index; + + Dictionary modifiers = []; + + while (Peek() is TokenKeyword keyword) + { + switch (keyword.Keyword) + { + case Keyword.Export: + Next(); + modifiers[Keyword.Export] = keyword; + break; + case Keyword.Packed: + Next(); + modifiers[Keyword.Packed] = keyword; + break; + case Keyword.Extern: + Next(); + modifiers[Keyword.Extern] = keyword; + break; + default: + goto modifier_done; + } + } + + modifier_done: + + if (TryExpectKeyword(Keyword.Func)) + { + var exported = modifiers.Remove(Keyword.Export); + var @extern = modifiers.Remove(Keyword.Extern); + + foreach (var modifier in modifiers) + // todo(nub31): Add to diagnostics instead of throwing + throw BasicError("Invalid modifier for function", modifier.Value); + + var name = ExpectIdent(); + var parameters = ParseFuncParameters(); + + NodeType? returnType = null; + if (TryExpectSymbol(Symbol.Colon)) + returnType = ParseType(); + + if (@extern) + { + return new NodeDefinitionExternFunc(TokensFrom(startIndex), exported, name, parameters, returnType); + } + else + { + var body = ParseStatement(); + return new NodeDefinitionFunc(TokensFrom(startIndex), exported, name, parameters, body, returnType); + } + } + + if (TryExpectKeyword(Keyword.Struct)) + { + var exported = modifiers.Remove(Keyword.Export); + var packed = modifiers.Remove(Keyword.Packed); + + foreach (var modifier in modifiers) + // todo(nub31): Add to diagnostics instead of throwing + throw BasicError("Invalid modifier for struct", modifier.Value); + + var name = ExpectIdent(); + var fields = new List(); + + ExpectSymbol(Symbol.OpenCurly); + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var fieldStartIndex = index; + var fieldName = ExpectIdent(); + ExpectSymbol(Symbol.Colon); + var fieldType = ParseType(); + TryExpectSymbol(Symbol.Comma); + fields.Add(new NodeDefinitionStruct.Field(TokensFrom(fieldStartIndex), fieldName, fieldType)); + } + + return new NodeDefinitionStruct(TokensFrom(startIndex), exported, packed, name, fields); + } + + if (TryExpectKeyword(Keyword.Enum)) + { + var exported = modifiers.Remove(Keyword.Export); + + foreach (var modifier in modifiers) + // todo(nub31): Add to diagnostics instead of throwing + throw BasicError("Invalid modifier for struct", modifier.Value); + + var name = ExpectIdent(); + var variants = new List(); + + ExpectSymbol(Symbol.OpenCurly); + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var variantsStartIndex = index; + var variantName = ExpectIdent(); + + NodeType? variantType = null; + if (TryExpectSymbol(Symbol.Colon)) + variantType = ParseType(); + + TryExpectSymbol(Symbol.Comma); + + variants.Add(new NodeDefinitionEnum.Variant(TokensFrom(variantsStartIndex), variantName, variantType)); + } + + return new NodeDefinitionEnum(TokensFrom(startIndex), exported, name, variants); + } + + if (TryExpectKeyword(Keyword.Let)) + { + var exported = modifiers.Remove(Keyword.Export); + + foreach (var modifier in modifiers) + // todo(nub31): Add to diagnostics instead of throwing + throw BasicError("Invalid modifier for global variable", modifier.Value); + + var name = ExpectIdent(); + ExpectSymbol(Symbol.Colon); + var type = ParseType(); + + return new NodeDefinitionGlobalVariable(TokensFrom(startIndex), exported, name, type); + } + + throw BasicError("Not a valid definition", Peek()); + } + + private List ParseFuncParameters() + { + var parameters = new List(); + + ExpectSymbol(Symbol.OpenParen); + + while (true) + { + if (TryExpectSymbol(Symbol.CloseParen)) + break; + + var startIndex = index; + + var name = ExpectIdent(); + ExpectSymbol(Symbol.Colon); + var type = ParseType(); + + parameters.Add(new NodeDefinitionFunc.Param(TokensFrom(startIndex), name, type)); + + if (!TryExpectSymbol(Symbol.Comma)) + { + ExpectSymbol(Symbol.CloseParen); + break; + } + } + + return parameters; + } + + private NodeStatement ParseStatement() + { + var startIndex = index; + + if (TryExpectSymbol(Symbol.OpenCurly)) + { + var statements = new List(); + while (!TryExpectSymbol(Symbol.CloseCurly)) + statements.Add(ParseStatement()); + + return new NodeStatementBlock(TokensFrom(startIndex), statements); + } + + if (TryExpectKeyword(Keyword.Return)) + { + NodeExpression? value = null; + + if (Peek() is TokenIdent token && token.Ident == "void") + { + Next(); + } + else + { + value = ParseExpression(); + } + + return new NodeStatementReturn(TokensFrom(startIndex), value); + } + + if (TryExpectKeyword(Keyword.Let)) + { + var name = ExpectIdent(); + + NodeType? type = null; + if (TryExpectSymbol(Symbol.Colon)) + type = ParseType(); + + ExpectSymbol(Symbol.Equal); + var value = ParseExpression(); + + return new NodeStatementVariableDeclaration(TokensFrom(startIndex), name, type, value); + } + + if (TryExpectKeyword(Keyword.If)) + { + var condition = ParseExpression(); + var thenBlock = ParseStatement(); + NodeStatement? elseBlock = null; + + if (TryExpectKeyword(Keyword.Else)) + elseBlock = ParseStatement(); + + return new NodeStatementIf(TokensFrom(startIndex), condition, thenBlock, elseBlock); + } + + if (TryExpectKeyword(Keyword.While)) + { + var condition = ParseExpression(); + var block = ParseStatement(); + return new NodeStatementWhile(TokensFrom(startIndex), condition, block); + } + + if (TryExpectKeyword(Keyword.For)) + { + var variableName = ExpectIdent(); + ExpectKeyword(Keyword.In); + var array = ParseExpression(); + var block = ParseStatement(); + return new NodeStatementFor(TokensFrom(startIndex), variableName, array, block); + } + + if (TryExpectKeyword(Keyword.Match)) + { + var target = ParseExpression(); + var cases = new List(); + + ExpectSymbol(Symbol.OpenCurly); + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var caseStartIndex = index; + var variant = ExpectIdent(); + TryExpectIdent(out var variableName); + var body = ParseStatement(); + cases.Add(new NodeStatementMatch.Case(TokensFrom(caseStartIndex), variant, variableName, body)); + } + + return new NodeStatementMatch(TokensFrom(startIndex), target, cases); + } + + { + var target = ParseExpression(); + + if (TryExpectSymbol(Symbol.Equal)) + { + var value = ParseExpression(); + return new NodeStatementAssignment(TokensFrom(startIndex), target, value); + } + + return new NodeStatementExpression(TokensFrom(startIndex), target); + } + } + + private NodeExpression ParseExpression(int minPrecedence = -1) + { + var startIndex = index; + + var left = ParseExpressionLeaf(); + + while (TryPeekBinaryOperator(out var op) && GetPrecedence(op) >= minPrecedence) + { + Next(); + var right = ParseExpression(GetPrecedence(op) + 1); + left = new NodeExpressionBinary(TokensFrom(startIndex), left, op, right); + } + + return left; + } + + private static int GetPrecedence(NodeExpressionBinary.Op operation) + { + return operation switch + { + NodeExpressionBinary.Op.Multiply => 10, + NodeExpressionBinary.Op.Divide => 10, + NodeExpressionBinary.Op.Modulo => 10, + + NodeExpressionBinary.Op.Add => 9, + NodeExpressionBinary.Op.Subtract => 9, + + NodeExpressionBinary.Op.LeftShift => 8, + NodeExpressionBinary.Op.RightShift => 8, + + NodeExpressionBinary.Op.GreaterThan => 7, + NodeExpressionBinary.Op.GreaterThanOrEqual => 7, + NodeExpressionBinary.Op.LessThan => 7, + NodeExpressionBinary.Op.LessThanOrEqual => 7, + + NodeExpressionBinary.Op.Equal => 7, + NodeExpressionBinary.Op.NotEqual => 7, + + // NodeExpressionBinary.Op.BitwiseAnd => 6, + // NodeExpressionBinary.Op.BitwiseXor => 5, + // NodeExpressionBinary.Op.BitwiseOr => 4, + + NodeExpressionBinary.Op.LogicalAnd => 3, + NodeExpressionBinary.Op.LogicalOr => 2, + _ => throw new ArgumentOutOfRangeException(nameof(operation), operation, null) + }; + } + + private NodeExpression ParseExpressionLeaf() + { + var startIndex = index; + + NodeExpression expr; + + if (TryExpectSymbol(Symbol.OpenParen)) + { + var value = ParseExpression(); + ExpectSymbol(Symbol.CloseParen); + expr = value; + } + else if (TryExpectSymbol(Symbol.Minus)) + { + var target = ParseExpression(); + expr = new NodeExpressionUnary(TokensFrom(startIndex), target, NodeExpressionUnary.Op.Negate); + } + else if (TryExpectSymbol(Symbol.OpenSquare)) + { + var values = new List(); + + while (!TryExpectSymbol(Symbol.CloseSquare)) + { + var value = ParseExpression(); + values.Add(value); + TryExpectSymbol(Symbol.Comma); + } + + expr = new NodeExpressionArrayLiteral(TokensFrom(startIndex), values); + } + else if (TryExpectSymbol(Symbol.OpenCurly)) + { + var initializers = new List(); + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var initializerStartIndex = startIndex; + var fieldName = ExpectIdent(); + ExpectSymbol(Symbol.Equal); + var fieldValue = ParseExpression(); + initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue)); + } + + expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), null, initializers); + } + else if (TryExpectSymbol(Symbol.Bang)) + { + var target = ParseExpression(); + expr = new NodeExpressionUnary(TokensFrom(startIndex), target, NodeExpressionUnary.Op.Invert); + } + else if (TryExpectIntLiteral(out var intLiteral)) + { + expr = new NodeExpressionIntLiteral(TokensFrom(startIndex), intLiteral); + } + else if (TryExpectStringLiteral(out var stringLiteral)) + { + expr = new NodeExpressionStringLiteral(TokensFrom(startIndex), stringLiteral); + } + else if (TryExpectBoolLiteral(out var boolLiteral)) + { + expr = new NodeExpressionBoolLiteral(TokensFrom(startIndex), boolLiteral); + } + else if (TryExpectIdent(out var ident)) + { + List sections = [ident]; + + while (TryExpectSymbol(Symbol.ColonColon)) + { + sections.Add(ExpectIdent()); + } + + expr = new NodeExpressionIdent(TokensFrom(startIndex), sections); + } + else if (TryExpectKeyword(Keyword.New)) + { + var type = ParseType(); + + if (type is NodeTypeString) + { + ExpectSymbol(Symbol.OpenParen); + var value = ParseExpression(); + ExpectSymbol(Symbol.CloseParen); + + expr = new NodeExpressionStringConstructor(TokensFrom(startIndex), value); + } + else if (type is NodeTypeNamed namedType) + { + if (TryExpectSymbol(Symbol.OpenParen)) + { + var value = ParseExpression(); + ExpectSymbol(Symbol.CloseParen); + + expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), namedType, value); + } + else if (TryExpectSymbol(Symbol.OpenCurly)) + { + var initializers = new List(); + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var initializerStartIndex = startIndex; + var fieldName = ExpectIdent(); + ExpectSymbol(Symbol.Equal); + var fieldValue = ParseExpression(); + initializers.Add(new NodeExpressionStructLiteral.Initializer(TokensFrom(initializerStartIndex), fieldName, fieldValue)); + } + + expr = new NodeExpressionStructLiteral(TokensFrom(startIndex), null, initializers); + } + else + { + expr = new NodeExpressionEnumLiteral(TokensFrom(startIndex), namedType, null); + } + } + else + { + throw BasicError($"Expected named type or string", type); + } + } + else + { + throw BasicError("Expected start of expression", Peek()); + } + + while (true) + { + if (TryExpectSymbol(Symbol.Period)) + { + var name = ExpectIdent(); + expr = new NodeExpressionMemberAccess(TokensFrom(startIndex), expr, name); + } + else if (TryExpectSymbol(Symbol.OpenParen)) + { + var parameters = new List(); + + while (!TryExpectSymbol(Symbol.CloseParen)) + { + parameters.Add(ParseExpression()); + TryExpectSymbol(Symbol.Comma); + } + + expr = new NodeExpressionFuncCall(TokensFrom(startIndex), expr, parameters); + } + else + { + break; + } + } + + return expr; + } + + private NodeType ParseType() + { + var startIndex = index; + + if (TryExpectSymbol(Symbol.Caret)) + { + var to = ParseType(); + return new NodeTypePointer(TokensFrom(startIndex), to); + } + + if (TryExpectKeyword(Keyword.Func)) + { + var parameters = new List(); + + ExpectSymbol(Symbol.OpenParen); + while (!TryExpectSymbol(Symbol.CloseParen)) + { + parameters.Add(ParseType()); + } + + ExpectSymbol(Symbol.Colon); + var returnType = ParseType(); + + return new NodeTypeFunc(TokensFrom(startIndex), parameters, returnType); + } + + if (TryExpectSymbol(Symbol.OpenCurly)) + { + var fields = new List(); + + while (!TryExpectSymbol(Symbol.CloseCurly)) + { + var name = ExpectIdent(); + ExpectSymbol(Symbol.Colon); + var type = ParseType(); + fields.Add(new NodeTypeAnonymousStruct.Field(name, type)); + } + + return new NodeTypeAnonymousStruct(TokensFrom(startIndex), fields); + } + + if (TryExpectSymbol(Symbol.OpenSquare)) + { + ExpectSymbol(Symbol.CloseSquare); + var elementType = ParseType(); + return new NodeTypeArray(TokensFrom(startIndex), elementType); + } + + if (TryExpectIdent(out var ident)) + { + switch (ident.Ident) + { + case "void": + return new NodeTypeVoid(TokensFrom(startIndex)); + case "string": + return new NodeTypeString(TokensFrom(startIndex)); + case "char": + return new NodeTypeChar(TokensFrom(startIndex)); + case "bool": + return new NodeTypeBool(TokensFrom(startIndex)); + case "int": + return new NodeTypeSInt(TokensFrom(startIndex), 64); + case "i8": + return new NodeTypeSInt(TokensFrom(startIndex), 8); + case "i16": + return new NodeTypeSInt(TokensFrom(startIndex), 16); + case "i32": + return new NodeTypeSInt(TokensFrom(startIndex), 32); + case "i64": + return new NodeTypeSInt(TokensFrom(startIndex), 64); + case "uint": + return new NodeTypeUInt(TokensFrom(startIndex), 64); + case "u8": + return new NodeTypeUInt(TokensFrom(startIndex), 8); + case "u16": + return new NodeTypeUInt(TokensFrom(startIndex), 16); + case "u32": + return new NodeTypeUInt(TokensFrom(startIndex), 32); + case "u64": + return new NodeTypeUInt(TokensFrom(startIndex), 64); + default: + List secitons = [ident]; + while (TryExpectSymbol(Symbol.ColonColon)) + { + ident = ExpectIdent(); + secitons.Add(ident); + } + + return new NodeTypeNamed(TokensFrom(startIndex), secitons); + } + } + + throw BasicError("Expected type", Peek()); + } + + private List TokensFrom(int startIndex) + { + return tokens.GetRange(startIndex, index - startIndex); + } + + private void ExpectKeyword(Keyword keyword) + { + if (Peek() is TokenKeyword token && token.Keyword == keyword) + { + Next(); + return; + } + + throw BasicError($"Expected '{keyword.AsString()}'", Peek()); + } + + private bool TryExpectKeyword(Keyword keyword) + { + if (Peek() is TokenKeyword token && token.Keyword == keyword) + { + Next(); + return true; + } + + return false; + } + + private void ExpectSymbol(Symbol symbol) + { + if (Peek() is TokenSymbol token && token.Symbol == symbol) + { + Next(); + return; + } + + throw BasicError($"Expected '{symbol.AsString()}'", Peek()); + } + + private bool TryExpectSymbol(Symbol symbol) + { + if (Peek() is TokenSymbol token && token.Symbol == symbol) + { + Next(); + return true; + } + + return false; + } + + private TokenIdent ExpectIdent() + { + if (Peek() is TokenIdent token) + { + Next(); + return token; + } + + throw BasicError("Expected identifier", Peek()); + } + + private bool TryExpectIdent([NotNullWhen(true)] out TokenIdent? ident) + { + if (Peek() is TokenIdent token) + { + Next(); + ident = token; + return true; + } + + ident = null; + return false; + } + + private bool TryExpectIntLiteral([NotNullWhen(true)] out TokenIntLiteral? intLiteral) + { + if (Peek() is TokenIntLiteral token) + { + Next(); + intLiteral = token; + return true; + } + + intLiteral = null; + return false; + } + + private bool TryExpectStringLiteral([NotNullWhen(true)] out TokenStringLiteral? stringLiteral) + { + if (Peek() is TokenStringLiteral token) + { + Next(); + stringLiteral = token; + return true; + } + + stringLiteral = null; + return false; + } + + private bool TryExpectBoolLiteral([NotNullWhen(true)] out TokenBoolLiteral? boolLiteral) + { + if (Peek() is TokenBoolLiteral token) + { + Next(); + boolLiteral = token; + return true; + } + + boolLiteral = null; + return false; + } + + private void Next() + { + if (index >= tokens.Count) + throw BasicError("Unexpected end of tokens", Peek()); + + index += 1; + } + + private Token? Peek(int offset = 0) + { + if (index + offset >= tokens.Count) + return null; + + return tokens[index + offset]; + } + + private bool TryPeekBinaryOperator(out NodeExpressionBinary.Op op) + { + if (Peek() is not TokenSymbol token) + { + op = default; + return false; + } + + switch (token.Symbol) + { + case Symbol.Plus: + op = NodeExpressionBinary.Op.Add; + return true; + case Symbol.Minus: + op = NodeExpressionBinary.Op.Subtract; + return true; + case Symbol.Star: + op = NodeExpressionBinary.Op.Multiply; + return true; + case Symbol.ForwardSlash: + op = NodeExpressionBinary.Op.Divide; + return true; + case Symbol.Percent: + op = NodeExpressionBinary.Op.Modulo; + return true; + case Symbol.BangEqual: + op = NodeExpressionBinary.Op.NotEqual; + return true; + case Symbol.EqualEqual: + op = NodeExpressionBinary.Op.Equal; + return true; + case Symbol.LessThan: + op = NodeExpressionBinary.Op.LessThan; + return true; + case Symbol.LessThanEqual: + op = NodeExpressionBinary.Op.LessThanOrEqual; + return true; + case Symbol.GreaterThan: + op = NodeExpressionBinary.Op.GreaterThan; + return true; + case Symbol.GreaterThanEqual: + op = NodeExpressionBinary.Op.GreaterThanOrEqual; + return true; + case Symbol.LessThanLessThan: + op = NodeExpressionBinary.Op.LeftShift; + return true; + case Symbol.GreaterThanGreaterThan: + op = NodeExpressionBinary.Op.RightShift; + return true; + case Symbol.AmpersandAmpersand: + op = NodeExpressionBinary.Op.LogicalAnd; + return true; + case Symbol.PipePipe: + op = NodeExpressionBinary.Op.LogicalOr; + return true; + default: + op = default; + return false; + } + } + + private CompileException BasicError(string message, Token? ident) + { + return new CompileException(Diagnostic.Error(message).At(fileName, ident).Build()); + } + + private CompileException BasicError(string message, Node? node) + { + return new CompileException(Diagnostic.Error(message).At(fileName, node).Build()); + } +} + +public class Ast(string fileName, TokenIdent moduleName, List definitions) +{ + public string FileName { get; } = fileName; + public TokenIdent ModuleName { get; } = moduleName; + public List Definitions { get; } = definitions; +} + +public abstract class Node(List tokens) +{ + public List Tokens { get; } = tokens; +} + +public abstract class NodeDefinition(List tokens) : Node(tokens); + +public class NodeDefinitionExternFunc(List tokens, bool exported, TokenIdent name, List parameters, NodeType? returnType) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public TokenIdent Name { get; } = name; + public List Parameters { get; } = parameters; + public NodeType? ReturnType { get; } = returnType; +} + +public class NodeDefinitionFunc(List tokens, bool exported, TokenIdent name, List parameters, NodeStatement body, NodeType? returnType) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public TokenIdent Name { get; } = name; + public List Parameters { get; } = parameters; + public NodeStatement Body { get; } = body; + public NodeType? ReturnType { get; } = returnType; + + public class Param(List tokens, TokenIdent name, NodeType type) : Node(tokens) + { + public TokenIdent Name { get; } = name; + public NodeType Type { get; } = type; + } +} + +public class NodeDefinitionStruct(List tokens, bool exported, bool packed, TokenIdent name, List fields) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public bool Packed { get; } = packed; + public TokenIdent Name { get; } = name; + public List Fields { get; } = fields; + + public class Field(List tokens, TokenIdent name, NodeType type) : Node(tokens) + { + public TokenIdent Name { get; } = name; + public NodeType Type { get; } = type; + } +} + +public class NodeDefinitionEnum(List tokens, bool exported, TokenIdent name, List variants) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public TokenIdent Name { get; } = name; + public List Variants { get; } = variants; + + public class Variant(List tokens, TokenIdent name, NodeType? type) : Node(tokens) + { + public TokenIdent Name { get; } = name; + public NodeType? Type { get; } = type; + } +} + +public class NodeDefinitionExternGlobalVariable(List tokens, bool exported, TokenIdent name, NodeType type) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public TokenIdent Name { get; } = name; + public NodeType Type { get; } = type; +} + +public class NodeDefinitionGlobalVariable(List tokens, bool exported, TokenIdent name, NodeType type) : NodeDefinition(tokens) +{ + public bool Exported { get; } = exported; + public TokenIdent Name { get; } = name; + public NodeType Type { get; } = type; +} + +public abstract class NodeStatement(List tokens) : Node(tokens); + +public class NodeStatementBlock(List tokens, List statements) : NodeStatement(tokens) +{ + public List Statements { get; } = statements; +} + +public class NodeStatementExpression(List tokens, NodeExpression expression) : NodeStatement(tokens) +{ + public NodeExpression Expression { get; } = expression; +} + +public class NodeStatementReturn(List tokens, NodeExpression? value) : NodeStatement(tokens) +{ + public NodeExpression? Value { get; } = value; +} + +public class NodeStatementVariableDeclaration(List tokens, TokenIdent name, NodeType? type, NodeExpression value) : NodeStatement(tokens) +{ + public TokenIdent Name { get; } = name; + public NodeType? Type { get; } = type; + public NodeExpression Value { get; } = value; +} + +public class NodeStatementAssignment(List tokens, NodeExpression target, NodeExpression value) : NodeStatement(tokens) +{ + public NodeExpression Target { get; } = target; + public NodeExpression Value { get; } = value; +} + +public class NodeStatementIf(List tokens, NodeExpression condition, NodeStatement thenBlock, NodeStatement? elseBlock) : NodeStatement(tokens) +{ + public NodeExpression Condition { get; } = condition; + public NodeStatement ThenBlock { get; } = thenBlock; + public NodeStatement? ElseBlock { get; } = elseBlock; +} + +public class NodeStatementWhile(List tokens, NodeExpression condition, NodeStatement body) : NodeStatement(tokens) +{ + public NodeExpression Condition { get; } = condition; + public NodeStatement Body { get; } = body; +} + +public class NodeStatementFor(List tokens, TokenIdent variableName, NodeExpression array, NodeStatement body) : NodeStatement(tokens) +{ + public TokenIdent VariableName { get; } = variableName; + public NodeExpression Array { get; } = array; + public NodeStatement Body { get; } = body; +} + +public class NodeStatementMatch(List tokens, NodeExpression target, List cases) : NodeStatement(tokens) +{ + public NodeExpression Target { get; } = target; + public List Cases { get; } = cases; + + public class Case(List tokens, TokenIdent type, TokenIdent? variableName, NodeStatement body) : Node(tokens) + { + public TokenIdent Variant { get; } = type; + public TokenIdent? VariableName { get; } = variableName; + public NodeStatement Body { get; } = body; + } +} + +public abstract class NodeExpression(List tokens) : Node(tokens); + +public class NodeExpressionIntLiteral(List tokens, TokenIntLiteral value) : NodeExpression(tokens) +{ + public TokenIntLiteral Value { get; } = value; +} + +public class NodeExpressionStringLiteral(List tokens, TokenStringLiteral value) : NodeExpression(tokens) +{ + public TokenStringLiteral Value { get; } = value; +} + +public class NodeExpressionBoolLiteral(List tokens, TokenBoolLiteral value) : NodeExpression(tokens) +{ + public TokenBoolLiteral Value { get; } = value; +} + +public class NodeExpressionStructLiteral(List tokens, NodeTypeNamed? type, List initializers) : NodeExpression(tokens) +{ + public NodeTypeNamed? Type { get; } = type; + public List Initializers { get; } = initializers; + + public class Initializer(List tokens, TokenIdent name, NodeExpression value) : Node(tokens) + { + public TokenIdent Name { get; } = name; + public NodeExpression Value { get; } = value; + } +} + +public class NodeExpressionEnumLiteral(List tokens, NodeTypeNamed type, NodeExpression? value) : NodeExpression(tokens) +{ + public NodeTypeNamed Type { get; } = type; + public NodeExpression? Value { get; } = value; +} + +public class NodeExpressionArrayLiteral(List tokens, List values) : NodeExpression(tokens) +{ + public List Values { get; } = values; +} + +public class NodeExpressionStringConstructor(List tokens, NodeExpression value) : NodeExpression(tokens) +{ + public NodeExpression Value { get; } = value; +} + +public class NodeExpressionMemberAccess(List tokens, NodeExpression target, TokenIdent name) : NodeExpression(tokens) +{ + public NodeExpression Target { get; } = target; + public TokenIdent Name { get; } = name; +} + +public class NodeExpressionFuncCall(List tokens, NodeExpression target, List parameters) : NodeExpression(tokens) +{ + public NodeExpression Target { get; } = target; + public List Parameters { get; } = parameters; +} + +public class NodeExpressionIdent(List tokens, List sections) : NodeExpression(tokens) +{ + public List Sections { get; } = sections; +} + +public class NodeExpressionBinary(List tokens, NodeExpression left, NodeExpressionBinary.Op operation, NodeExpression right) : NodeExpression(tokens) +{ + public NodeExpression Left { get; } = left; + public Op Operation { get; } = operation; + public NodeExpression Right { get; } = right; + + public enum Op + { + Add, + Subtract, + Multiply, + Divide, + Modulo, + + Equal, + NotEqual, + LessThan, + LessThanOrEqual, + GreaterThan, + GreaterThanOrEqual, + + LeftShift, + RightShift, + + // BitwiseAnd, + // BitwiseXor, + // BitwiseOr, + + LogicalAnd, + LogicalOr, + } +} + +public class NodeExpressionUnary(List tokens, NodeExpression target, NodeExpressionUnary.Op op) : NodeExpression(tokens) +{ + public NodeExpression Target { get; } = target; + public Op Operation { get; } = op; + + public enum Op + { + Negate, + Invert, + } +} + +public abstract class NodeType(List tokens) : Node(tokens); + +public class NodeTypeVoid(List tokens) : NodeType(tokens); + +public class NodeTypeUInt(List tokens, int width) : NodeType(tokens) +{ + public int Width { get; } = width; +} + +public class NodeTypeSInt(List tokens, int width) : NodeType(tokens) +{ + public int Width { get; } = width; +} + +public class NodeTypeBool(List tokens) : NodeType(tokens); + +public class NodeTypeString(List tokens) : NodeType(tokens); + +public class NodeTypeChar(List tokens) : NodeType(tokens); + +public class NodeTypeNamed(List tokens, List sections) : NodeType(tokens) +{ + public List Sections { get; } = sections; +} + +public class NodeTypeAnonymousStruct(List tokens, List fields) : NodeType(tokens) +{ + public List Fields { get; } = fields; + + public class Field(TokenIdent name, NodeType type) + { + public TokenIdent Name { get; } = name; + public NodeType Type { get; } = type; + } +} + +public class NodeTypeArray(List tokens, NodeType elementType) : NodeType(tokens) +{ + public NodeType ElementType { get; } = elementType; +} + +public class NodeTypePointer(List tokens, NodeType to) : NodeType(tokens) +{ + public NodeType To { get; } = to; +} + +public class NodeTypeFunc(List tokens, List parameters, NodeType returnType) : NodeType(tokens) +{ + public List Parameters { get; } = parameters; + public NodeType ReturnType { get; } = returnType; +} diff --git a/compiler/Program.cs b/compiler/Program.cs new file mode 100644 index 0000000..38bb364 --- /dev/null +++ b/compiler/Program.cs @@ -0,0 +1,179 @@ +using System.Diagnostics; +using Compiler; + +var nubFiles = new List(); +var libFiles = new List(); +var compileLib = false; + +for (int i = 0; i < args.Length; i++) +{ + string arg = args[i]; + + if (arg.StartsWith("--type=")) + { + var value = arg.Split("--type=")[1]; + switch (value) + { + case "lib": + compileLib = true; + break; + case "exe": + compileLib = false; + break; + default: + DiagnosticFormatter.Print(Diagnostic.Error("Type must be 'exe' or 'lib'").Build(), Console.Error); + return 1; + } + } + else if (arg.EndsWith(".nub")) + { + nubFiles.Add(arg); + } + else if (arg.EndsWith(".nublib")) + { + libFiles.Add(arg); + } + else if (arg == "--help") + { + Console.WriteLine(""" + Usage: nubc [options] + + Options: + --type=exe Compile the input files into an executable (default) + --type=lib Compile the input files into a library + --help Show this help message + + Files: + *.nub Nub source files to compile + *.nublib Precompiled Nub libraries to link + + Example: + nubc --type=exe main.nub utils.nub math.nublib + """); + } + else + { + DiagnosticFormatter.Print(Diagnostic.Error($"Unrecognized option '{arg}'").Build(), Console.Error); + return 1; + } +} + +var moduleGraphBuilder = ModuleGraph.CreateBuilder(); +var asts = new List(); +var archivePaths = new List(); + +foreach (var libPath in libFiles) +{ + var lib = NubLib.Unpack(libPath); + archivePaths.Add(lib.ArchivePath); + moduleGraphBuilder.AddManifest(lib.Manifest); +} + +foreach (var fileName in nubFiles) +{ + var file = File.ReadAllText(fileName); + + var tokens = Tokenizer.Tokenize(fileName, file, out var tokenizerDiagnostics); + + foreach (var diagnostic in tokenizerDiagnostics) + DiagnosticFormatter.Print(diagnostic, Console.Error); + + if (tokens == null) + return 1; + + var ast = Parser.Parse(fileName, tokens, out var parserDiagnostics); + + foreach (var diagnostic in parserDiagnostics) + DiagnosticFormatter.Print(diagnostic, Console.Error); + + if (ast == null) + return 1; + + moduleGraphBuilder.AddAst(ast); + asts.Add(ast); +} + +var moduleGraph = moduleGraphBuilder.Build(out var moduleGraphDiagnostics); + +foreach (var diagnostic in moduleGraphDiagnostics) + DiagnosticFormatter.Print(diagnostic, Console.Error); + +if (moduleGraph == null) + return 1; + +var functions = new List(); + +foreach (var ast in asts) +{ + foreach (var func in ast.Definitions.OfType()) + { + var typedFunction = TypeChecker.CheckFunction(ast.FileName, ast.ModuleName.Ident, func, moduleGraph, out var typeCheckerDiagnostics); + + foreach (var diagnostic in typeCheckerDiagnostics) + DiagnosticFormatter.Print(diagnostic, Console.Error); + + if (typedFunction == null) + return 1; + + functions.Add(typedFunction); + } +} + +if (Directory.Exists(".build")) +{ + CleanDirectory(".build"); +} +else +{ + Directory.CreateDirectory(".build"); +} + +string? entryPoint = null; + +if (!compileLib) +{ + if (!moduleGraph.TryResolveIdentifier("main", "main", true, out var info) || info.Type is not NubTypeFunc entryPointType) + { + DiagnosticFormatter.Print(Diagnostic.Error("func main::main(): i32 is not defined. If you wanted to compile as a library, specify --type=lib").Build(), Console.Error); + return 1; + } + + if (!entryPointType.ReturnType.IsAssignableTo(NubTypeSInt.Get(32))) + { + DiagnosticFormatter.Print(Diagnostic.Error($"Entrypoint must return an i32 (currently '{entryPointType.ReturnType}')").Build(), Console.Error); + return 1; + } + + entryPoint = info.MangledName; +} + +var outFile = Generator.Emit(functions, moduleGraph, entryPoint); + +if (compileLib) +{ + Process.Start("gcc", ["-Og", "-g", "-Wall", "-Werror", "-c", "-o", ".build/out.o", outFile, .. archivePaths]).WaitForExit(); + Process.Start("ar", ["rcs", ".build/out.a", ".build/out.o"]).WaitForExit(); + NubLib.Pack(".build/out.nublib", ".build/out.a", Manifest.Create(moduleGraph)); +} +else +{ + Process.Start("gcc", ["-Og", "-g", "-Wall", "-Werror", "-o", ".build/out", outFile, .. archivePaths]).WaitForExit(); +} + +return 0; + +static void CleanDirectory(string dirName) +{ + var dir = new DirectoryInfo(dirName); + + foreach (var file in dir.GetFiles()) + { + file.Delete(); + } + + foreach (var subdir in dir.GetDirectories()) + { + CleanDirectory(subdir.FullName); + subdir.Delete(); + } +} diff --git a/compiler/Tokenizer.cs b/compiler/Tokenizer.cs new file mode 100644 index 0000000..e2bab08 --- /dev/null +++ b/compiler/Tokenizer.cs @@ -0,0 +1,643 @@ +using System.Numerics; +using System.Text; + +namespace Compiler; + +public class Tokenizer +{ + public static List? Tokenize(string fileName, string contents, out List diagnostics) + { + return new Tokenizer(fileName, contents).Tokenize(out diagnostics); + } + + private Tokenizer(string fileName, string contents) + { + this.fileName = fileName; + this.contents = contents; + } + + private readonly string fileName; + private readonly string contents; + private int index; + private int line = 1; + private int column = 1; + + private List? Tokenize(out List diagnostics) + { + var tokens = new List(); + diagnostics = []; + + while (true) + { + try + { + if (!TryPeek(out var c)) + break; + + if (char.IsWhiteSpace(c)) + { + Consume(); + continue; + } + + if (c == '/' && Peek(1) == '/') + { + Consume(); + Consume(); + while (TryPeek(out c) && c != '\n') + Consume(); + + Consume(); + continue; + } + + tokens.Add(ParseToken()); + } + catch (CompileException e) + { + diagnostics.Add(e.Diagnostic); + // Skip current token if parsing failed, this prevents an infinite loop when ParseToken fails before consuming any tokens + TryConsume(out _); + } + } + + if (diagnostics.Any(x => x.Severity == Diagnostic.DiagnosticSeverity.Error)) + return null; + + return tokens; + } + + private Token ParseToken() + { + var startColumn = column; + var c = Peek()!.Value; + + if (char.IsDigit(c)) + { + switch (c) + { + case '0' when Peek(1) is 'x': + { + Consume(); + Consume(); + + var parsed = BigInteger.Zero; + var seenDigit = false; + + while (TryPeek(out c)) + { + if (c == '_') + { + Consume(); + continue; + } + + if (!char.IsAsciiHexDigit(c)) + break; + + seenDigit = true; + parsed <<= 4; + + Consume(); + parsed += c switch + { + >= '0' and <= '9' => c - '0', + >= 'a' and <= 'f' => c - 'a' + 10, + >= 'A' and <= 'F' => c - 'A' + 10, + _ => 0 + }; + } + + if (!seenDigit) + throw new CompileException(Diagnostic.Error("Expected hexadecimal digits after 0x").At(fileName, line, startColumn, column - startColumn).Build()); + + return new TokenIntLiteral(line, startColumn, column - startColumn, parsed); + } + case '0' when Peek(1) is 'b': + { + Consume(); + Consume(); + + var parsed = BigInteger.Zero; + var seenDigit = false; + + while (TryPeek(out c)) + { + if (c == '_') + { + Consume(); + continue; + } + + if (c is not '0' and not '1') + break; + + seenDigit = true; + parsed <<= 1; + + if (Consume() == '1') + parsed += BigInteger.One; + } + + if (!seenDigit) + throw new CompileException(Diagnostic.Error("Expected binary digits after 0b").At(fileName, line, startColumn, column - startColumn).Build()); + + return new TokenIntLiteral(line, startColumn, column - startColumn, parsed); + } + default: + { + var parsed = BigInteger.Zero; + + while (TryPeek(out c)) + { + if (c == '_') + { + Consume(); + continue; + } + + if (!char.IsDigit(c)) + break; + + parsed *= 10; + parsed += Consume() - '0'; + } + + return new TokenIntLiteral(line, startColumn, column - startColumn, parsed); + } + } + } + + switch (c) + { + case '"': + { + Consume(); + var buf = new StringBuilder(); + + while (true) + { + if (!TryPeek(out c)) + throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 0).Build()); + + if (c == '"') + break; + + if (c == '\n') + throw new CompileException(Diagnostic.Error("Unterminated string literal").At(fileName, line, column, 1).Build()); + + buf.Append(Consume()); + } + + Consume(); + return new TokenStringLiteral(line, startColumn, column - startColumn, buf.ToString()); + } + + case '{': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenCurly); + } + case '}': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseCurly); + } + case '[': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenSquare); + } + case ']': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseSquare); + } + case '(': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.OpenParen); + } + case ')': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.CloseParen); + } + case ',': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Comma); + } + case '.': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Period); + } + case ':' when Peek(1) is ':': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ColonColon); + } + case ':': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Colon); + } + case '^': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Caret); + } + case '!' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.BangEqual); + } + case '!': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Bang); + } + case '=' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.EqualEqual); + } + case '=': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Equal); + } + case '<' when Peek(1) is '<': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanLessThan); + } + case '<' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThanEqual); + } + case '<': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.LessThan); + } + case '>' when Peek(1) is '>': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanGreaterThan); + } + case '>' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThanEqual); + } + case '>': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.GreaterThan); + } + case '+' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PlusEqual); + } + case '+': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Plus); + } + case '-' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.MinusEqual); + } + case '-': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Minus); + } + case '*' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.StarEqual); + } + case '*': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Star); + } + case '/' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlashEqual); + } + case '/': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.ForwardSlash); + } + case '%' when Peek(1) is '=': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PercentEqual); + } + case '%': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Percent); + } + case '&' when Peek(1) is '&': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.AmpersandAmpersand); + } + case '&': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Ampersand); + } + case '|' when Peek(1) is '|': + { + Consume(); + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.PipePipe); + } + case '|': + { + Consume(); + return new TokenSymbol(line, startColumn, column - startColumn, Symbol.Pipe); + } + default: + { + if (char.IsLetter(c) || c == '_') + { + var buf = new StringBuilder(); + + while (TryPeek(out c) && (char.IsLetterOrDigit(c) || c == '_')) + buf.Append(Consume()); + + var value = buf.ToString(); + + return value switch + { + "func" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Func), + "struct" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Struct), + "packed" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Packed), + "enum" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Enum), + "new" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.New), + "match" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Match), + "let" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Let), + "if" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.If), + "else" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Else), + "while" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.While), + "for" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.For), + "in" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.In), + "return" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Return), + "module" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Module), + "export" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Export), + "extern" => new TokenKeyword(line, startColumn, column - startColumn, Keyword.Extern), + "true" => new TokenBoolLiteral(line, startColumn, column - startColumn, true), + "false" => new TokenBoolLiteral(line, startColumn, column - startColumn, false), + _ => new TokenIdent(line, startColumn, column - startColumn, value) + }; + } + + throw new CompileException(Diagnostic.Error($"Unexpected character '{c}'").At(fileName, line, column, 1).Build()); + } + } + } + + private bool TryConsume(out char c) + { + if (index >= contents.Length) + { + c = '\0'; + return false; + } + + c = contents[index]; + + if (c == '\n') + { + line += 1; + column = 1; + } + else + { + column += 1; + } + + index += 1; + + return true; + } + + private char Consume() + { + if (!TryConsume(out var c)) + throw new CompileException(Diagnostic.Error("Unexpected end of file").At(fileName, line, column, 0).Build()); + + return c; + } + + private char? Peek(int offset = 0) + { + if (index + offset >= contents.Length) + return null; + + return contents[index + offset]; + } + + private bool TryPeek(out char c) + { + if (index >= contents.Length) + { + c = '\0'; + return false; + } + + c = contents[index]; + return true; + } +} + +public abstract class Token(int line, int column, int length) +{ + public int Line { get; } = line; + public int Column { get; } = column; + public int Length { get; } = length; +} + +public class TokenIdent(int line, int column, int length, string ident) : Token(line, column, length) +{ + public string Ident { get; } = ident; +} + +public class TokenIntLiteral(int line, int column, int length, BigInteger value) : Token(line, column, length) +{ + public BigInteger Value { get; } = value; +} + +public class TokenStringLiteral(int line, int column, int length, string value) : Token(line, column, length) +{ + public string Value { get; } = value; +} + +public class TokenBoolLiteral(int line, int column, int length, bool value) : Token(line, column, length) +{ + public bool Value { get; } = value; +} + +public enum Symbol +{ + OpenCurly, + CloseCurly, + OpenParen, + CloseParen, + OpenSquare, + CloseSquare, + Comma, + Period, + Colon, + ColonColon, + Caret, + Bang, + Equal, + EqualEqual, + BangEqual, + LessThan, + LessThanLessThan, + LessThanEqual, + GreaterThan, + GreaterThanGreaterThan, + GreaterThanEqual, + Plus, + PlusEqual, + Minus, + MinusEqual, + Star, + StarEqual, + ForwardSlash, + ForwardSlashEqual, + Percent, + PercentEqual, + Ampersand, + AmpersandAmpersand, + Pipe, + PipePipe, +} + +public class TokenSymbol(int line, int column, int length, Symbol symbol) : Token(line, column, length) +{ + public Symbol Symbol { get; } = symbol; +} + +public enum Keyword +{ + Func, + Struct, + Packed, + Enum, + New, + Match, + Let, + If, + Else, + While, + For, + In, + Return, + Module, + Export, + Extern, +} + +public class TokenKeyword(int line, int column, int length, Keyword keyword) : Token(line, column, length) +{ + public Keyword Keyword { get; } = keyword; +} + +public static class TokenExtensions +{ + public static string AsString(this Symbol symbol) + { + return symbol switch + { + Symbol.OpenCurly => "{", + Symbol.CloseCurly => "}", + Symbol.OpenParen => "(", + Symbol.CloseParen => ")", + Symbol.OpenSquare => "[", + Symbol.CloseSquare => "]", + Symbol.Comma => ",", + Symbol.Period => ".", + Symbol.Colon => ":", + Symbol.ColonColon => "::", + Symbol.Caret => "^", + Symbol.Bang => "!", + Symbol.Equal => "=", + Symbol.EqualEqual => "==", + Symbol.BangEqual => "!=", + Symbol.LessThan => "<", + Symbol.LessThanLessThan => "<<", + Symbol.LessThanEqual => "<=", + Symbol.GreaterThan => ">", + Symbol.GreaterThanGreaterThan => ">>", + Symbol.GreaterThanEqual => ">=", + Symbol.Plus => "+", + Symbol.PlusEqual => "+=", + Symbol.Minus => "-", + Symbol.MinusEqual => "-=", + Symbol.Star => "*", + Symbol.StarEqual => "*=", + Symbol.ForwardSlash => "/", + Symbol.ForwardSlashEqual => "/=", + Symbol.Percent => "%", + Symbol.PercentEqual => "%=", + Symbol.Ampersand => "&", + Symbol.AmpersandAmpersand => "&&", + Symbol.Pipe => "|", + Symbol.PipePipe => "||", + _ => throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null) + }; + } + + public static string AsString(this Keyword symbol) + { + return symbol switch + { + Keyword.Func => "func", + Keyword.Struct => "struct", + Keyword.Packed => "packed", + Keyword.Enum => "enum", + Keyword.New => "new", + Keyword.Match => "enum", + Keyword.Let => "let", + Keyword.If => "if", + Keyword.Else => "else", + Keyword.While => "while", + Keyword.For => "for", + Keyword.In => "in", + Keyword.Return => "return", + Keyword.Module => "module", + Keyword.Export => "export", + Keyword.Extern => "extern", + _ => throw new ArgumentOutOfRangeException(nameof(symbol), symbol, null) + }; + } +} \ No newline at end of file diff --git a/compiler/TypeChecker.cs b/compiler/TypeChecker.cs new file mode 100644 index 0000000..7b20534 --- /dev/null +++ b/compiler/TypeChecker.cs @@ -0,0 +1,1106 @@ +using System.Data.Common; +using System.Diagnostics.CodeAnalysis; +using System.Formats.Tar; + +namespace Compiler; + +public class TypeChecker +{ + public static TypedNodeDefinitionFunc? CheckFunction(string fileName, string currentModule, NodeDefinitionFunc function, ModuleGraph moduleGraph, out List diagnostics) + { + return new TypeChecker(fileName, currentModule, function, moduleGraph).CheckFunction(out diagnostics); + } + + private TypeChecker(string fileName, string currentModule, NodeDefinitionFunc function, ModuleGraph moduleGraph) + { + this.fileName = fileName; + this.currentModule = currentModule; + this.function = function; + this.moduleGraph = moduleGraph; + } + + private readonly string fileName; + private readonly string currentModule; + private readonly NodeDefinitionFunc function; + private NubType functionReturnType = null!; + private readonly ModuleGraph moduleGraph; + private readonly Stack> scopes = new(); + + private TypedNodeDefinitionFunc? CheckFunction(out List diagnostics) + { + diagnostics = []; + + var parameters = new List(); + var invalidParameter = false; + TypedNodeStatement? body = null; + + if (function.ReturnType == null) + { + functionReturnType = NubTypeVoid.Instance; + } + else + { + try + { + functionReturnType = ResolveType(function.ReturnType); + } + catch (CompileException e) + { + diagnostics.Add(e.Diagnostic); + return null; + } + } + + using (EnterScope()) + { + foreach (var parameter in function.Parameters) + { + NubType parameterType; + + try + { + parameterType = ResolveType(parameter.Type); + DeclareLocalIdentifier(parameter.Name, parameterType); + } + catch (CompileException e) + { + diagnostics.Add(e.Diagnostic); + invalidParameter = true; + continue; + } + + parameters.Add(new TypedNodeDefinitionFunc.Param(parameter.Tokens, parameter.Name, parameterType)); + } + + try + { + body = CheckStatement(function.Body); + } + catch (CompileException e) + { + diagnostics.Add(e.Diagnostic); + } + + if (body == null || invalidParameter) + return null; + + return new TypedNodeDefinitionFunc(function.Tokens, currentModule, function.Name, parameters, body, functionReturnType); + } + } + + private TypedNodeStatement CheckStatement(NodeStatement node) + { + return node switch + { + NodeStatementAssignment statement => CheckStatementAssignment(statement), + NodeStatementBlock statement => CheckStatementBlock(statement), + NodeStatementExpression statement => CheckStatementExpression(statement), + NodeStatementIf statement => CheckStatementIf(statement), + NodeStatementReturn statement => CheckStatementReturn(statement), + NodeStatementVariableDeclaration statement => CheckStatementVariableDeclaration(statement), + NodeStatementWhile statement => CheckStatementWhile(statement), + NodeStatementFor statement => CheckStatementFor(statement), + NodeStatementMatch statement => CheckStatementMatch(statement), + _ => throw new ArgumentOutOfRangeException(nameof(node)) + }; + } + + private TypedNodeStatementAssignment CheckStatementAssignment(NodeStatementAssignment statement) + { + var target = CheckExpression(statement.Target, null); + var value = CheckExpression(statement.Value, target.Type); + + return new TypedNodeStatementAssignment(statement.Tokens, target, value); + } + + private TypedNodeStatementBlock CheckStatementBlock(NodeStatementBlock statement) + { + using (EnterScope()) + { + var statements = statement.Statements.Select(CheckStatement).ToList(); + return new TypedNodeStatementBlock(statement.Tokens, statements); + } + } + + private TypedNodeStatementFuncCall CheckStatementExpression(NodeStatementExpression statement) + { + if (statement.Expression is not NodeExpressionFuncCall funcCall) + throw BasicError("Expected statement or function call", statement); + + var expr = CheckExpressionFuncCall(funcCall, null); + + return new TypedNodeStatementFuncCall(expr.Tokens, expr.Target, expr.Parameters); + } + + private TypedNodeStatementIf CheckStatementIf(NodeStatementIf statement) + { + var condition = CheckExpression(statement.Condition, NubTypeBool.Instance); + if (!condition.Type.IsAssignableTo(NubTypeBool.Instance)) + throw BasicError("Condition part of if statement must be a boolean", condition); + + TypedNodeStatement thenBlock; + + using (EnterScope()) + { + thenBlock = CheckStatement(statement.ThenBlock); + } + + TypedNodeStatement? elseBlock; + + using (EnterScope()) + { + elseBlock = statement.ElseBlock == null ? null : CheckStatement(statement.ElseBlock); + } + + return new TypedNodeStatementIf(statement.Tokens, condition, thenBlock, elseBlock); + } + + private TypedNodeStatementReturn CheckStatementReturn(NodeStatementReturn statement) + { + if (statement.Value == null) + { + if (functionReturnType is not NubTypeVoid) + throw BasicError($"Missing return value. Expected '{functionReturnType}'", statement); + + return new TypedNodeStatementReturn(statement.Tokens, null); + } + else + { + var value = CheckExpression(statement.Value, functionReturnType); + if (!value.Type.IsAssignableTo(functionReturnType)) + throw BasicError($"Type of returned value ({value.Type}) is not assignable to the return type of the function ({functionReturnType})", value); + + return new TypedNodeStatementReturn(statement.Tokens, value); + } + } + + private TypedNodeStatementVariableDeclaration CheckStatementVariableDeclaration(NodeStatementVariableDeclaration statement) + { + NubType? type = null; + if (statement.Type != null) + type = ResolveType(statement.Type); + + var value = CheckExpression(statement.Value, type); + + if (type is not null && !value.Type.IsAssignableTo(type)) + throw BasicError("Type of variable does match type of assigned value", value); + + type ??= value.Type; + + DeclareLocalIdentifier(statement.Name, type); + + return new TypedNodeStatementVariableDeclaration(statement.Tokens, statement.Name, type, value); + } + + private TypedNodeStatementWhile CheckStatementWhile(NodeStatementWhile statement) + { + var condition = CheckExpression(statement.Condition, NubTypeBool.Instance); + if (!condition.Type.IsAssignableTo(NubTypeBool.Instance)) + throw BasicError("Condition part of if statement must be a boolean", condition); + + using (EnterScope()) + { + var body = CheckStatement(statement.Body); + return new TypedNodeStatementWhile(statement.Tokens, condition, body); + } + } + + private TypedNodeStatementFor CheckStatementFor(NodeStatementFor statement) + { + var array = CheckExpression(statement.Array, null); + if (array.Type is not NubTypeArray arrayType) + throw BasicError($"Cannot iterate over non-array type '{array.Type}'", statement.Array); + + TypedNodeStatement body; + using (EnterScope()) + { + DeclareLocalIdentifier(statement.VariableName, arrayType.ElementType); + body = CheckStatement(statement.Body); + } + + return new TypedNodeStatementFor(statement.Tokens, statement.VariableName, array, body); + } + + private TypedNodeStatementMatch CheckStatementMatch(NodeStatementMatch statement) + { + var target = CheckExpression(statement.Target, null); + if (target.Type is not NubTypeEnum enumType) + throw BasicError("A match statement can only be used on enum types", target); + + if (!moduleGraph.TryResolveType(enumType.Module, enumType.Name, enumType.Module == currentModule, out var info)) + throw BasicError($"Type '{enumType}' not found", target); + + if (info is not Module.TypeInfoEnum enumInfo) + throw BasicError($"Type '{enumType}' is not an enum", target); + + var uncoveredCases = enumInfo.Variants.Select(x => x.Name).ToList(); + + var cases = new List(); + foreach (var @case in statement.Cases) + { + var variant = enumInfo.Variants.FirstOrDefault(x => x.Name == @case.Variant.Ident); + if (variant == null) + throw BasicError($"Enum type'{enumType}' does not have a variant named '{@case.Variant.Ident}'", @case.Variant); + + uncoveredCases.Remove(@case.Variant.Ident); + + using (EnterScope()) + { + if (@case.VariableName != null) + { + if (variant.Type is null) + throw BasicError("Cannot capture variable for enum variant without type", @case.VariableName); + + DeclareLocalIdentifier(@case.VariableName, variant.Type); + } + + var body = CheckStatement(@case.Body); + + cases.Add(new TypedNodeStatementMatch.Case(@case.Tokens, @case.Variant, @case.VariableName, body)); + } + } + + if (uncoveredCases.Any()) + throw BasicError($"Match statement does not cover the following cases: {string.Join(", ", uncoveredCases)}", statement); + + return new TypedNodeStatementMatch(statement.Tokens, target, cases); + } + + private TypedNodeExpression CheckExpression(NodeExpression node, NubType? expectedType) + { + return node switch + { + NodeExpressionBinary expression => CheckExpressionBinary(expression, expectedType), + NodeExpressionUnary expression => CheckExpressionUnary(expression, expectedType), + NodeExpressionBoolLiteral expression => CheckExpressionBoolLiteral(expression, expectedType), + NodeExpressionIdent expression => CheckExpressionIdent(expression, expectedType), + NodeExpressionIntLiteral expression => CheckExpressionIntLiteral(expression, expectedType), + NodeExpressionMemberAccess expression => CheckExpressionMemberAccess(expression, expectedType), + NodeExpressionFuncCall expression => CheckExpressionFuncCall(expression, expectedType), + NodeExpressionStringLiteral expression => CheckExpressionStringLiteral(expression, expectedType), + NodeExpressionStructLiteral expression => CheckExpressionStructLiteral(expression, expectedType), + NodeExpressionEnumLiteral expression => CheckExpressionEnumLiteral(expression, expectedType), + NodeExpressionStringConstructor expression => CheckExpressionStringConstructor(expression, expectedType), + NodeExpressionArrayLiteral expression => CheckExpressionArrayLiteral(expression, expectedType), + _ => throw new ArgumentOutOfRangeException(nameof(node)) + }; + } + + private TypedNodeExpressionBinary CheckExpressionBinary(NodeExpressionBinary expression, NubType? expectedType) + { + // todo(nub31): Add proper inference here + var left = CheckExpression(expression.Left, null); + var right = CheckExpression(expression.Right, null); + NubType type; + + switch (expression.Operation) + { + case NodeExpressionBinary.Op.Add: + { + if (left.Type is NubTypeString) + { + if (right.Type is not NubTypeString) + throw BasicError("Right hand side of string concatination operator must be a string", right); + + return new TypedNodeExpressionBinary(expression.Tokens, NubTypeString.Instance, left, CheckExpressionBinaryOperation(expression.Operation), right); + } + + if (left.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for left hand side arithmetic operation: {left.Type}", left); + + if (right.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for right hand side arithmetic operation: {right.Type}", right); + + type = left.Type; + break; + } + case NodeExpressionBinary.Op.Subtract: + case NodeExpressionBinary.Op.Multiply: + case NodeExpressionBinary.Op.Divide: + case NodeExpressionBinary.Op.Modulo: + { + if (left.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for left hand side arithmetic operation: {left.Type}", left); + + if (right.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for right hand side arithmetic operation: {right.Type}", right); + + type = left.Type; + break; + } + case NodeExpressionBinary.Op.LeftShift: + case NodeExpressionBinary.Op.RightShift: + { + if (left.Type is not NubTypeUInt) + throw BasicError($"Unsupported type for left hand side of left/right shift operation: {left.Type}", left); + + if (right.Type is not NubTypeUInt) + throw BasicError($"Unsupported type for right hand side of left/right shift operation: {right.Type}", right); + + type = left.Type; + break; + } + case NodeExpressionBinary.Op.Equal: + case NodeExpressionBinary.Op.NotEqual: + case NodeExpressionBinary.Op.LessThan: + case NodeExpressionBinary.Op.LessThanOrEqual: + case NodeExpressionBinary.Op.GreaterThan: + case NodeExpressionBinary.Op.GreaterThanOrEqual: + { + if (left.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for left hand side of comparison: {left.Type}", left); + + if (right.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for right hand side of comparison: {right.Type}", right); + + type = NubTypeBool.Instance; + break; + } + case NodeExpressionBinary.Op.LogicalAnd: + case NodeExpressionBinary.Op.LogicalOr: + { + if (left.Type is not NubTypeBool) + throw BasicError($"Unsupported type for left hand side of logical operation: {left.Type}", left); + + if (right.Type is not NubTypeBool) + throw BasicError($"Unsupported type for right hand side of logical operation: {right.Type}", right); + + type = NubTypeBool.Instance; + break; + } + default: + throw new ArgumentOutOfRangeException(); + } + + return new TypedNodeExpressionBinary(expression.Tokens, type, left, CheckExpressionBinaryOperation(expression.Operation), right); + } + + private static TypedNodeExpressionBinary.Op CheckExpressionBinaryOperation(NodeExpressionBinary.Op op) + { + return op switch + { + NodeExpressionBinary.Op.Add => TypedNodeExpressionBinary.Op.Add, + NodeExpressionBinary.Op.Subtract => TypedNodeExpressionBinary.Op.Subtract, + NodeExpressionBinary.Op.Multiply => TypedNodeExpressionBinary.Op.Multiply, + NodeExpressionBinary.Op.Divide => TypedNodeExpressionBinary.Op.Divide, + NodeExpressionBinary.Op.Modulo => TypedNodeExpressionBinary.Op.Modulo, + NodeExpressionBinary.Op.Equal => TypedNodeExpressionBinary.Op.Equal, + NodeExpressionBinary.Op.NotEqual => TypedNodeExpressionBinary.Op.NotEqual, + NodeExpressionBinary.Op.LessThan => TypedNodeExpressionBinary.Op.LessThan, + NodeExpressionBinary.Op.LessThanOrEqual => TypedNodeExpressionBinary.Op.LessThanOrEqual, + NodeExpressionBinary.Op.GreaterThan => TypedNodeExpressionBinary.Op.GreaterThan, + NodeExpressionBinary.Op.GreaterThanOrEqual => TypedNodeExpressionBinary.Op.GreaterThanOrEqual, + NodeExpressionBinary.Op.LeftShift => TypedNodeExpressionBinary.Op.LeftShift, + NodeExpressionBinary.Op.RightShift => TypedNodeExpressionBinary.Op.RightShift, + NodeExpressionBinary.Op.LogicalAnd => TypedNodeExpressionBinary.Op.LogicalAnd, + NodeExpressionBinary.Op.LogicalOr => TypedNodeExpressionBinary.Op.LogicalOr, + _ => throw new ArgumentOutOfRangeException(nameof(op), op, null) + }; + } + + private TypedNodeExpressionUnary CheckExpressionUnary(NodeExpressionUnary expression, NubType? expectedType) + { + // todo(nub31): Add proper inference here + var target = CheckExpression(expression.Target, null); + NubType type; + + switch (expression.Operation) + { + case NodeExpressionUnary.Op.Negate: + { + if (target.Type is not NubTypeSInt and not NubTypeUInt) + throw BasicError($"Unsupported type for negation: {target.Type}", target); + + type = target.Type; + break; + } + case NodeExpressionUnary.Op.Invert: + { + if (target.Type is not NubTypeBool) + throw BasicError($"Unsupported type for inversion: {target.Type}", target); + + type = NubTypeBool.Instance; + break; + } + default: + throw new ArgumentOutOfRangeException(); + } + + return new TypedNodeExpressionUnary(expression.Tokens, type, target, CheckExpressionUnaryOperation(expression.Operation)); + } + + private static TypedNodeExpressionUnary.Op CheckExpressionUnaryOperation(NodeExpressionUnary.Op op) + { + return op switch + { + NodeExpressionUnary.Op.Negate => TypedNodeExpressionUnary.Op.Negate, + NodeExpressionUnary.Op.Invert => TypedNodeExpressionUnary.Op.Invert, + _ => throw new ArgumentOutOfRangeException(nameof(op), op, null) + }; + } + + private TypedNodeExpressionBoolLiteral CheckExpressionBoolLiteral(NodeExpressionBoolLiteral expression, NubType? expectedType) + { + return new TypedNodeExpressionBoolLiteral(expression.Tokens, NubTypeBool.Instance, expression.Value); + } + + private TypedNodeExpression CheckExpressionIdent(NodeExpressionIdent expression, NubType? expectedType) + { + if (expression.Sections.Count == 1) + { + var name = expression.Sections[0]; + + var localType = GetIdentifierType(name.Ident); + if (localType is not null) + return new TypedNodeExpressionLocalIdent(expression.Tokens, localType, name.Ident); + + if (moduleGraph.TryResolveIdentifier(currentModule, name.Ident, true, out var ident)) + return new TypedNodeExpressionGlobalIdent(expression.Tokens, ident.Type, currentModule, name.Ident); + } + else if (expression.Sections.Count == 2) + { + var module = expression.Sections[0].Ident; + var name = expression.Sections[1].Ident; + + if (moduleGraph.TryResolveIdentifier(module, name, true, out var ident)) + return new TypedNodeExpressionGlobalIdent(expression.Tokens, ident.Type, module, name); + } + + throw BasicError($"Unknown identifier '{string.Join("::", expression.Sections.Select(x => x.Ident))}'", expression); + } + + private TypedNodeExpressionIntLiteral CheckExpressionIntLiteral(NodeExpressionIntLiteral expression, NubType? expectedType) + { + NubType? type = null; + + if (expectedType is NubTypeSInt or NubTypeUInt) + type = expectedType; + + type ??= NubTypeSInt.Get(32); + + return new TypedNodeExpressionIntLiteral(expression.Tokens, type, expression.Value); + } + + private TypedNodeExpression CheckExpressionMemberAccess(NodeExpressionMemberAccess expression, NubType? expectedType) + { + var target = CheckExpression(expression.Target, null); + + switch (target.Type) + { + case NubTypeString stringType: + { + switch (expression.Name.Ident) + { + case "length": + return new TypedNodeExpressionStringLength(expression.Tokens, NubTypeUInt.Get(64), target); + case "ptr": + return new TypedNodeExpressionStringPointer(expression.Tokens, NubTypePointer.Get(NubTypeChar.Instance), target); + default: + throw BasicError($"'{expression.Name.Ident}' is not a member of type {stringType}", expression.Name); + } + } + case NubTypeArray arrayType: + { + switch (expression.Name.Ident) + { + case "count": + return new TypedNodeExpressionArrayCount(expression.Tokens, NubTypeUInt.Get(64), target); + case "ptr": + return new TypedNodeExpressionArrayPointer(expression.Tokens, NubTypePointer.Get(arrayType.ElementType), target); + default: + throw BasicError($"'{expression.Name.Ident}' is not a member of type {arrayType}", expression.Name); + } + } + case NubTypeStruct structType: + { + if (!moduleGraph.TryResolveModule(structType.Module, out var module)) + throw BasicError($"Module '{structType.Module}' not found", expression.Target); + + if (!module.TryResolveType(structType.Name, currentModule == structType.Module, out var typeDef)) + throw BasicError($"Type '{structType.Name}' not found in module '{structType.Module}'", expression.Target); + + if (typeDef is not Module.TypeInfoStruct structDef) + throw BasicError($"Type '{target.Type}' is not a struct", expression.Target); + + var field = structDef.Fields.FirstOrDefault(x => x.Name == expression.Name.Ident); + if (field == null) + throw BasicError($"Struct '{target.Type}' does not have a field matching the name '{expression.Name.Ident}'", target); + + return new TypedNodeExpressionStructMemberAccess(expression.Tokens, field.Type, target, expression.Name); + } + case NubTypeAnonymousStruct anonymousStructType: + { + var field = anonymousStructType.Fields.FirstOrDefault(x => x.Name == expression.Name.Ident); + if (field == null) + throw BasicError($"Struct '{target.Type}' does not have a field matching the name '{expression.Name.Ident}'", target); + + return new TypedNodeExpressionStructMemberAccess(expression.Tokens, field.Type, target, expression.Name); + } + default: + throw BasicError($"{target.Type} has no member '{expression.Name.Ident}'", target); + } + } + + private TypedNodeExpressionFuncCall CheckExpressionFuncCall(NodeExpressionFuncCall expression, NubType? expectedType) + { + var target = CheckExpression(expression.Target, null); + if (target.Type is not NubTypeFunc funcType) + throw BasicError("Expected a function type", target); + + if (funcType.Parameters.Count != expression.Parameters.Count) + throw BasicError($"Expected {funcType.Parameters.Count} parameters but got {expression.Parameters.Count}", expression); + + var parameters = new List(); + for (int i = 0; i < expression.Parameters.Count; i++) + { + var parameter = CheckExpression(expression.Parameters[i], funcType.Parameters[i]); + if (!parameter.Type.IsAssignableTo(funcType.Parameters[i])) + throw BasicError($"Parameter {i + 1} ({parameter.Type}) does is not assignable to '{funcType.Parameters[i]}'", parameter); + + parameters.Add(parameter); + } + + return new TypedNodeExpressionFuncCall(expression.Tokens, funcType.ReturnType, target, parameters); + } + + private TypedNodeExpressionStringLiteral CheckExpressionStringLiteral(NodeExpressionStringLiteral expression, NubType? expectedType) + { + return new TypedNodeExpressionStringLiteral(expression.Tokens, NubTypeString.Instance, expression.Value); + } + + private TypedNodeExpressionStructLiteral CheckExpressionStructLiteral(NodeExpressionStructLiteral expression, NubType? expectedType) + { + if (expression.Type != null) + { + var type = ResolveType(expression.Type); + if (type is not NubTypeStruct structType) + throw BasicError("Type of struct literal is not a struct", expression); + + if (!moduleGraph.TryResolveType(structType.Module, structType.Name, structType.Module == currentModule, out var info)) + throw BasicError($"Type '{structType}' struct literal not found", expression); + + if (info is not Module.TypeInfoStruct structInfo) + throw BasicError($"Type '{structType}' is not a struct", expression.Type); + + var initializers = new List(); + foreach (var initializer in expression.Initializers) + { + var field = structInfo.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident); + if (field == null) + throw BasicError($"Field '{initializer.Name.Ident}' does not exist on struct '{structType.Module}::{structType.Name}'", initializer.Name); + + var value = CheckExpression(initializer.Value, field.Type); + if (!value.Type.IsAssignableTo(field.Type)) + throw BasicError($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})", initializer.Name); + + initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value)); + } + + return new TypedNodeExpressionStructLiteral(expression.Tokens, structType, initializers); + } + else if (expectedType is NubTypeStruct structType) + { + if (!moduleGraph.TryResolveType(structType.Module, structType.Name, structType.Module == currentModule, out var info)) + throw BasicError($"Type '{structType}' struct literal not found", expression); + + if (info is not Module.TypeInfoStruct structInfo) + throw BasicError($"Type '{structType}' is not a struct", expression); + + var initializers = new List(); + foreach (var initializer in expression.Initializers) + { + var field = structInfo.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident); + if (field == null) + throw BasicError($"Field '{initializer.Name.Ident}' does not exist on struct '{structType.Module}::{structType.Name}'", initializer.Name); + + var value = CheckExpression(initializer.Value, field.Type); + if (!value.Type.IsAssignableTo(field.Type)) + throw BasicError($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})", initializer.Name); + + initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value)); + } + + return new TypedNodeExpressionStructLiteral(expression.Tokens, structType, initializers); + } + else if (expectedType is NubTypeAnonymousStruct anonymousStructType) + { + var initializers = new List(); + foreach (var initializer in expression.Initializers) + { + var field = anonymousStructType.Fields.FirstOrDefault(x => x.Name == initializer.Name.Ident); + if (field == null) + throw BasicError($"Field '{initializer.Name.Ident}' does not exist on anonymous struct '{anonymousStructType}'", initializer.Name); + + var value = CheckExpression(initializer.Value, field.Type); + if (!value.Type.IsAssignableTo(field.Type)) + throw BasicError($"Type of assignment ({value.Type}) does not match expected type of field '{field.Name}' ({field.Type})", initializer.Name); + + initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value)); + } + + return new TypedNodeExpressionStructLiteral(expression.Tokens, anonymousStructType, initializers); + } + else + { + var initializers = new List(); + foreach (var initializer in expression.Initializers) + { + var value = CheckExpression(initializer.Value, null); + initializers.Add(new TypedNodeExpressionStructLiteral.Initializer(initializer.Tokens, initializer.Name, value)); + } + + var type = NubTypeAnonymousStruct.Get(initializers.Select(x => new NubTypeAnonymousStruct.Field(x.Name.Ident, x.Value.Type)).ToList()); + + return new TypedNodeExpressionStructLiteral(expression.Tokens, type, initializers); + } + } + + private TypedNodeExpressionEnumLiteral CheckExpressionEnumLiteral(NodeExpressionEnumLiteral expression, NubType? expectedType) + { + var type = ResolveType(expression.Type); + if (type is not NubTypeEnumVariant variantType) + throw BasicError("Expected enum variant type", expression.Type); + + if (!moduleGraph.TryResolveType(variantType.EnumType.Module, variantType.EnumType.Name, variantType.EnumType.Module == currentModule, out var info)) + throw BasicError($"Type '{variantType.EnumType}' not found", expression.Type); + + if (info is not Module.TypeInfoEnum enumInfo) + throw BasicError($"Type '{variantType.EnumType}' is not an enum", expression.Type); + + var variant = enumInfo.Variants.FirstOrDefault(x => x.Name == variantType.Variant); + if (variant == null) + throw BasicError($"Enum '{variantType.EnumType}' does not have a variant named '{variantType.Variant}'", expression.Type); + + if (expression.Value == null && variant.Type is not null) + throw BasicError($"Enum variant '{variantType}' expects a value of type '{variant.Type}'", expression.Type); + + if (expression.Value != null && variant.Type is null) + throw BasicError($"Enum variant '{variantType}' does not expect any data", expression.Value); + + var value = expression.Value == null ? null : CheckExpression(expression.Value, variant.Type); + + return new TypedNodeExpressionEnumLiteral(expression.Tokens, type, value); + } + + private TypedNodeExpressionStringConstructor CheckExpressionStringConstructor(NodeExpressionStringConstructor expression, NubType? expectedType) + { + var stringPoitnerType = NubTypePointer.Get(NubTypeChar.Instance); + + var value = CheckExpression(expression.Value, stringPoitnerType); + if (!value.Type.IsAssignableTo(stringPoitnerType)) + throw BasicError($"Value of string constructor must be assignable to {stringPoitnerType}", value); + + return new TypedNodeExpressionStringConstructor(expression.Tokens, NubTypeString.Instance, value); + } + + private TypedNodeExpressionArrayLiteral CheckExpressionArrayLiteral(NodeExpressionArrayLiteral expression, NubType? expectedType) + { + NubType? elementType = null; + if (expectedType is NubTypeArray arrayType) + elementType = arrayType.ElementType; + + var values = new List(); + + foreach (var value in expression.Values) + { + var checkedValue = CheckExpression(value, elementType); + elementType ??= checkedValue.Type; + + if (!checkedValue.Type.IsAssignableTo(elementType)) + throw BasicError($"Type '{checkedValue.Type}' is not assignable to type of element '{elementType}'", checkedValue); + + values.Add(checkedValue); + } + + if (elementType is null) + throw BasicError("Unable to infer type of array element", expression); + + return new TypedNodeExpressionArrayLiteral(expression.Tokens, NubTypeArray.Get(elementType), values); + } + + private NubType ResolveType(NodeType node) + { + return node switch + { + NodeTypeBool => NubTypeBool.Instance, + NodeTypeNamed type => ResolveNamedType(type), + NodeTypeAnonymousStruct type => NubTypeAnonymousStruct.Get(type.Fields.Select(x => new NubTypeAnonymousStruct.Field(x.Name.Ident, ResolveType(x.Type))).ToList()), + NodeTypeFunc type => NubTypeFunc.Get(type.Parameters.Select(ResolveType).ToList(), ResolveType(type.ReturnType)), + NodeTypePointer type => NubTypePointer.Get(ResolveType(type.To)), + NodeTypeSInt type => NubTypeSInt.Get(type.Width), + NodeTypeUInt type => NubTypeUInt.Get(type.Width), + NodeTypeString => NubTypeString.Instance, + NodeTypeVoid => NubTypeVoid.Instance, + NodeTypeArray type => NubTypeArray.Get(ResolveType(type.ElementType)), + _ => throw new ArgumentOutOfRangeException(nameof(node)) + }; + } + + private NubType ResolveNamedType(NodeTypeNamed type) + { + return type.Sections.Count switch + { + 3 => ResolveThreePartType(type.Sections[0], type.Sections[1], type.Sections[2]), + 2 => ResolveTwoPartType(type.Sections[0], type.Sections[1]), + 1 => ResolveOnePartType(type.Sections[0]), + _ => throw BasicError("Invalid type name", type) + }; + } + + private NubType ResolveThreePartType(TokenIdent first, TokenIdent second, TokenIdent third) + { + if (TryResolveEnumVariant(first.Ident, second.Ident, third.Ident, out var variantType)) + return variantType; + + throw BasicError($"Enum '{first.Ident}::{second.Ident}::{third.Ident}' does not have a variant named '{third.Ident}'", third); + } + + private NubType ResolveTwoPartType(TokenIdent first, TokenIdent second) + { + if (TryResolveEnumVariant(currentModule, first.Ident, second.Ident, out var variantType)) + return variantType; + + var typeInfo = ResolveModuleTypeInfo(ResolveModule(first), second); + return typeInfo switch + { + Module.TypeInfoStruct => NubTypeStruct.Get(first.Ident, second.Ident), + Module.TypeInfoEnum => NubTypeEnum.Get(first.Ident, second.Ident), + _ => throw new ArgumentOutOfRangeException(nameof(typeInfo)) + }; + } + + private NubType ResolveOnePartType(TokenIdent name) + { + if (!moduleGraph.TryResolveModule(currentModule, out var module)) + throw BasicError($"Module '{currentModule}' not found", name); + + var typeInfo = ResolveModuleTypeInfo(module, name); + return typeInfo switch + { + Module.TypeInfoStruct => NubTypeStruct.Get(currentModule, name.Ident), + Module.TypeInfoEnum => NubTypeEnum.Get(currentModule, name.Ident), + _ => throw new ArgumentOutOfRangeException(nameof(typeInfo)) + }; + } + + private Module ResolveModule(TokenIdent name) + { + if (!moduleGraph.TryResolveModule(name.Ident, out var module)) + throw BasicError($"Module '{name.Ident}' not found", name); + + return module; + } + + private Module.TypeInfo ResolveModuleTypeInfo(Module module, TokenIdent name) + { + if (!module.TryResolveType(name.Ident, currentModule == module.Name, out var type)) + throw BasicError($"Named type '{module.Name}::{name.Ident}' not found", name); + + return type; + } + + private bool TryResolveEnumVariant(string moduleName, string enumName, string variantName, [NotNullWhen(true)] out NubType? result) + { + result = null; + + if (!moduleGraph.TryResolveModule(moduleName, out var module)) + return false; + + if (!module.TryResolveType(enumName, true, out var type)) + return false; + + if (type is not Module.TypeInfoEnum enumInfo) + return false; + + var variant = enumInfo.Variants.FirstOrDefault(v => v.Name == variantName); + + if (variant == null) + return false; + + result = NubTypeEnumVariant.Get(NubTypeEnum.Get(moduleName, enumName), variantName); + return true; + } + + private CompileException BasicError(string message, TokenIdent ident) + { + return new CompileException(Diagnostic.Error(message).At(fileName, ident).Build()); + } + + private CompileException BasicError(string message, Node node) + { + return new CompileException(Diagnostic.Error(message).At(fileName, node).Build()); + } + + private CompileException BasicError(string message, TypedNode node) + { + return new CompileException(Diagnostic.Error(message).At(fileName, node).Build()); + } + + public void DeclareLocalIdentifier(TokenIdent name, NubType type) + { + var existing = GetIdentifierType(name.Ident); + if (existing is not null) + throw BasicError($"Local identifier '{name.Ident}' is already defined", name); + + scopes.Peek().Add(name.Ident, type); + } + + public NubType? GetIdentifierType(string name) + { + foreach (var scope in scopes) + { + if (scope.TryGetValue(name, out var type)) + { + return type; + } + } + + return null; + } + + public IDisposable EnterScope() + { + scopes.Push([]); + return new ScopeGuard(this); + } + + private void ExitScope() + { + scopes.Pop(); + } + + private sealed class ScopeGuard(TypeChecker owner) : IDisposable + { + public void Dispose() + { + owner.ExitScope(); + } + } +} + +public abstract class TypedNode(List tokens) +{ + public List Tokens { get; } = tokens; +} + +public abstract class TypedNodeDefinition(List tokens, string module) : TypedNode(tokens) +{ + public string Module { get; } = module; +} + +public class TypedNodeDefinitionFunc(List tokens, string module, TokenIdent name, List parameters, TypedNodeStatement body, NubType returnType) : TypedNodeDefinition(tokens, module) +{ + public TokenIdent Name { get; } = name; + public List Parameters { get; } = parameters; + public TypedNodeStatement Body { get; } = body; + public NubType ReturnType { get; } = returnType; + + public NubTypeFunc GetNubType() + { + return NubTypeFunc.Get(Parameters.Select(x => x.Type).ToList(), ReturnType); + } + + public class Param(List tokens, TokenIdent name, NubType type) : TypedNode(tokens) + { + public TokenIdent Name { get; } = name; + public NubType Type { get; } = type; + } +} + +public abstract class TypedNodeStatement(List tokens) : TypedNode(tokens); + +public class TypedNodeStatementBlock(List tokens, List statements) : TypedNodeStatement(tokens) +{ + public List Statements { get; } = statements; +} + +public class TypedNodeStatementFuncCall(List tokens, TypedNodeExpression target, List parameters) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression Target { get; } = target; + public List Parameters { get; } = parameters; +} + +public class TypedNodeStatementReturn(List tokens, TypedNodeExpression? value) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression? Value { get; } = value; +} + +public class TypedNodeStatementVariableDeclaration(List tokens, TokenIdent name, NubType type, TypedNodeExpression value) : TypedNodeStatement(tokens) +{ + public TokenIdent Name { get; } = name; + public NubType Type { get; } = type; + public TypedNodeExpression Value { get; } = value; +} + +public class TypedNodeStatementAssignment(List tokens, TypedNodeExpression target, TypedNodeExpression value) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression Target { get; } = target; + public TypedNodeExpression Value { get; } = value; +} + +public class TypedNodeStatementIf(List tokens, TypedNodeExpression condition, TypedNodeStatement thenBlock, TypedNodeStatement? elseBlock) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression Condition { get; } = condition; + public TypedNodeStatement ThenBlock { get; } = thenBlock; + public TypedNodeStatement? ElseBlock { get; } = elseBlock; +} + +public class TypedNodeStatementWhile(List tokens, TypedNodeExpression condition, TypedNodeStatement body) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression Condition { get; } = condition; + public TypedNodeStatement Body { get; } = body; +} + +public class TypedNodeStatementFor(List tokens, TokenIdent variableName, TypedNodeExpression array, TypedNodeStatement body) : TypedNodeStatement(tokens) +{ + public TokenIdent VariableName { get; } = variableName; + public TypedNodeExpression Array { get; } = array; + public TypedNodeStatement Body { get; } = body; +} + +public class TypedNodeStatementMatch(List tokens, TypedNodeExpression target, List cases) : TypedNodeStatement(tokens) +{ + public TypedNodeExpression Target { get; } = target; + public List Cases { get; } = cases; + + public class Case(List tokens, TokenIdent type, TokenIdent? variableName, TypedNodeStatement body) : Node(tokens) + { + public TokenIdent Variant { get; } = type; + public TokenIdent? VariableName { get; } = variableName; + public TypedNodeStatement Body { get; } = body; + } +} + +public abstract class TypedNodeExpression(List tokens, NubType type) : TypedNode(tokens) +{ + public NubType Type { get; } = type; +} + +public class TypedNodeExpressionIntLiteral(List tokens, NubType type, TokenIntLiteral value) : TypedNodeExpression(tokens, type) +{ + public TokenIntLiteral Value { get; } = value; +} + +public class TypedNodeExpressionStringLiteral(List tokens, NubType type, TokenStringLiteral value) : TypedNodeExpression(tokens, type) +{ + public TokenStringLiteral Value { get; } = value; +} + +public class TypedNodeExpressionBoolLiteral(List tokens, NubType type, TokenBoolLiteral value) : TypedNodeExpression(tokens, type) +{ + public TokenBoolLiteral Value { get; } = value; +} + +public class TypedNodeExpressionStructLiteral(List tokens, NubType type, List initializers) : TypedNodeExpression(tokens, type) +{ + public List Initializers { get; } = initializers; + + public class Initializer(List tokens, TokenIdent name, TypedNodeExpression value) : Node(tokens) + { + public TokenIdent Name { get; } = name; + public TypedNodeExpression Value { get; } = value; + } +} + +public class TypedNodeExpressionEnumLiteral(List tokens, NubType type, TypedNodeExpression? value) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression? Value { get; } = value; +} + +public class TypedNodeExpressionStringConstructor(List tokens, NubType type, TypedNodeExpression value) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Value { get; } = value; +} + +public class TypedNodeExpressionArrayLiteral(List tokens, NubType type, List values) : TypedNodeExpression(tokens, type) +{ + public List Values { get; } = values; +} + +public class TypedNodeExpressionStructMemberAccess(List tokens, NubType type, TypedNodeExpression target, TokenIdent name) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; + public TokenIdent Name { get; } = name; +} + +public class TypedNodeExpressionStringLength(List tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; +} + +public class TypedNodeExpressionStringPointer(List tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; +} + +public class TypedNodeExpressionArrayCount(List tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; +} + +public class TypedNodeExpressionArrayPointer(List tokens, NubType type, TypedNodeExpression target) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; +} + +public class TypedNodeExpressionFuncCall(List tokens, NubType type, TypedNodeExpression target, List parameters) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; + public List Parameters { get; } = parameters; +} + +public class TypedNodeExpressionLocalIdent(List tokens, NubType type, string value) : TypedNodeExpression(tokens, type) +{ + public string Name { get; } = value; +} + +public class TypedNodeExpressionGlobalIdent(List tokens, NubType type, string module, string value) : TypedNodeExpression(tokens, type) +{ + public string Module { get; } = module; + public string Name { get; } = value; +} + +public class TypedNodeExpressionBinary(List tokens, NubType type, TypedNodeExpression left, TypedNodeExpressionBinary.Op operation, TypedNodeExpression right) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Left { get; } = left; + public Op Operation { get; } = operation; + public TypedNodeExpression Right { get; } = right; + + public enum Op + { + Add, + Subtract, + Multiply, + Divide, + Modulo, + + Equal, + NotEqual, + LessThan, + LessThanOrEqual, + GreaterThan, + GreaterThanOrEqual, + + LeftShift, + RightShift, + + // BitwiseAnd, + // BitwiseXor, + // BitwiseOr, + + LogicalAnd, + LogicalOr, + } +} + +public class TypedNodeExpressionUnary(List tokens, NubType type, TypedNodeExpression target, TypedNodeExpressionUnary.Op op) : TypedNodeExpression(tokens, type) +{ + public TypedNodeExpression Target { get; } = target; + public Op Operation { get; } = op; + + public enum Op + { + Negate, + Invert, + } +} diff --git a/examples/.gitignore b/examples/.gitignore index a8b1f05..24e5b0a 100644 --- a/examples/.gitignore +++ b/examples/.gitignore @@ -1,3 +1 @@ .build -out.a -out \ No newline at end of file diff --git a/examples/build b/examples/build new file mode 100755 index 0000000..c855df2 --- /dev/null +++ b/examples/build @@ -0,0 +1,21 @@ +#!/bin/bash + +set -e + +SCRIPT_DIR=$(dirname "$0") + +pushd $SCRIPT_DIR + pushd ../compiler + dotnet build -c Release + popd + + pushd core + time ../../compiler/bin/Release/net9.0/Compiler sys.nub print.nub --type=lib + popd + + pushd program + time ../../compiler/bin/Release/net9.0/Compiler main.nub ../core/.build/out.nublib + popd + + ./program/.build/out +popd diff --git a/examples/core/print.nub b/examples/core/print.nub new file mode 100644 index 0000000..a5716fc --- /dev/null +++ b/examples/core/print.nub @@ -0,0 +1,10 @@ +module core + +export func print(text: string) { + sys::write(0, text.ptr, text.length) +} + +export func println(text: string) { + print(text) + print("\n") +} \ No newline at end of file diff --git a/examples/core/sys.nub b/examples/core/sys.nub new file mode 100644 index 0000000..1de4ac4 --- /dev/null +++ b/examples/core/sys.nub @@ -0,0 +1,5 @@ +module sys + +export extern func read(fd: u32, buf: ^char, count: u64): i64 +export extern func write(fd: u32, buf: ^char, count: u64): i64 +export extern func open(fileName: ^char, flags: i32, mode: u16): i64 diff --git a/examples/hello-world/build.sh b/examples/hello-world/build.sh deleted file mode 100755 index 95b00b2..0000000 --- a/examples/hello-world/build.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -obj=$(nubc main.nub) -clang $obj -o .build/out \ No newline at end of file diff --git a/examples/hello-world/main.nub b/examples/hello-world/main.nub deleted file mode 100644 index f1d52f8..0000000 --- a/examples/hello-world/main.nub +++ /dev/null @@ -1,9 +0,0 @@ -module "main" - -extern "puts" func puts(text: ^i8) - -extern "main" func main(argc: i64, argv: [?]^i8): i64 -{ - puts("Hello, World!") - return 0 -} \ No newline at end of file diff --git a/examples/program/main.nub b/examples/program/main.nub new file mode 100644 index 0000000..5f58211 --- /dev/null +++ b/examples/program/main.nub @@ -0,0 +1,32 @@ +module main + +struct Human { + name: string + age: i32 +} + +enum Message { + Quit + Say: string +} + +func main(): i32 { + + let x = new string("test".ptr) + " " + "uwu" + core::println(x) + + let messages: []Message = [new Message::Say("first"), new Message::Quit] + + for message in messages { + match message { + Say msg { + core::println(msg) + } + Quit { + core::println("quit") + } + } + } + + return 0 +} diff --git a/examples/raylib/build.sh b/examples/raylib/build.sh deleted file mode 100755 index e94f583..0000000 --- a/examples/raylib/build.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/bash - -set -euo pipefail - -obj=$(nubc main.nub generated/raylib.nub) -clang $obj raylib-5.5_linux_amd64/lib/libraylib.a -lm -o .build/out \ No newline at end of file diff --git a/examples/raylib/generated/raylib.nub b/examples/raylib/generated/raylib.nub deleted file mode 100644 index 1f90db0..0000000 --- a/examples/raylib/generated/raylib.nub +++ /dev/null @@ -1,1578 +0,0 @@ -module "raylib" - -export struct Vector2 -{ - x: f32 - y: f32 -} -export struct Vector3 -{ - x: f32 - y: f32 - z: f32 -} -export struct Vector4 -{ - x: f32 - y: f32 - z: f32 - w: f32 -} -export struct Matrix -{ - m0: f32 - m4: f32 - m8: f32 - m12: f32 - m1: f32 - m5: f32 - m9: f32 - m13: f32 - m2: f32 - m6: f32 - m10: f32 - m14: f32 - m3: f32 - m7: f32 - m11: f32 - m15: f32 -} -export struct Color -{ - r: u8 - g: u8 - b: u8 - a: u8 -} -export struct Rectangle -{ - x: f32 - y: f32 - width: f32 - height: f32 -} -export struct Image -{ - data: ^void - width: i32 - height: i32 - mipmaps: i32 - format: i32 -} -export struct Texture -{ - id: u32 - width: i32 - height: i32 - mipmaps: i32 - format: i32 -} -export struct RenderTexture -{ - id: u32 - texture: Texture - depth: Texture -} -export struct NPatchInfo -{ - source: Rectangle - left: i32 - top: i32 - right: i32 - bottom: i32 - layout: i32 -} -export struct GlyphInfo -{ - value: i32 - offsetX: i32 - offsetY: i32 - advanceX: i32 - image: Image -} -export struct Font -{ - baseSize: i32 - glyphCount: i32 - glyphPadding: i32 - texture: Texture - recs: ^Rectangle - glyphs: ^GlyphInfo -} -export struct Camera3D -{ - position: Vector3 - target: Vector3 - up: Vector3 - fovy: f32 - projection: i32 -} -export struct Camera2D -{ - offset: Vector2 - target: Vector2 - rotation: f32 - zoom: f32 -} -export struct Mesh -{ - vertexCount: i32 - triangleCount: i32 - vertices: ^f32 - texcoords: ^f32 - texcoords2: ^f32 - normals: ^f32 - tangents: ^f32 - colors: ^u8 - indices: ^u16 - animVertices: ^f32 - animNormals: ^f32 - boneIds: ^u8 - boneWeights: ^f32 - boneMatrices: ^Matrix - boneCount: i32 - vaoId: u32 - vboId: ^u32 -} -export struct Shader -{ - id: u32 - locs: ^i32 -} -export struct MaterialMap -{ - texture: Texture - color: Color - value: f32 -} -export struct Material -{ - shader: Shader - maps: ^MaterialMap - params: [4]f32 -} -export struct Transform -{ - translation: Vector3 - rotation: Vector4 - scale: Vector3 -} -export struct BoneInfo -{ - name: [32]i8 - parent: i32 -} -export struct Model -{ - transform: Matrix - meshCount: i32 - materialCount: i32 - meshes: ^Mesh - materials: ^Material - meshMaterial: ^i32 - boneCount: i32 - bones: ^BoneInfo - bindPose: ^Transform -} -export struct ModelAnimation -{ - boneCount: i32 - frameCount: i32 - bones: ^BoneInfo - framePoses: ^^Transform - name: [32]i8 -} -export struct Ray -{ - position: Vector3 - direction: Vector3 -} -export struct RayCollision -{ - hit: bool - distance: f32 - point: Vector3 - normal: Vector3 -} -export struct BoundingBox -{ - min: Vector3 - max: Vector3 -} -export struct Wave -{ - frameCount: u32 - sampleRate: u32 - sampleSize: u32 - channels: u32 - data: ^void -} -export struct AudioStream -{ - buffer: ^void - processor: ^void - sampleRate: u32 - sampleSize: u32 - channels: u32 -} -export struct Sound -{ - stream: AudioStream - frameCount: u32 -} -export struct Music -{ - stream: AudioStream - frameCount: u32 - looping: bool - ctxType: i32 - ctxData: ^void -} -export struct VrDeviceInfo -{ - hResolution: i32 - vResolution: i32 - hScreenSize: f32 - vScreenSize: f32 - eyeToScreenDistance: f32 - lensSeparationDistance: f32 - interpupillaryDistance: f32 - lensDistortionValues: [4]f32 - chromaAbCorrection: [4]f32 -} -export struct VrStereoConfig -{ - projection: [2]Matrix - viewOffset: [2]Matrix - leftLensCenter: [2]f32 - rightLensCenter: [2]f32 - leftScreenCenter: [2]f32 - rightScreenCenter: [2]f32 - scale: [2]f32 - scaleIn: [2]f32 -} -export struct FilePathList -{ - capacity: u32 - count: u32 - paths: ^^i8 -} -export struct AutomationEvent -{ - frame: u32 - type: u32 - params: [4]i32 -} -export struct AutomationEventList -{ - capacity: u32 - count: u32 - events: ^AutomationEvent -} -export enum ConfigFlags : u32 -{ - FLAG_VSYNC_HINT = 64 - FLAG_FULLSCREEN_MODE = 2 - FLAG_WINDOW_RESIZABLE = 4 - FLAG_WINDOW_UNDECORATED = 8 - FLAG_WINDOW_HIDDEN = 128 - FLAG_WINDOW_MINIMIZED = 512 - FLAG_WINDOW_MAXIMIZED = 1024 - FLAG_WINDOW_UNFOCUSED = 2048 - FLAG_WINDOW_TOPMOST = 4096 - FLAG_WINDOW_ALWAYS_RUN = 256 - FLAG_WINDOW_TRANSPARENT = 16 - FLAG_WINDOW_HIGHDPI = 8192 - FLAG_WINDOW_MOUSE_PASSTHROUGH = 16384 - FLAG_BORDERLESS_WINDOWED_MODE = 32768 - FLAG_MSAA_4X_HINT = 32 - FLAG_INTERLACED_HINT = 65536 -} -export enum ConfigFlags : u32 -{ - FLAG_VSYNC_HINT = 64 - FLAG_FULLSCREEN_MODE = 2 - FLAG_WINDOW_RESIZABLE = 4 - FLAG_WINDOW_UNDECORATED = 8 - FLAG_WINDOW_HIDDEN = 128 - FLAG_WINDOW_MINIMIZED = 512 - FLAG_WINDOW_MAXIMIZED = 1024 - FLAG_WINDOW_UNFOCUSED = 2048 - FLAG_WINDOW_TOPMOST = 4096 - FLAG_WINDOW_ALWAYS_RUN = 256 - FLAG_WINDOW_TRANSPARENT = 16 - FLAG_WINDOW_HIGHDPI = 8192 - FLAG_WINDOW_MOUSE_PASSTHROUGH = 16384 - FLAG_BORDERLESS_WINDOWED_MODE = 32768 - FLAG_MSAA_4X_HINT = 32 - FLAG_INTERLACED_HINT = 65536 -} -export enum TraceLogLevel : u32 -{ - LOG_ALL = 0 - LOG_TRACE = 1 - LOG_DEBUG = 2 - LOG_INFO = 3 - LOG_WARNING = 4 - LOG_ERROR = 5 - LOG_FATAL = 6 - LOG_NONE = 7 -} -export enum TraceLogLevel : u32 -{ - LOG_ALL = 0 - LOG_TRACE = 1 - LOG_DEBUG = 2 - LOG_INFO = 3 - LOG_WARNING = 4 - LOG_ERROR = 5 - LOG_FATAL = 6 - LOG_NONE = 7 -} -export enum KeyboardKey : u32 -{ - KEY_NULL = 0 - KEY_APOSTROPHE = 39 - KEY_COMMA = 44 - KEY_MINUS = 45 - KEY_PERIOD = 46 - KEY_SLASH = 47 - KEY_ZERO = 48 - KEY_ONE = 49 - KEY_TWO = 50 - KEY_THREE = 51 - KEY_FOUR = 52 - KEY_FIVE = 53 - KEY_SIX = 54 - KEY_SEVEN = 55 - KEY_EIGHT = 56 - KEY_NINE = 57 - KEY_SEMICOLON = 59 - KEY_EQUAL = 61 - KEY_A = 65 - KEY_B = 66 - KEY_C = 67 - KEY_D = 68 - KEY_E = 69 - KEY_F = 70 - KEY_G = 71 - KEY_H = 72 - KEY_I = 73 - KEY_J = 74 - KEY_K = 75 - KEY_L = 76 - KEY_M = 77 - KEY_N = 78 - KEY_O = 79 - KEY_P = 80 - KEY_Q = 81 - KEY_R = 82 - KEY_S = 83 - KEY_T = 84 - KEY_U = 85 - KEY_V = 86 - KEY_W = 87 - KEY_X = 88 - KEY_Y = 89 - KEY_Z = 90 - KEY_LEFT_BRACKET = 91 - KEY_BACKSLASH = 92 - KEY_RIGHT_BRACKET = 93 - KEY_GRAVE = 96 - KEY_SPACE = 32 - KEY_ESCAPE = 256 - KEY_ENTER = 257 - KEY_TAB = 258 - KEY_BACKSPACE = 259 - KEY_INSERT = 260 - KEY_DELETE = 261 - KEY_RIGHT = 262 - KEY_LEFT = 263 - KEY_DOWN = 264 - KEY_UP = 265 - KEY_PAGE_UP = 266 - KEY_PAGE_DOWN = 267 - KEY_HOME = 268 - KEY_END = 269 - KEY_CAPS_LOCK = 280 - KEY_SCROLL_LOCK = 281 - KEY_NUM_LOCK = 282 - KEY_PRINT_SCREEN = 283 - KEY_PAUSE = 284 - KEY_F1 = 290 - KEY_F2 = 291 - KEY_F3 = 292 - KEY_F4 = 293 - KEY_F5 = 294 - KEY_F6 = 295 - KEY_F7 = 296 - KEY_F8 = 297 - KEY_F9 = 298 - KEY_F10 = 299 - KEY_F11 = 300 - KEY_F12 = 301 - KEY_LEFT_SHIFT = 340 - KEY_LEFT_CONTROL = 341 - KEY_LEFT_ALT = 342 - KEY_LEFT_SUPER = 343 - KEY_RIGHT_SHIFT = 344 - KEY_RIGHT_CONTROL = 345 - KEY_RIGHT_ALT = 346 - KEY_RIGHT_SUPER = 347 - KEY_KB_MENU = 348 - KEY_KP_0 = 320 - KEY_KP_1 = 321 - KEY_KP_2 = 322 - KEY_KP_3 = 323 - KEY_KP_4 = 324 - KEY_KP_5 = 325 - KEY_KP_6 = 326 - KEY_KP_7 = 327 - KEY_KP_8 = 328 - KEY_KP_9 = 329 - KEY_KP_DECIMAL = 330 - KEY_KP_DIVIDE = 331 - KEY_KP_MULTIPLY = 332 - KEY_KP_SUBTRACT = 333 - KEY_KP_ADD = 334 - KEY_KP_ENTER = 335 - KEY_KP_EQUAL = 336 - KEY_BACK = 4 - KEY_MENU = 5 - KEY_VOLUME_UP = 24 - KEY_VOLUME_DOWN = 25 -} -export enum KeyboardKey : u32 -{ - KEY_NULL = 0 - KEY_APOSTROPHE = 39 - KEY_COMMA = 44 - KEY_MINUS = 45 - KEY_PERIOD = 46 - KEY_SLASH = 47 - KEY_ZERO = 48 - KEY_ONE = 49 - KEY_TWO = 50 - KEY_THREE = 51 - KEY_FOUR = 52 - KEY_FIVE = 53 - KEY_SIX = 54 - KEY_SEVEN = 55 - KEY_EIGHT = 56 - KEY_NINE = 57 - KEY_SEMICOLON = 59 - KEY_EQUAL = 61 - KEY_A = 65 - KEY_B = 66 - KEY_C = 67 - KEY_D = 68 - KEY_E = 69 - KEY_F = 70 - KEY_G = 71 - KEY_H = 72 - KEY_I = 73 - KEY_J = 74 - KEY_K = 75 - KEY_L = 76 - KEY_M = 77 - KEY_N = 78 - KEY_O = 79 - KEY_P = 80 - KEY_Q = 81 - KEY_R = 82 - KEY_S = 83 - KEY_T = 84 - KEY_U = 85 - KEY_V = 86 - KEY_W = 87 - KEY_X = 88 - KEY_Y = 89 - KEY_Z = 90 - KEY_LEFT_BRACKET = 91 - KEY_BACKSLASH = 92 - KEY_RIGHT_BRACKET = 93 - KEY_GRAVE = 96 - KEY_SPACE = 32 - KEY_ESCAPE = 256 - KEY_ENTER = 257 - KEY_TAB = 258 - KEY_BACKSPACE = 259 - KEY_INSERT = 260 - KEY_DELETE = 261 - KEY_RIGHT = 262 - KEY_LEFT = 263 - KEY_DOWN = 264 - KEY_UP = 265 - KEY_PAGE_UP = 266 - KEY_PAGE_DOWN = 267 - KEY_HOME = 268 - KEY_END = 269 - KEY_CAPS_LOCK = 280 - KEY_SCROLL_LOCK = 281 - KEY_NUM_LOCK = 282 - KEY_PRINT_SCREEN = 283 - KEY_PAUSE = 284 - KEY_F1 = 290 - KEY_F2 = 291 - KEY_F3 = 292 - KEY_F4 = 293 - KEY_F5 = 294 - KEY_F6 = 295 - KEY_F7 = 296 - KEY_F8 = 297 - KEY_F9 = 298 - KEY_F10 = 299 - KEY_F11 = 300 - KEY_F12 = 301 - KEY_LEFT_SHIFT = 340 - KEY_LEFT_CONTROL = 341 - KEY_LEFT_ALT = 342 - KEY_LEFT_SUPER = 343 - KEY_RIGHT_SHIFT = 344 - KEY_RIGHT_CONTROL = 345 - KEY_RIGHT_ALT = 346 - KEY_RIGHT_SUPER = 347 - KEY_KB_MENU = 348 - KEY_KP_0 = 320 - KEY_KP_1 = 321 - KEY_KP_2 = 322 - KEY_KP_3 = 323 - KEY_KP_4 = 324 - KEY_KP_5 = 325 - KEY_KP_6 = 326 - KEY_KP_7 = 327 - KEY_KP_8 = 328 - KEY_KP_9 = 329 - KEY_KP_DECIMAL = 330 - KEY_KP_DIVIDE = 331 - KEY_KP_MULTIPLY = 332 - KEY_KP_SUBTRACT = 333 - KEY_KP_ADD = 334 - KEY_KP_ENTER = 335 - KEY_KP_EQUAL = 336 - KEY_BACK = 4 - KEY_MENU = 5 - KEY_VOLUME_UP = 24 - KEY_VOLUME_DOWN = 25 -} -export enum MouseButton : u32 -{ - MOUSE_BUTTON_LEFT = 0 - MOUSE_BUTTON_RIGHT = 1 - MOUSE_BUTTON_MIDDLE = 2 - MOUSE_BUTTON_SIDE = 3 - MOUSE_BUTTON_EXTRA = 4 - MOUSE_BUTTON_FORWARD = 5 - MOUSE_BUTTON_BACK = 6 -} -export enum MouseButton : u32 -{ - MOUSE_BUTTON_LEFT = 0 - MOUSE_BUTTON_RIGHT = 1 - MOUSE_BUTTON_MIDDLE = 2 - MOUSE_BUTTON_SIDE = 3 - MOUSE_BUTTON_EXTRA = 4 - MOUSE_BUTTON_FORWARD = 5 - MOUSE_BUTTON_BACK = 6 -} -export enum MouseCursor : u32 -{ - MOUSE_CURSOR_DEFAULT = 0 - MOUSE_CURSOR_ARROW = 1 - MOUSE_CURSOR_IBEAM = 2 - MOUSE_CURSOR_CROSSHAIR = 3 - MOUSE_CURSOR_POINTING_HAND = 4 - MOUSE_CURSOR_RESIZE_EW = 5 - MOUSE_CURSOR_RESIZE_NS = 6 - MOUSE_CURSOR_RESIZE_NWSE = 7 - MOUSE_CURSOR_RESIZE_NESW = 8 - MOUSE_CURSOR_RESIZE_ALL = 9 - MOUSE_CURSOR_NOT_ALLOWED = 10 -} -export enum MouseCursor : u32 -{ - MOUSE_CURSOR_DEFAULT = 0 - MOUSE_CURSOR_ARROW = 1 - MOUSE_CURSOR_IBEAM = 2 - MOUSE_CURSOR_CROSSHAIR = 3 - MOUSE_CURSOR_POINTING_HAND = 4 - MOUSE_CURSOR_RESIZE_EW = 5 - MOUSE_CURSOR_RESIZE_NS = 6 - MOUSE_CURSOR_RESIZE_NWSE = 7 - MOUSE_CURSOR_RESIZE_NESW = 8 - MOUSE_CURSOR_RESIZE_ALL = 9 - MOUSE_CURSOR_NOT_ALLOWED = 10 -} -export enum GamepadButton : u32 -{ - GAMEPAD_BUTTON_UNKNOWN = 0 - GAMEPAD_BUTTON_LEFT_FACE_UP = 1 - GAMEPAD_BUTTON_LEFT_FACE_RIGHT = 2 - GAMEPAD_BUTTON_LEFT_FACE_DOWN = 3 - GAMEPAD_BUTTON_LEFT_FACE_LEFT = 4 - GAMEPAD_BUTTON_RIGHT_FACE_UP = 5 - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT = 6 - GAMEPAD_BUTTON_RIGHT_FACE_DOWN = 7 - GAMEPAD_BUTTON_RIGHT_FACE_LEFT = 8 - GAMEPAD_BUTTON_LEFT_TRIGGER_1 = 9 - GAMEPAD_BUTTON_LEFT_TRIGGER_2 = 10 - GAMEPAD_BUTTON_RIGHT_TRIGGER_1 = 11 - GAMEPAD_BUTTON_RIGHT_TRIGGER_2 = 12 - GAMEPAD_BUTTON_MIDDLE_LEFT = 13 - GAMEPAD_BUTTON_MIDDLE = 14 - GAMEPAD_BUTTON_MIDDLE_RIGHT = 15 - GAMEPAD_BUTTON_LEFT_THUMB = 16 - GAMEPAD_BUTTON_RIGHT_THUMB = 17 -} -export enum GamepadButton : u32 -{ - GAMEPAD_BUTTON_UNKNOWN = 0 - GAMEPAD_BUTTON_LEFT_FACE_UP = 1 - GAMEPAD_BUTTON_LEFT_FACE_RIGHT = 2 - GAMEPAD_BUTTON_LEFT_FACE_DOWN = 3 - GAMEPAD_BUTTON_LEFT_FACE_LEFT = 4 - GAMEPAD_BUTTON_RIGHT_FACE_UP = 5 - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT = 6 - GAMEPAD_BUTTON_RIGHT_FACE_DOWN = 7 - GAMEPAD_BUTTON_RIGHT_FACE_LEFT = 8 - GAMEPAD_BUTTON_LEFT_TRIGGER_1 = 9 - GAMEPAD_BUTTON_LEFT_TRIGGER_2 = 10 - GAMEPAD_BUTTON_RIGHT_TRIGGER_1 = 11 - GAMEPAD_BUTTON_RIGHT_TRIGGER_2 = 12 - GAMEPAD_BUTTON_MIDDLE_LEFT = 13 - GAMEPAD_BUTTON_MIDDLE = 14 - GAMEPAD_BUTTON_MIDDLE_RIGHT = 15 - GAMEPAD_BUTTON_LEFT_THUMB = 16 - GAMEPAD_BUTTON_RIGHT_THUMB = 17 -} -export enum GamepadAxis : u32 -{ - GAMEPAD_AXIS_LEFT_X = 0 - GAMEPAD_AXIS_LEFT_Y = 1 - GAMEPAD_AXIS_RIGHT_X = 2 - GAMEPAD_AXIS_RIGHT_Y = 3 - GAMEPAD_AXIS_LEFT_TRIGGER = 4 - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 -} -export enum GamepadAxis : u32 -{ - GAMEPAD_AXIS_LEFT_X = 0 - GAMEPAD_AXIS_LEFT_Y = 1 - GAMEPAD_AXIS_RIGHT_X = 2 - GAMEPAD_AXIS_RIGHT_Y = 3 - GAMEPAD_AXIS_LEFT_TRIGGER = 4 - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 -} -export enum MaterialMapIndex : u32 -{ - MATERIAL_MAP_ALBEDO = 0 - MATERIAL_MAP_METALNESS = 1 - MATERIAL_MAP_NORMAL = 2 - MATERIAL_MAP_ROUGHNESS = 3 - MATERIAL_MAP_OCCLUSION = 4 - MATERIAL_MAP_EMISSION = 5 - MATERIAL_MAP_HEIGHT = 6 - MATERIAL_MAP_CUBEMAP = 7 - MATERIAL_MAP_IRRADIANCE = 8 - MATERIAL_MAP_PREFILTER = 9 - MATERIAL_MAP_BRDF = 10 -} -export enum MaterialMapIndex : u32 -{ - MATERIAL_MAP_ALBEDO = 0 - MATERIAL_MAP_METALNESS = 1 - MATERIAL_MAP_NORMAL = 2 - MATERIAL_MAP_ROUGHNESS = 3 - MATERIAL_MAP_OCCLUSION = 4 - MATERIAL_MAP_EMISSION = 5 - MATERIAL_MAP_HEIGHT = 6 - MATERIAL_MAP_CUBEMAP = 7 - MATERIAL_MAP_IRRADIANCE = 8 - MATERIAL_MAP_PREFILTER = 9 - MATERIAL_MAP_BRDF = 10 -} -export enum ShaderLocationIndex : u32 -{ - SHADER_LOC_VERTEX_POSITION = 0 - SHADER_LOC_VERTEX_TEXCOORD01 = 1 - SHADER_LOC_VERTEX_TEXCOORD02 = 2 - SHADER_LOC_VERTEX_NORMAL = 3 - SHADER_LOC_VERTEX_TANGENT = 4 - SHADER_LOC_VERTEX_COLOR = 5 - SHADER_LOC_MATRIX_MVP = 6 - SHADER_LOC_MATRIX_VIEW = 7 - SHADER_LOC_MATRIX_PROJECTION = 8 - SHADER_LOC_MATRIX_MODEL = 9 - SHADER_LOC_MATRIX_NORMAL = 10 - SHADER_LOC_VECTOR_VIEW = 11 - SHADER_LOC_COLOR_DIFFUSE = 12 - SHADER_LOC_COLOR_SPECULAR = 13 - SHADER_LOC_COLOR_AMBIENT = 14 - SHADER_LOC_MAP_ALBEDO = 15 - SHADER_LOC_MAP_METALNESS = 16 - SHADER_LOC_MAP_NORMAL = 17 - SHADER_LOC_MAP_ROUGHNESS = 18 - SHADER_LOC_MAP_OCCLUSION = 19 - SHADER_LOC_MAP_EMISSION = 20 - SHADER_LOC_MAP_HEIGHT = 21 - SHADER_LOC_MAP_CUBEMAP = 22 - SHADER_LOC_MAP_IRRADIANCE = 23 - SHADER_LOC_MAP_PREFILTER = 24 - SHADER_LOC_MAP_BRDF = 25 - SHADER_LOC_VERTEX_BONEIDS = 26 - SHADER_LOC_VERTEX_BONEWEIGHTS = 27 - SHADER_LOC_BONE_MATRICES = 28 -} -export enum ShaderLocationIndex : u32 -{ - SHADER_LOC_VERTEX_POSITION = 0 - SHADER_LOC_VERTEX_TEXCOORD01 = 1 - SHADER_LOC_VERTEX_TEXCOORD02 = 2 - SHADER_LOC_VERTEX_NORMAL = 3 - SHADER_LOC_VERTEX_TANGENT = 4 - SHADER_LOC_VERTEX_COLOR = 5 - SHADER_LOC_MATRIX_MVP = 6 - SHADER_LOC_MATRIX_VIEW = 7 - SHADER_LOC_MATRIX_PROJECTION = 8 - SHADER_LOC_MATRIX_MODEL = 9 - SHADER_LOC_MATRIX_NORMAL = 10 - SHADER_LOC_VECTOR_VIEW = 11 - SHADER_LOC_COLOR_DIFFUSE = 12 - SHADER_LOC_COLOR_SPECULAR = 13 - SHADER_LOC_COLOR_AMBIENT = 14 - SHADER_LOC_MAP_ALBEDO = 15 - SHADER_LOC_MAP_METALNESS = 16 - SHADER_LOC_MAP_NORMAL = 17 - SHADER_LOC_MAP_ROUGHNESS = 18 - SHADER_LOC_MAP_OCCLUSION = 19 - SHADER_LOC_MAP_EMISSION = 20 - SHADER_LOC_MAP_HEIGHT = 21 - SHADER_LOC_MAP_CUBEMAP = 22 - SHADER_LOC_MAP_IRRADIANCE = 23 - SHADER_LOC_MAP_PREFILTER = 24 - SHADER_LOC_MAP_BRDF = 25 - SHADER_LOC_VERTEX_BONEIDS = 26 - SHADER_LOC_VERTEX_BONEWEIGHTS = 27 - SHADER_LOC_BONE_MATRICES = 28 -} -export enum ShaderUniformDataType : u32 -{ - SHADER_UNIFORM_FLOAT = 0 - SHADER_UNIFORM_VEC2 = 1 - SHADER_UNIFORM_VEC3 = 2 - SHADER_UNIFORM_VEC4 = 3 - SHADER_UNIFORM_INT = 4 - SHADER_UNIFORM_IVEC2 = 5 - SHADER_UNIFORM_IVEC3 = 6 - SHADER_UNIFORM_IVEC4 = 7 - SHADER_UNIFORM_SAMPLER2D = 8 -} -export enum ShaderUniformDataType : u32 -{ - SHADER_UNIFORM_FLOAT = 0 - SHADER_UNIFORM_VEC2 = 1 - SHADER_UNIFORM_VEC3 = 2 - SHADER_UNIFORM_VEC4 = 3 - SHADER_UNIFORM_INT = 4 - SHADER_UNIFORM_IVEC2 = 5 - SHADER_UNIFORM_IVEC3 = 6 - SHADER_UNIFORM_IVEC4 = 7 - SHADER_UNIFORM_SAMPLER2D = 8 -} -export enum ShaderAttributeDataType : u32 -{ - SHADER_ATTRIB_FLOAT = 0 - SHADER_ATTRIB_VEC2 = 1 - SHADER_ATTRIB_VEC3 = 2 - SHADER_ATTRIB_VEC4 = 3 -} -export enum ShaderAttributeDataType : u32 -{ - SHADER_ATTRIB_FLOAT = 0 - SHADER_ATTRIB_VEC2 = 1 - SHADER_ATTRIB_VEC3 = 2 - SHADER_ATTRIB_VEC4 = 3 -} -export enum PixelFormat : u32 -{ - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1 - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA = 2 - PIXELFORMAT_UNCOMPRESSED_R5G6B5 = 3 - PIXELFORMAT_UNCOMPRESSED_R8G8B8 = 4 - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1 = 5 - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4 = 6 - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 = 7 - PIXELFORMAT_UNCOMPRESSED_R32 = 8 - PIXELFORMAT_UNCOMPRESSED_R32G32B32 = 9 - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32 = 10 - PIXELFORMAT_UNCOMPRESSED_R16 = 11 - PIXELFORMAT_UNCOMPRESSED_R16G16B16 = 12 - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16 = 13 - PIXELFORMAT_COMPRESSED_DXT1_RGB = 14 - PIXELFORMAT_COMPRESSED_DXT1_RGBA = 15 - PIXELFORMAT_COMPRESSED_DXT3_RGBA = 16 - PIXELFORMAT_COMPRESSED_DXT5_RGBA = 17 - PIXELFORMAT_COMPRESSED_ETC1_RGB = 18 - PIXELFORMAT_COMPRESSED_ETC2_RGB = 19 - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA = 20 - PIXELFORMAT_COMPRESSED_PVRT_RGB = 21 - PIXELFORMAT_COMPRESSED_PVRT_RGBA = 22 - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA = 23 - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA = 24 -} -export enum PixelFormat : u32 -{ - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1 - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA = 2 - PIXELFORMAT_UNCOMPRESSED_R5G6B5 = 3 - PIXELFORMAT_UNCOMPRESSED_R8G8B8 = 4 - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1 = 5 - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4 = 6 - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8 = 7 - PIXELFORMAT_UNCOMPRESSED_R32 = 8 - PIXELFORMAT_UNCOMPRESSED_R32G32B32 = 9 - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32 = 10 - PIXELFORMAT_UNCOMPRESSED_R16 = 11 - PIXELFORMAT_UNCOMPRESSED_R16G16B16 = 12 - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16 = 13 - PIXELFORMAT_COMPRESSED_DXT1_RGB = 14 - PIXELFORMAT_COMPRESSED_DXT1_RGBA = 15 - PIXELFORMAT_COMPRESSED_DXT3_RGBA = 16 - PIXELFORMAT_COMPRESSED_DXT5_RGBA = 17 - PIXELFORMAT_COMPRESSED_ETC1_RGB = 18 - PIXELFORMAT_COMPRESSED_ETC2_RGB = 19 - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA = 20 - PIXELFORMAT_COMPRESSED_PVRT_RGB = 21 - PIXELFORMAT_COMPRESSED_PVRT_RGBA = 22 - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA = 23 - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA = 24 -} -export enum TextureFilter : u32 -{ - TEXTURE_FILTER_POINT = 0 - TEXTURE_FILTER_BILINEAR = 1 - TEXTURE_FILTER_TRILINEAR = 2 - TEXTURE_FILTER_ANISOTROPIC_4X = 3 - TEXTURE_FILTER_ANISOTROPIC_8X = 4 - TEXTURE_FILTER_ANISOTROPIC_16X = 5 -} -export enum TextureFilter : u32 -{ - TEXTURE_FILTER_POINT = 0 - TEXTURE_FILTER_BILINEAR = 1 - TEXTURE_FILTER_TRILINEAR = 2 - TEXTURE_FILTER_ANISOTROPIC_4X = 3 - TEXTURE_FILTER_ANISOTROPIC_8X = 4 - TEXTURE_FILTER_ANISOTROPIC_16X = 5 -} -export enum TextureWrap : u32 -{ - TEXTURE_WRAP_REPEAT = 0 - TEXTURE_WRAP_CLAMP = 1 - TEXTURE_WRAP_MIRROR_REPEAT = 2 - TEXTURE_WRAP_MIRROR_CLAMP = 3 -} -export enum TextureWrap : u32 -{ - TEXTURE_WRAP_REPEAT = 0 - TEXTURE_WRAP_CLAMP = 1 - TEXTURE_WRAP_MIRROR_REPEAT = 2 - TEXTURE_WRAP_MIRROR_CLAMP = 3 -} -export enum CubemapLayout : u32 -{ - CUBEMAP_LAYOUT_AUTO_DETECT = 0 - CUBEMAP_LAYOUT_LINE_VERTICAL = 1 - CUBEMAP_LAYOUT_LINE_HORIZONTAL = 2 - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR = 3 - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE = 4 -} -export enum CubemapLayout : u32 -{ - CUBEMAP_LAYOUT_AUTO_DETECT = 0 - CUBEMAP_LAYOUT_LINE_VERTICAL = 1 - CUBEMAP_LAYOUT_LINE_HORIZONTAL = 2 - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR = 3 - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE = 4 -} -export enum FontType : u32 -{ - FONT_DEFAULT = 0 - FONT_BITMAP = 1 - FONT_SDF = 2 -} -export enum FontType : u32 -{ - FONT_DEFAULT = 0 - FONT_BITMAP = 1 - FONT_SDF = 2 -} -export enum BlendMode : u32 -{ - BLEND_ALPHA = 0 - BLEND_ADDITIVE = 1 - BLEND_MULTIPLIED = 2 - BLEND_ADD_COLORS = 3 - BLEND_SUBTRACT_COLORS = 4 - BLEND_ALPHA_PREMULTIPLY = 5 - BLEND_CUSTOM = 6 - BLEND_CUSTOM_SEPARATE = 7 -} -export enum BlendMode : u32 -{ - BLEND_ALPHA = 0 - BLEND_ADDITIVE = 1 - BLEND_MULTIPLIED = 2 - BLEND_ADD_COLORS = 3 - BLEND_SUBTRACT_COLORS = 4 - BLEND_ALPHA_PREMULTIPLY = 5 - BLEND_CUSTOM = 6 - BLEND_CUSTOM_SEPARATE = 7 -} -export enum Gesture : u32 -{ - GESTURE_NONE = 0 - GESTURE_TAP = 1 - GESTURE_DOUBLETAP = 2 - GESTURE_HOLD = 4 - GESTURE_DRAG = 8 - GESTURE_SWIPE_RIGHT = 16 - GESTURE_SWIPE_LEFT = 32 - GESTURE_SWIPE_UP = 64 - GESTURE_SWIPE_DOWN = 128 - GESTURE_PINCH_IN = 256 - GESTURE_PINCH_OUT = 512 -} -export enum Gesture : u32 -{ - GESTURE_NONE = 0 - GESTURE_TAP = 1 - GESTURE_DOUBLETAP = 2 - GESTURE_HOLD = 4 - GESTURE_DRAG = 8 - GESTURE_SWIPE_RIGHT = 16 - GESTURE_SWIPE_LEFT = 32 - GESTURE_SWIPE_UP = 64 - GESTURE_SWIPE_DOWN = 128 - GESTURE_PINCH_IN = 256 - GESTURE_PINCH_OUT = 512 -} -export enum CameraMode : u32 -{ - CAMERA_CUSTOM = 0 - CAMERA_FREE = 1 - CAMERA_ORBITAL = 2 - CAMERA_FIRST_PERSON = 3 - CAMERA_THIRD_PERSON = 4 -} -export enum CameraMode : u32 -{ - CAMERA_CUSTOM = 0 - CAMERA_FREE = 1 - CAMERA_ORBITAL = 2 - CAMERA_FIRST_PERSON = 3 - CAMERA_THIRD_PERSON = 4 -} -export enum CameraProjection : u32 -{ - CAMERA_PERSPECTIVE = 0 - CAMERA_ORTHOGRAPHIC = 1 -} -export enum CameraProjection : u32 -{ - CAMERA_PERSPECTIVE = 0 - CAMERA_ORTHOGRAPHIC = 1 -} -export enum NPatchLayout : u32 -{ - NPATCH_NINE_PATCH = 0 - NPATCH_THREE_PATCH_VERTICAL = 1 - NPATCH_THREE_PATCH_HORIZONTAL = 2 -} -export enum NPatchLayout : u32 -{ - NPATCH_NINE_PATCH = 0 - NPATCH_THREE_PATCH_VERTICAL = 1 - NPATCH_THREE_PATCH_HORIZONTAL = 2 -} -export extern "InitWindow" func InitWindow(width: i32, height: i32, title: ^i8): void -export extern "CloseWindow" func CloseWindow(): void -export extern "WindowShouldClose" func WindowShouldClose(): bool -export extern "IsWindowReady" func IsWindowReady(): bool -export extern "IsWindowFullscreen" func IsWindowFullscreen(): bool -export extern "IsWindowHidden" func IsWindowHidden(): bool -export extern "IsWindowMinimized" func IsWindowMinimized(): bool -export extern "IsWindowMaximized" func IsWindowMaximized(): bool -export extern "IsWindowFocused" func IsWindowFocused(): bool -export extern "IsWindowResized" func IsWindowResized(): bool -export extern "IsWindowState" func IsWindowState(flag: u32): bool -export extern "SetWindowState" func SetWindowState(flags: u32): void -export extern "ClearWindowState" func ClearWindowState(flags: u32): void -export extern "ToggleFullscreen" func ToggleFullscreen(): void -export extern "ToggleBorderlessWindowed" func ToggleBorderlessWindowed(): void -export extern "MaximizeWindow" func MaximizeWindow(): void -export extern "MinimizeWindow" func MinimizeWindow(): void -export extern "RestoreWindow" func RestoreWindow(): void -export extern "SetWindowIcon" func SetWindowIcon(image: Image): void -export extern "SetWindowIcons" func SetWindowIcons(images: ^Image, count: i32): void -export extern "SetWindowTitle" func SetWindowTitle(title: ^i8): void -export extern "SetWindowPosition" func SetWindowPosition(x: i32, y: i32): void -export extern "SetWindowMonitor" func SetWindowMonitor(monitor: i32): void -export extern "SetWindowMinSize" func SetWindowMinSize(width: i32, height: i32): void -export extern "SetWindowMaxSize" func SetWindowMaxSize(width: i32, height: i32): void -export extern "SetWindowSize" func SetWindowSize(width: i32, height: i32): void -export extern "SetWindowOpacity" func SetWindowOpacity(opacity: f32): void -export extern "SetWindowFocused" func SetWindowFocused(): void -export extern "GetWindowHandle" func GetWindowHandle(): ^void -export extern "GetScreenWidth" func GetScreenWidth(): i32 -export extern "GetScreenHeight" func GetScreenHeight(): i32 -export extern "GetRenderWidth" func GetRenderWidth(): i32 -export extern "GetRenderHeight" func GetRenderHeight(): i32 -export extern "GetMonitorCount" func GetMonitorCount(): i32 -export extern "GetCurrentMonitor" func GetCurrentMonitor(): i32 -export extern "GetMonitorPosition" func GetMonitorPosition(monitor: i32): Vector2 -export extern "GetMonitorWidth" func GetMonitorWidth(monitor: i32): i32 -export extern "GetMonitorHeight" func GetMonitorHeight(monitor: i32): i32 -export extern "GetMonitorPhysicalWidth" func GetMonitorPhysicalWidth(monitor: i32): i32 -export extern "GetMonitorPhysicalHeight" func GetMonitorPhysicalHeight(monitor: i32): i32 -export extern "GetMonitorRefreshRate" func GetMonitorRefreshRate(monitor: i32): i32 -export extern "GetWindowPosition" func GetWindowPosition(): Vector2 -export extern "GetWindowScaleDPI" func GetWindowScaleDPI(): Vector2 -export extern "GetMonitorName" func GetMonitorName(monitor: i32): ^i8 -export extern "SetClipboardText" func SetClipboardText(text: ^i8): void -export extern "GetClipboardText" func GetClipboardText(): ^i8 -export extern "GetClipboardImage" func GetClipboardImage(): Image -export extern "EnableEventWaiting" func EnableEventWaiting(): void -export extern "DisableEventWaiting" func DisableEventWaiting(): void -export extern "ShowCursor" func ShowCursor(): void -export extern "HideCursor" func HideCursor(): void -export extern "IsCursorHidden" func IsCursorHidden(): bool -export extern "EnableCursor" func EnableCursor(): void -export extern "DisableCursor" func DisableCursor(): void -export extern "IsCursorOnScreen" func IsCursorOnScreen(): bool -export extern "ClearBackground" func ClearBackground(color: Color): void -export extern "BeginDrawing" func BeginDrawing(): void -export extern "EndDrawing" func EndDrawing(): void -export extern "BeginMode2D" func BeginMode2D(camera: Camera2D): void -export extern "EndMode2D" func EndMode2D(): void -export extern "BeginMode3D" func BeginMode3D(camera: Camera3D): void -export extern "EndMode3D" func EndMode3D(): void -export extern "BeginTextureMode" func BeginTextureMode(target: RenderTexture): void -export extern "EndTextureMode" func EndTextureMode(): void -export extern "BeginShaderMode" func BeginShaderMode(shader: Shader): void -export extern "EndShaderMode" func EndShaderMode(): void -export extern "BeginBlendMode" func BeginBlendMode(mode: i32): void -export extern "EndBlendMode" func EndBlendMode(): void -export extern "BeginScissorMode" func BeginScissorMode(x: i32, y: i32, width: i32, height: i32): void -export extern "EndScissorMode" func EndScissorMode(): void -export extern "BeginVrStereoMode" func BeginVrStereoMode(config: VrStereoConfig): void -export extern "EndVrStereoMode" func EndVrStereoMode(): void -export extern "LoadVrStereoConfig" func LoadVrStereoConfig(device: VrDeviceInfo): VrStereoConfig -export extern "UnloadVrStereoConfig" func UnloadVrStereoConfig(config: VrStereoConfig): void -export extern "LoadShader" func LoadShader(vsFileName: ^i8, fsFileName: ^i8): Shader -export extern "LoadShaderFromMemory" func LoadShaderFromMemory(vsCode: ^i8, fsCode: ^i8): Shader -export extern "IsShaderValid" func IsShaderValid(shader: Shader): bool -export extern "GetShaderLocation" func GetShaderLocation(shader: Shader, uniformName: ^i8): i32 -export extern "GetShaderLocationAttrib" func GetShaderLocationAttrib(shader: Shader, attribName: ^i8): i32 -export extern "SetShaderValue" func SetShaderValue(shader: Shader, locIndex: i32, value: ^void, uniformType: i32): void -export extern "SetShaderValueV" func SetShaderValueV(shader: Shader, locIndex: i32, value: ^void, uniformType: i32, count: i32): void -export extern "SetShaderValueMatrix" func SetShaderValueMatrix(shader: Shader, locIndex: i32, mat: Matrix): void -export extern "SetShaderValueTexture" func SetShaderValueTexture(shader: Shader, locIndex: i32, texture: Texture): void -export extern "UnloadShader" func UnloadShader(shader: Shader): void -export extern "GetScreenToWorldRay" func GetScreenToWorldRay(position: Vector2, camera: Camera3D): Ray -export extern "GetScreenToWorldRayEx" func GetScreenToWorldRayEx(position: Vector2, camera: Camera3D, width: i32, height: i32): Ray -export extern "GetWorldToScreen" func GetWorldToScreen(position: Vector3, camera: Camera3D): Vector2 -export extern "GetWorldToScreenEx" func GetWorldToScreenEx(position: Vector3, camera: Camera3D, width: i32, height: i32): Vector2 -export extern "GetWorldToScreen2D" func GetWorldToScreen2D(position: Vector2, camera: Camera2D): Vector2 -export extern "GetScreenToWorld2D" func GetScreenToWorld2D(position: Vector2, camera: Camera2D): Vector2 -export extern "GetCameraMatrix" func GetCameraMatrix(camera: Camera3D): Matrix -export extern "GetCameraMatrix2D" func GetCameraMatrix2D(camera: Camera2D): Matrix -export extern "SetTargetFPS" func SetTargetFPS(fps: i32): void -export extern "GetFrameTime" func GetFrameTime(): f32 -export extern "GetTime" func GetTime(): f64 -export extern "GetFPS" func GetFPS(): i32 -export extern "SwapScreenBuffer" func SwapScreenBuffer(): void -export extern "PollInputEvents" func PollInputEvents(): void -export extern "WaitTime" func WaitTime(seconds: f64): void -export extern "SetRandomSeed" func SetRandomSeed(seed: u32): void -export extern "GetRandomValue" func GetRandomValue(min: i32, max: i32): i32 -export extern "LoadRandomSequence" func LoadRandomSequence(count: u32, min: i32, max: i32): ^i32 -export extern "UnloadRandomSequence" func UnloadRandomSequence(sequence: ^i32): void -export extern "TakeScreenshot" func TakeScreenshot(fileName: ^i8): void -export extern "SetConfigFlags" func SetConfigFlags(flags: u32): void -export extern "OpenURL" func OpenURL(url: ^i8): void -export extern "TraceLog" func TraceLog(logLevel: i32, text: ^i8): void -export extern "SetTraceLogLevel" func SetTraceLogLevel(logLevel: i32): void -export extern "MemAlloc" func MemAlloc(size: u32): ^void -export extern "MemRealloc" func MemRealloc(ptr: ^void, size: u32): ^void -export extern "MemFree" func MemFree(ptr: ^void): void -export extern "SetTraceLogCallback" func SetTraceLogCallback(callback: func(i32, ^i8, i32): void): void -export extern "SetLoadFileDataCallback" func SetLoadFileDataCallback(callback: func(^i8, ^i32): ^u8): void -export extern "SetSaveFileDataCallback" func SetSaveFileDataCallback(callback: func(^i8, ^void, i32): bool): void -export extern "SetLoadFileTextCallback" func SetLoadFileTextCallback(callback: func(^i8): ^i8): void -export extern "SetSaveFileTextCallback" func SetSaveFileTextCallback(callback: func(^i8, ^i8): bool): void -export extern "LoadFileData" func LoadFileData(fileName: ^i8, dataSize: ^i32): ^u8 -export extern "UnloadFileData" func UnloadFileData(data: ^u8): void -export extern "SaveFileData" func SaveFileData(fileName: ^i8, data: ^void, dataSize: i32): bool -export extern "ExportDataAsCode" func ExportDataAsCode(data: ^u8, dataSize: i32, fileName: ^i8): bool -export extern "LoadFileText" func LoadFileText(fileName: ^i8): ^i8 -export extern "UnloadFileText" func UnloadFileText(text: ^i8): void -export extern "SaveFileText" func SaveFileText(fileName: ^i8, text: ^i8): bool -export extern "FileExists" func FileExists(fileName: ^i8): bool -export extern "DirectoryExists" func DirectoryExists(dirPath: ^i8): bool -export extern "IsFileExtension" func IsFileExtension(fileName: ^i8, ext: ^i8): bool -export extern "GetFileLength" func GetFileLength(fileName: ^i8): i32 -export extern "GetFileExtension" func GetFileExtension(fileName: ^i8): ^i8 -export extern "GetFileName" func GetFileName(filePath: ^i8): ^i8 -export extern "GetFileNameWithoutExt" func GetFileNameWithoutExt(filePath: ^i8): ^i8 -export extern "GetDirectoryPath" func GetDirectoryPath(filePath: ^i8): ^i8 -export extern "GetPrevDirectoryPath" func GetPrevDirectoryPath(dirPath: ^i8): ^i8 -export extern "GetWorkingDirectory" func GetWorkingDirectory(): ^i8 -export extern "GetApplicationDirectory" func GetApplicationDirectory(): ^i8 -export extern "MakeDirectory" func MakeDirectory(dirPath: ^i8): i32 -export extern "ChangeDirectory" func ChangeDirectory(dir: ^i8): bool -export extern "IsPathFile" func IsPathFile(path: ^i8): bool -export extern "IsFileNameValid" func IsFileNameValid(fileName: ^i8): bool -export extern "LoadDirectoryFiles" func LoadDirectoryFiles(dirPath: ^i8): FilePathList -export extern "LoadDirectoryFilesEx" func LoadDirectoryFilesEx(basePath: ^i8, filter: ^i8, scanSubdirs: bool): FilePathList -export extern "UnloadDirectoryFiles" func UnloadDirectoryFiles(files: FilePathList): void -export extern "IsFileDropped" func IsFileDropped(): bool -export extern "LoadDroppedFiles" func LoadDroppedFiles(): FilePathList -export extern "UnloadDroppedFiles" func UnloadDroppedFiles(files: FilePathList): void -export extern "GetFileModTime" func GetFileModTime(fileName: ^i8): i64 -export extern "CompressData" func CompressData(data: ^u8, dataSize: i32, compDataSize: ^i32): ^u8 -export extern "DecompressData" func DecompressData(compData: ^u8, compDataSize: i32, dataSize: ^i32): ^u8 -export extern "EncodeDataBase64" func EncodeDataBase64(data: ^u8, dataSize: i32, outputSize: ^i32): ^i8 -export extern "DecodeDataBase64" func DecodeDataBase64(data: ^u8, outputSize: ^i32): ^u8 -export extern "ComputeCRC32" func ComputeCRC32(data: ^u8, dataSize: i32): u32 -export extern "ComputeMD5" func ComputeMD5(data: ^u8, dataSize: i32): ^u32 -export extern "ComputeSHA1" func ComputeSHA1(data: ^u8, dataSize: i32): ^u32 -export extern "LoadAutomationEventList" func LoadAutomationEventList(fileName: ^i8): AutomationEventList -export extern "UnloadAutomationEventList" func UnloadAutomationEventList(list: AutomationEventList): void -export extern "ExportAutomationEventList" func ExportAutomationEventList(list: AutomationEventList, fileName: ^i8): bool -export extern "SetAutomationEventList" func SetAutomationEventList(list: ^AutomationEventList): void -export extern "SetAutomationEventBaseFrame" func SetAutomationEventBaseFrame(frame: i32): void -export extern "StartAutomationEventRecording" func StartAutomationEventRecording(): void -export extern "StopAutomationEventRecording" func StopAutomationEventRecording(): void -export extern "PlayAutomationEvent" func PlayAutomationEvent(event: AutomationEvent): void -export extern "IsKeyPressed" func IsKeyPressed(key: i32): bool -export extern "IsKeyPressedRepeat" func IsKeyPressedRepeat(key: i32): bool -export extern "IsKeyDown" func IsKeyDown(key: i32): bool -export extern "IsKeyReleased" func IsKeyReleased(key: i32): bool -export extern "IsKeyUp" func IsKeyUp(key: i32): bool -export extern "GetKeyPressed" func GetKeyPressed(): i32 -export extern "GetCharPressed" func GetCharPressed(): i32 -export extern "SetExitKey" func SetExitKey(key: i32): void -export extern "IsGamepadAvailable" func IsGamepadAvailable(gamepad: i32): bool -export extern "GetGamepadName" func GetGamepadName(gamepad: i32): ^i8 -export extern "IsGamepadButtonPressed" func IsGamepadButtonPressed(gamepad: i32, button: i32): bool -export extern "IsGamepadButtonDown" func IsGamepadButtonDown(gamepad: i32, button: i32): bool -export extern "IsGamepadButtonReleased" func IsGamepadButtonReleased(gamepad: i32, button: i32): bool -export extern "IsGamepadButtonUp" func IsGamepadButtonUp(gamepad: i32, button: i32): bool -export extern "GetGamepadButtonPressed" func GetGamepadButtonPressed(): i32 -export extern "GetGamepadAxisCount" func GetGamepadAxisCount(gamepad: i32): i32 -export extern "GetGamepadAxisMovement" func GetGamepadAxisMovement(gamepad: i32, axis: i32): f32 -export extern "SetGamepadMappings" func SetGamepadMappings(mappings: ^i8): i32 -export extern "SetGamepadVibration" func SetGamepadVibration(gamepad: i32, leftMotor: f32, rightMotor: f32, duration: f32): void -export extern "IsMouseButtonPressed" func IsMouseButtonPressed(button: i32): bool -export extern "IsMouseButtonDown" func IsMouseButtonDown(button: i32): bool -export extern "IsMouseButtonReleased" func IsMouseButtonReleased(button: i32): bool -export extern "IsMouseButtonUp" func IsMouseButtonUp(button: i32): bool -export extern "GetMouseX" func GetMouseX(): i32 -export extern "GetMouseY" func GetMouseY(): i32 -export extern "GetMousePosition" func GetMousePosition(): Vector2 -export extern "GetMouseDelta" func GetMouseDelta(): Vector2 -export extern "SetMousePosition" func SetMousePosition(x: i32, y: i32): void -export extern "SetMouseOffset" func SetMouseOffset(offsetX: i32, offsetY: i32): void -export extern "SetMouseScale" func SetMouseScale(scaleX: f32, scaleY: f32): void -export extern "GetMouseWheelMove" func GetMouseWheelMove(): f32 -export extern "GetMouseWheelMoveV" func GetMouseWheelMoveV(): Vector2 -export extern "SetMouseCursor" func SetMouseCursor(cursor: i32): void -export extern "GetTouchX" func GetTouchX(): i32 -export extern "GetTouchY" func GetTouchY(): i32 -export extern "GetTouchPosition" func GetTouchPosition(index: i32): Vector2 -export extern "GetTouchPointId" func GetTouchPointId(index: i32): i32 -export extern "GetTouchPointCount" func GetTouchPointCount(): i32 -export extern "SetGesturesEnabled" func SetGesturesEnabled(flags: u32): void -export extern "IsGestureDetected" func IsGestureDetected(gesture: u32): bool -export extern "GetGestureDetected" func GetGestureDetected(): i32 -export extern "GetGestureHoldDuration" func GetGestureHoldDuration(): f32 -export extern "GetGestureDragVector" func GetGestureDragVector(): Vector2 -export extern "GetGestureDragAngle" func GetGestureDragAngle(): f32 -export extern "GetGesturePinchVector" func GetGesturePinchVector(): Vector2 -export extern "GetGesturePinchAngle" func GetGesturePinchAngle(): f32 -export extern "UpdateCamera" func UpdateCamera(camera: ^Camera3D, mode: i32): void -export extern "UpdateCameraPro" func UpdateCameraPro(camera: ^Camera3D, movement: Vector3, rotation: Vector3, zoom: f32): void -export extern "SetShapesTexture" func SetShapesTexture(texture: Texture, source: Rectangle): void -export extern "GetShapesTexture" func GetShapesTexture(): Texture -export extern "GetShapesTextureRectangle" func GetShapesTextureRectangle(): Rectangle -export extern "DrawPixel" func DrawPixel(posX: i32, posY: i32, color: Color): void -export extern "DrawPixelV" func DrawPixelV(position: Vector2, color: Color): void -export extern "DrawLine" func DrawLine(startPosX: i32, startPosY: i32, endPosX: i32, endPosY: i32, color: Color): void -export extern "DrawLineV" func DrawLineV(startPos: Vector2, endPos: Vector2, color: Color): void -export extern "DrawLineEx" func DrawLineEx(startPos: Vector2, endPos: Vector2, thick: f32, color: Color): void -export extern "DrawLineStrip" func DrawLineStrip(points: ^Vector2, pointCount: i32, color: Color): void -export extern "DrawLineBezier" func DrawLineBezier(startPos: Vector2, endPos: Vector2, thick: f32, color: Color): void -export extern "DrawCircle" func DrawCircle(centerX: i32, centerY: i32, radius: f32, color: Color): void -export extern "DrawCircleSector" func DrawCircleSector(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: i32, color: Color): void -export extern "DrawCircleSectorLines" func DrawCircleSectorLines(center: Vector2, radius: f32, startAngle: f32, endAngle: f32, segments: i32, color: Color): void -export extern "DrawCircleGradient" func DrawCircleGradient(centerX: i32, centerY: i32, radius: f32, inner: Color, outer: Color): void -export extern "DrawCircleV" func DrawCircleV(center: Vector2, radius: f32, color: Color): void -export extern "DrawCircleLines" func DrawCircleLines(centerX: i32, centerY: i32, radius: f32, color: Color): void -export extern "DrawCircleLinesV" func DrawCircleLinesV(center: Vector2, radius: f32, color: Color): void -export extern "DrawEllipse" func DrawEllipse(centerX: i32, centerY: i32, radiusH: f32, radiusV: f32, color: Color): void -export extern "DrawEllipseLines" func DrawEllipseLines(centerX: i32, centerY: i32, radiusH: f32, radiusV: f32, color: Color): void -export extern "DrawRing" func DrawRing(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: i32, color: Color): void -export extern "DrawRingLines" func DrawRingLines(center: Vector2, innerRadius: f32, outerRadius: f32, startAngle: f32, endAngle: f32, segments: i32, color: Color): void -export extern "DrawRectangle" func DrawRectangle(posX: i32, posY: i32, width: i32, height: i32, color: Color): void -export extern "DrawRectangleV" func DrawRectangleV(position: Vector2, size: Vector2, color: Color): void -export extern "DrawRectangleRec" func DrawRectangleRec(rec: Rectangle, color: Color): void -export extern "DrawRectanglePro" func DrawRectanglePro(rec: Rectangle, origin: Vector2, rotation: f32, color: Color): void -export extern "DrawRectangleGradientV" func DrawRectangleGradientV(posX: i32, posY: i32, width: i32, height: i32, top: Color, bottom: Color): void -export extern "DrawRectangleGradientH" func DrawRectangleGradientH(posX: i32, posY: i32, width: i32, height: i32, left: Color, right: Color): void -export extern "DrawRectangleGradientEx" func DrawRectangleGradientEx(rec: Rectangle, topLeft: Color, bottomLeft: Color, topRight: Color, bottomRight: Color): void -export extern "DrawRectangleLines" func DrawRectangleLines(posX: i32, posY: i32, width: i32, height: i32, color: Color): void -export extern "DrawRectangleLinesEx" func DrawRectangleLinesEx(rec: Rectangle, lineThick: f32, color: Color): void -export extern "DrawRectangleRounded" func DrawRectangleRounded(rec: Rectangle, roundness: f32, segments: i32, color: Color): void -export extern "DrawRectangleRoundedLines" func DrawRectangleRoundedLines(rec: Rectangle, roundness: f32, segments: i32, color: Color): void -export extern "DrawRectangleRoundedLinesEx" func DrawRectangleRoundedLinesEx(rec: Rectangle, roundness: f32, segments: i32, lineThick: f32, color: Color): void -export extern "DrawTriangle" func DrawTriangle(v1: Vector2, v2: Vector2, v3: Vector2, color: Color): void -export extern "DrawTriangleLines" func DrawTriangleLines(v1: Vector2, v2: Vector2, v3: Vector2, color: Color): void -export extern "DrawTriangleFan" func DrawTriangleFan(points: ^Vector2, pointCount: i32, color: Color): void -export extern "DrawTriangleStrip" func DrawTriangleStrip(points: ^Vector2, pointCount: i32, color: Color): void -export extern "DrawPoly" func DrawPoly(center: Vector2, sides: i32, radius: f32, rotation: f32, color: Color): void -export extern "DrawPolyLines" func DrawPolyLines(center: Vector2, sides: i32, radius: f32, rotation: f32, color: Color): void -export extern "DrawPolyLinesEx" func DrawPolyLinesEx(center: Vector2, sides: i32, radius: f32, rotation: f32, lineThick: f32, color: Color): void -export extern "DrawSplineLinear" func DrawSplineLinear(points: ^Vector2, pointCount: i32, thick: f32, color: Color): void -export extern "DrawSplineBasis" func DrawSplineBasis(points: ^Vector2, pointCount: i32, thick: f32, color: Color): void -export extern "DrawSplineCatmullRom" func DrawSplineCatmullRom(points: ^Vector2, pointCount: i32, thick: f32, color: Color): void -export extern "DrawSplineBezierQuadratic" func DrawSplineBezierQuadratic(points: ^Vector2, pointCount: i32, thick: f32, color: Color): void -export extern "DrawSplineBezierCubic" func DrawSplineBezierCubic(points: ^Vector2, pointCount: i32, thick: f32, color: Color): void -export extern "DrawSplineSegmentLinear" func DrawSplineSegmentLinear(p1: Vector2, p2: Vector2, thick: f32, color: Color): void -export extern "DrawSplineSegmentBasis" func DrawSplineSegmentBasis(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, thick: f32, color: Color): void -export extern "DrawSplineSegmentCatmullRom" func DrawSplineSegmentCatmullRom(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, thick: f32, color: Color): void -export extern "DrawSplineSegmentBezierQuadratic" func DrawSplineSegmentBezierQuadratic(p1: Vector2, c2: Vector2, p3: Vector2, thick: f32, color: Color): void -export extern "DrawSplineSegmentBezierCubic" func DrawSplineSegmentBezierCubic(p1: Vector2, c2: Vector2, c3: Vector2, p4: Vector2, thick: f32, color: Color): void -export extern "GetSplinePointLinear" func GetSplinePointLinear(startPos: Vector2, endPos: Vector2, t: f32): Vector2 -export extern "GetSplinePointBasis" func GetSplinePointBasis(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, t: f32): Vector2 -export extern "GetSplinePointCatmullRom" func GetSplinePointCatmullRom(p1: Vector2, p2: Vector2, p3: Vector2, p4: Vector2, t: f32): Vector2 -export extern "GetSplinePointBezierQuad" func GetSplinePointBezierQuad(p1: Vector2, c2: Vector2, p3: Vector2, t: f32): Vector2 -export extern "GetSplinePointBezierCubic" func GetSplinePointBezierCubic(p1: Vector2, c2: Vector2, c3: Vector2, p4: Vector2, t: f32): Vector2 -export extern "CheckCollisionRecs" func CheckCollisionRecs(rec1: Rectangle, rec2: Rectangle): bool -export extern "CheckCollisionCircles" func CheckCollisionCircles(center1: Vector2, radius1: f32, center2: Vector2, radius2: f32): bool -export extern "CheckCollisionCircleRec" func CheckCollisionCircleRec(center: Vector2, radius: f32, rec: Rectangle): bool -export extern "CheckCollisionCircleLine" func CheckCollisionCircleLine(center: Vector2, radius: f32, p1: Vector2, p2: Vector2): bool -export extern "CheckCollisionPointRec" func CheckCollisionPointRec(point: Vector2, rec: Rectangle): bool -export extern "CheckCollisionPointCircle" func CheckCollisionPointCircle(point: Vector2, center: Vector2, radius: f32): bool -export extern "CheckCollisionPointTriangle" func CheckCollisionPointTriangle(point: Vector2, p1: Vector2, p2: Vector2, p3: Vector2): bool -export extern "CheckCollisionPointLine" func CheckCollisionPointLine(point: Vector2, p1: Vector2, p2: Vector2, threshold: i32): bool -export extern "CheckCollisionPointPoly" func CheckCollisionPointPoly(point: Vector2, points: ^Vector2, pointCount: i32): bool -export extern "CheckCollisionLines" func CheckCollisionLines(startPos1: Vector2, endPos1: Vector2, startPos2: Vector2, endPos2: Vector2, collisionPoint: ^Vector2): bool -export extern "GetCollisionRec" func GetCollisionRec(rec1: Rectangle, rec2: Rectangle): Rectangle -export extern "LoadImage" func LoadImage(fileName: ^i8): Image -export extern "LoadImageRaw" func LoadImageRaw(fileName: ^i8, width: i32, height: i32, format: i32, headerSize: i32): Image -export extern "LoadImageAnim" func LoadImageAnim(fileName: ^i8, frames: ^i32): Image -export extern "LoadImageAnimFromMemory" func LoadImageAnimFromMemory(fileType: ^i8, fileData: ^u8, dataSize: i32, frames: ^i32): Image -export extern "LoadImageFromMemory" func LoadImageFromMemory(fileType: ^i8, fileData: ^u8, dataSize: i32): Image -export extern "LoadImageFromTexture" func LoadImageFromTexture(texture: Texture): Image -export extern "LoadImageFromScreen" func LoadImageFromScreen(): Image -export extern "IsImageValid" func IsImageValid(image: Image): bool -export extern "UnloadImage" func UnloadImage(image: Image): void -export extern "ExportImage" func ExportImage(image: Image, fileName: ^i8): bool -export extern "ExportImageToMemory" func ExportImageToMemory(image: Image, fileType: ^i8, fileSize: ^i32): ^u8 -export extern "ExportImageAsCode" func ExportImageAsCode(image: Image, fileName: ^i8): bool -export extern "GenImageColor" func GenImageColor(width: i32, height: i32, color: Color): Image -export extern "GenImageGradientLinear" func GenImageGradientLinear(width: i32, height: i32, direction: i32, start: Color, end: Color): Image -export extern "GenImageGradientRadial" func GenImageGradientRadial(width: i32, height: i32, density: f32, inner: Color, outer: Color): Image -export extern "GenImageGradientSquare" func GenImageGradientSquare(width: i32, height: i32, density: f32, inner: Color, outer: Color): Image -export extern "GenImageChecked" func GenImageChecked(width: i32, height: i32, checksX: i32, checksY: i32, col1: Color, col2: Color): Image -export extern "GenImageWhiteNoise" func GenImageWhiteNoise(width: i32, height: i32, factor: f32): Image -export extern "GenImagePerlinNoise" func GenImagePerlinNoise(width: i32, height: i32, offsetX: i32, offsetY: i32, scale: f32): Image -export extern "GenImageCellular" func GenImageCellular(width: i32, height: i32, tileSize: i32): Image -export extern "GenImageText" func GenImageText(width: i32, height: i32, text: ^i8): Image -export extern "ImageCopy" func ImageCopy(image: Image): Image -export extern "ImageFromImage" func ImageFromImage(image: Image, rec: Rectangle): Image -export extern "ImageFromChannel" func ImageFromChannel(image: Image, selectedChannel: i32): Image -export extern "ImageText" func ImageText(text: ^i8, fontSize: i32, color: Color): Image -export extern "ImageTextEx" func ImageTextEx(font: Font, text: ^i8, fontSize: f32, spacing: f32, tint: Color): Image -export extern "ImageFormat" func ImageFormat(image: ^Image, newFormat: i32): void -export extern "ImageToPOT" func ImageToPOT(image: ^Image, fill: Color): void -export extern "ImageCrop" func ImageCrop(image: ^Image, crop: Rectangle): void -export extern "ImageAlphaCrop" func ImageAlphaCrop(image: ^Image, threshold: f32): void -export extern "ImageAlphaClear" func ImageAlphaClear(image: ^Image, color: Color, threshold: f32): void -export extern "ImageAlphaMask" func ImageAlphaMask(image: ^Image, alphaMask: Image): void -export extern "ImageAlphaPremultiply" func ImageAlphaPremultiply(image: ^Image): void -export extern "ImageBlurGaussian" func ImageBlurGaussian(image: ^Image, blurSize: i32): void -export extern "ImageKernelConvolution" func ImageKernelConvolution(image: ^Image, kernel: ^f32, kernelSize: i32): void -export extern "ImageResize" func ImageResize(image: ^Image, newWidth: i32, newHeight: i32): void -export extern "ImageResizeNN" func ImageResizeNN(image: ^Image, newWidth: i32, newHeight: i32): void -export extern "ImageResizeCanvas" func ImageResizeCanvas(image: ^Image, newWidth: i32, newHeight: i32, offsetX: i32, offsetY: i32, fill: Color): void -export extern "ImageMipmaps" func ImageMipmaps(image: ^Image): void -export extern "ImageDither" func ImageDither(image: ^Image, rBpp: i32, gBpp: i32, bBpp: i32, aBpp: i32): void -export extern "ImageFlipVertical" func ImageFlipVertical(image: ^Image): void -export extern "ImageFlipHorizontal" func ImageFlipHorizontal(image: ^Image): void -export extern "ImageRotate" func ImageRotate(image: ^Image, degrees: i32): void -export extern "ImageRotateCW" func ImageRotateCW(image: ^Image): void -export extern "ImageRotateCCW" func ImageRotateCCW(image: ^Image): void -export extern "ImageColorTint" func ImageColorTint(image: ^Image, color: Color): void -export extern "ImageColorInvert" func ImageColorInvert(image: ^Image): void -export extern "ImageColorGrayscale" func ImageColorGrayscale(image: ^Image): void -export extern "ImageColorContrast" func ImageColorContrast(image: ^Image, contrast: f32): void -export extern "ImageColorBrightness" func ImageColorBrightness(image: ^Image, brightness: i32): void -export extern "ImageColorReplace" func ImageColorReplace(image: ^Image, color: Color, replace: Color): void -export extern "LoadImageColors" func LoadImageColors(image: Image): ^Color -export extern "LoadImagePalette" func LoadImagePalette(image: Image, maxPaletteSize: i32, colorCount: ^i32): ^Color -export extern "UnloadImageColors" func UnloadImageColors(colors: ^Color): void -export extern "UnloadImagePalette" func UnloadImagePalette(colors: ^Color): void -export extern "GetImageAlphaBorder" func GetImageAlphaBorder(image: Image, threshold: f32): Rectangle -export extern "GetImageColor" func GetImageColor(image: Image, x: i32, y: i32): Color -export extern "ImageClearBackground" func ImageClearBackground(dst: ^Image, color: Color): void -export extern "ImageDrawPixel" func ImageDrawPixel(dst: ^Image, posX: i32, posY: i32, color: Color): void -export extern "ImageDrawPixelV" func ImageDrawPixelV(dst: ^Image, position: Vector2, color: Color): void -export extern "ImageDrawLine" func ImageDrawLine(dst: ^Image, startPosX: i32, startPosY: i32, endPosX: i32, endPosY: i32, color: Color): void -export extern "ImageDrawLineV" func ImageDrawLineV(dst: ^Image, start: Vector2, end: Vector2, color: Color): void -export extern "ImageDrawLineEx" func ImageDrawLineEx(dst: ^Image, start: Vector2, end: Vector2, thick: i32, color: Color): void -export extern "ImageDrawCircle" func ImageDrawCircle(dst: ^Image, centerX: i32, centerY: i32, radius: i32, color: Color): void -export extern "ImageDrawCircleV" func ImageDrawCircleV(dst: ^Image, center: Vector2, radius: i32, color: Color): void -export extern "ImageDrawCircleLines" func ImageDrawCircleLines(dst: ^Image, centerX: i32, centerY: i32, radius: i32, color: Color): void -export extern "ImageDrawCircleLinesV" func ImageDrawCircleLinesV(dst: ^Image, center: Vector2, radius: i32, color: Color): void -export extern "ImageDrawRectangle" func ImageDrawRectangle(dst: ^Image, posX: i32, posY: i32, width: i32, height: i32, color: Color): void -export extern "ImageDrawRectangleV" func ImageDrawRectangleV(dst: ^Image, position: Vector2, size: Vector2, color: Color): void -export extern "ImageDrawRectangleRec" func ImageDrawRectangleRec(dst: ^Image, rec: Rectangle, color: Color): void -export extern "ImageDrawRectangleLines" func ImageDrawRectangleLines(dst: ^Image, rec: Rectangle, thick: i32, color: Color): void -export extern "ImageDrawTriangle" func ImageDrawTriangle(dst: ^Image, v1: Vector2, v2: Vector2, v3: Vector2, color: Color): void -export extern "ImageDrawTriangleEx" func ImageDrawTriangleEx(dst: ^Image, v1: Vector2, v2: Vector2, v3: Vector2, c1: Color, c2: Color, c3: Color): void -export extern "ImageDrawTriangleLines" func ImageDrawTriangleLines(dst: ^Image, v1: Vector2, v2: Vector2, v3: Vector2, color: Color): void -export extern "ImageDrawTriangleFan" func ImageDrawTriangleFan(dst: ^Image, points: ^Vector2, pointCount: i32, color: Color): void -export extern "ImageDrawTriangleStrip" func ImageDrawTriangleStrip(dst: ^Image, points: ^Vector2, pointCount: i32, color: Color): void -export extern "ImageDraw" func ImageDraw(dst: ^Image, src: Image, srcRec: Rectangle, dstRec: Rectangle, tint: Color): void -export extern "ImageDrawText" func ImageDrawText(dst: ^Image, text: ^i8, posX: i32, posY: i32, fontSize: i32, color: Color): void -export extern "ImageDrawTextEx" func ImageDrawTextEx(dst: ^Image, font: Font, text: ^i8, position: Vector2, fontSize: f32, spacing: f32, tint: Color): void -export extern "LoadTexture" func LoadTexture(fileName: ^i8): Texture -export extern "LoadTextureFromImage" func LoadTextureFromImage(image: Image): Texture -export extern "LoadTextureCubemap" func LoadTextureCubemap(image: Image, layout: i32): Texture -export extern "LoadRenderTexture" func LoadRenderTexture(width: i32, height: i32): RenderTexture -export extern "IsTextureValid" func IsTextureValid(texture: Texture): bool -export extern "UnloadTexture" func UnloadTexture(texture: Texture): void -export extern "IsRenderTextureValid" func IsRenderTextureValid(target: RenderTexture): bool -export extern "UnloadRenderTexture" func UnloadRenderTexture(target: RenderTexture): void -export extern "UpdateTexture" func UpdateTexture(texture: Texture, pixels: ^void): void -export extern "UpdateTextureRec" func UpdateTextureRec(texture: Texture, rec: Rectangle, pixels: ^void): void -export extern "GenTextureMipmaps" func GenTextureMipmaps(texture: ^Texture): void -export extern "SetTextureFilter" func SetTextureFilter(texture: Texture, filter: i32): void -export extern "SetTextureWrap" func SetTextureWrap(texture: Texture, wrap: i32): void -export extern "DrawTexture" func DrawTexture(texture: Texture, posX: i32, posY: i32, tint: Color): void -export extern "DrawTextureV" func DrawTextureV(texture: Texture, position: Vector2, tint: Color): void -export extern "DrawTextureEx" func DrawTextureEx(texture: Texture, position: Vector2, rotation: f32, scale: f32, tint: Color): void -export extern "DrawTextureRec" func DrawTextureRec(texture: Texture, source: Rectangle, position: Vector2, tint: Color): void -export extern "DrawTexturePro" func DrawTexturePro(texture: Texture, source: Rectangle, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color): void -export extern "DrawTextureNPatch" func DrawTextureNPatch(texture: Texture, nPatchInfo: NPatchInfo, dest: Rectangle, origin: Vector2, rotation: f32, tint: Color): void -export extern "ColorIsEqual" func ColorIsEqual(col1: Color, col2: Color): bool -export extern "Fade" func Fade(color: Color, alpha: f32): Color -export extern "ColorToInt" func ColorToInt(color: Color): i32 -export extern "ColorNormalize" func ColorNormalize(color: Color): Vector4 -export extern "ColorFromNormalized" func ColorFromNormalized(normalized: Vector4): Color -export extern "ColorToHSV" func ColorToHSV(color: Color): Vector3 -export extern "ColorFromHSV" func ColorFromHSV(hue: f32, saturation: f32, value: f32): Color -export extern "ColorTint" func ColorTint(color: Color, tint: Color): Color -export extern "ColorBrightness" func ColorBrightness(color: Color, factor: f32): Color -export extern "ColorContrast" func ColorContrast(color: Color, contrast: f32): Color -export extern "ColorAlpha" func ColorAlpha(color: Color, alpha: f32): Color -export extern "ColorAlphaBlend" func ColorAlphaBlend(dst: Color, src: Color, tint: Color): Color -export extern "ColorLerp" func ColorLerp(color1: Color, color2: Color, factor: f32): Color -export extern "GetColor" func GetColor(hexValue: u32): Color -export extern "GetPixelColor" func GetPixelColor(srcPtr: ^void, format: i32): Color -export extern "SetPixelColor" func SetPixelColor(dstPtr: ^void, color: Color, format: i32): void -export extern "GetPixelDataSize" func GetPixelDataSize(width: i32, height: i32, format: i32): i32 -export extern "GetFontDefault" func GetFontDefault(): Font -export extern "LoadFont" func LoadFont(fileName: ^i8): Font -export extern "LoadFontEx" func LoadFontEx(fileName: ^i8, fontSize: i32, codepoints: ^i32, codepointCount: i32): Font -export extern "LoadFontFromImage" func LoadFontFromImage(image: Image, key: Color, firstChar: i32): Font -export extern "LoadFontFromMemory" func LoadFontFromMemory(fileType: ^i8, fileData: ^u8, dataSize: i32, fontSize: i32, codepoints: ^i32, codepointCount: i32): Font -export extern "IsFontValid" func IsFontValid(font: Font): bool -export extern "LoadFontData" func LoadFontData(fileData: ^u8, dataSize: i32, fontSize: i32, codepoints: ^i32, codepointCount: i32, type: i32): ^GlyphInfo -export extern "GenImageFontAtlas" func GenImageFontAtlas(glyphs: ^GlyphInfo, glyphRecs: ^^Rectangle, glyphCount: i32, fontSize: i32, padding: i32, packMethod: i32): Image -export extern "UnloadFontData" func UnloadFontData(glyphs: ^GlyphInfo, glyphCount: i32): void -export extern "UnloadFont" func UnloadFont(font: Font): void -export extern "ExportFontAsCode" func ExportFontAsCode(font: Font, fileName: ^i8): bool -export extern "DrawFPS" func DrawFPS(posX: i32, posY: i32): void -export extern "DrawText" func DrawText(text: ^i8, posX: i32, posY: i32, fontSize: i32, color: Color): void -export extern "DrawTextEx" func DrawTextEx(font: Font, text: ^i8, position: Vector2, fontSize: f32, spacing: f32, tint: Color): void -export extern "DrawTextPro" func DrawTextPro(font: Font, text: ^i8, position: Vector2, origin: Vector2, rotation: f32, fontSize: f32, spacing: f32, tint: Color): void -export extern "DrawTextCodepoint" func DrawTextCodepoint(font: Font, codepoint: i32, position: Vector2, fontSize: f32, tint: Color): void -export extern "DrawTextCodepoints" func DrawTextCodepoints(font: Font, codepoints: ^i32, codepointCount: i32, position: Vector2, fontSize: f32, spacing: f32, tint: Color): void -export extern "SetTextLineSpacing" func SetTextLineSpacing(spacing: i32): void -export extern "MeasureText" func MeasureText(text: ^i8, fontSize: i32): i32 -export extern "MeasureTextEx" func MeasureTextEx(font: Font, text: ^i8, fontSize: f32, spacing: f32): Vector2 -export extern "GetGlyphIndex" func GetGlyphIndex(font: Font, codepoint: i32): i32 -export extern "GetGlyphInfo" func GetGlyphInfo(font: Font, codepoint: i32): GlyphInfo -export extern "GetGlyphAtlasRec" func GetGlyphAtlasRec(font: Font, codepoint: i32): Rectangle -export extern "LoadUTF8" func LoadUTF8(codepoints: ^i32, length: i32): ^i8 -export extern "UnloadUTF8" func UnloadUTF8(text: ^i8): void -export extern "LoadCodepoints" func LoadCodepoints(text: ^i8, count: ^i32): ^i32 -export extern "UnloadCodepoints" func UnloadCodepoints(codepoints: ^i32): void -export extern "GetCodepointCount" func GetCodepointCount(text: ^i8): i32 -export extern "GetCodepoint" func GetCodepoint(text: ^i8, codepointSize: ^i32): i32 -export extern "GetCodepointNext" func GetCodepointNext(text: ^i8, codepointSize: ^i32): i32 -export extern "GetCodepointPrevious" func GetCodepointPrevious(text: ^i8, codepointSize: ^i32): i32 -export extern "CodepointToUTF8" func CodepointToUTF8(codepoint: i32, utf8Size: ^i32): ^i8 -export extern "TextCopy" func TextCopy(dst: ^i8, src: ^i8): i32 -export extern "TextIsEqual" func TextIsEqual(text1: ^i8, text2: ^i8): bool -export extern "TextLength" func TextLength(text: ^i8): u32 -export extern "TextFormat" func TextFormat(text: ^i8): ^i8 -export extern "TextSubtext" func TextSubtext(text: ^i8, position: i32, length: i32): ^i8 -export extern "TextReplace" func TextReplace(text: ^i8, replace: ^i8, by: ^i8): ^i8 -export extern "TextInsert" func TextInsert(text: ^i8, insert: ^i8, position: i32): ^i8 -export extern "TextJoin" func TextJoin(textList: ^^i8, count: i32, delimiter: ^i8): ^i8 -export extern "TextSplit" func TextSplit(text: ^i8, delimiter: i8, count: ^i32): ^^i8 -export extern "TextAppend" func TextAppend(text: ^i8, append: ^i8, position: ^i32): void -export extern "TextFindIndex" func TextFindIndex(text: ^i8, find: ^i8): i32 -export extern "TextToUpper" func TextToUpper(text: ^i8): ^i8 -export extern "TextToLower" func TextToLower(text: ^i8): ^i8 -export extern "TextToPascal" func TextToPascal(text: ^i8): ^i8 -export extern "TextToSnake" func TextToSnake(text: ^i8): ^i8 -export extern "TextToCamel" func TextToCamel(text: ^i8): ^i8 -export extern "TextToInteger" func TextToInteger(text: ^i8): i32 -export extern "TextToFloat" func TextToFloat(text: ^i8): f32 -export extern "DrawLine3D" func DrawLine3D(startPos: Vector3, endPos: Vector3, color: Color): void -export extern "DrawPoint3D" func DrawPoint3D(position: Vector3, color: Color): void -export extern "DrawCircle3D" func DrawCircle3D(center: Vector3, radius: f32, rotationAxis: Vector3, rotationAngle: f32, color: Color): void -export extern "DrawTriangle3D" func DrawTriangle3D(v1: Vector3, v2: Vector3, v3: Vector3, color: Color): void -export extern "DrawTriangleStrip3D" func DrawTriangleStrip3D(points: ^Vector3, pointCount: i32, color: Color): void -export extern "DrawCube" func DrawCube(position: Vector3, width: f32, height: f32, length: f32, color: Color): void -export extern "DrawCubeV" func DrawCubeV(position: Vector3, size: Vector3, color: Color): void -export extern "DrawCubeWires" func DrawCubeWires(position: Vector3, width: f32, height: f32, length: f32, color: Color): void -export extern "DrawCubeWiresV" func DrawCubeWiresV(position: Vector3, size: Vector3, color: Color): void -export extern "DrawSphere" func DrawSphere(centerPos: Vector3, radius: f32, color: Color): void -export extern "DrawSphereEx" func DrawSphereEx(centerPos: Vector3, radius: f32, rings: i32, slices: i32, color: Color): void -export extern "DrawSphereWires" func DrawSphereWires(centerPos: Vector3, radius: f32, rings: i32, slices: i32, color: Color): void -export extern "DrawCylinder" func DrawCylinder(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: i32, color: Color): void -export extern "DrawCylinderEx" func DrawCylinderEx(startPos: Vector3, endPos: Vector3, startRadius: f32, endRadius: f32, sides: i32, color: Color): void -export extern "DrawCylinderWires" func DrawCylinderWires(position: Vector3, radiusTop: f32, radiusBottom: f32, height: f32, slices: i32, color: Color): void -export extern "DrawCylinderWiresEx" func DrawCylinderWiresEx(startPos: Vector3, endPos: Vector3, startRadius: f32, endRadius: f32, sides: i32, color: Color): void -export extern "DrawCapsule" func DrawCapsule(startPos: Vector3, endPos: Vector3, radius: f32, slices: i32, rings: i32, color: Color): void -export extern "DrawCapsuleWires" func DrawCapsuleWires(startPos: Vector3, endPos: Vector3, radius: f32, slices: i32, rings: i32, color: Color): void -export extern "DrawPlane" func DrawPlane(centerPos: Vector3, size: Vector2, color: Color): void -export extern "DrawRay" func DrawRay(ray: Ray, color: Color): void -export extern "DrawGrid" func DrawGrid(slices: i32, spacing: f32): void -export extern "LoadModel" func LoadModel(fileName: ^i8): Model -export extern "LoadModelFromMesh" func LoadModelFromMesh(mesh: Mesh): Model -export extern "IsModelValid" func IsModelValid(model: Model): bool -export extern "UnloadModel" func UnloadModel(model: Model): void -export extern "GetModelBoundingBox" func GetModelBoundingBox(model: Model): BoundingBox -export extern "DrawModel" func DrawModel(model: Model, position: Vector3, scale: f32, tint: Color): void -export extern "DrawModelEx" func DrawModelEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color): void -export extern "DrawModelWires" func DrawModelWires(model: Model, position: Vector3, scale: f32, tint: Color): void -export extern "DrawModelWiresEx" func DrawModelWiresEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color): void -export extern "DrawModelPoints" func DrawModelPoints(model: Model, position: Vector3, scale: f32, tint: Color): void -export extern "DrawModelPointsEx" func DrawModelPointsEx(model: Model, position: Vector3, rotationAxis: Vector3, rotationAngle: f32, scale: Vector3, tint: Color): void -export extern "DrawBoundingBox" func DrawBoundingBox(box: BoundingBox, color: Color): void -export extern "DrawBillboard" func DrawBillboard(camera: Camera3D, texture: Texture, position: Vector3, scale: f32, tint: Color): void -export extern "DrawBillboardRec" func DrawBillboardRec(camera: Camera3D, texture: Texture, source: Rectangle, position: Vector3, size: Vector2, tint: Color): void -export extern "DrawBillboardPro" func DrawBillboardPro(camera: Camera3D, texture: Texture, source: Rectangle, position: Vector3, up: Vector3, size: Vector2, origin: Vector2, rotation: f32, tint: Color): void -export extern "UploadMesh" func UploadMesh(mesh: ^Mesh, dynamic: bool): void -export extern "UpdateMeshBuffer" func UpdateMeshBuffer(mesh: Mesh, index: i32, data: ^void, dataSize: i32, offset: i32): void -export extern "UnloadMesh" func UnloadMesh(mesh: Mesh): void -export extern "DrawMesh" func DrawMesh(mesh: Mesh, material: Material, transform: Matrix): void -export extern "DrawMeshInstanced" func DrawMeshInstanced(mesh: Mesh, material: Material, transforms: ^Matrix, instances: i32): void -export extern "GetMeshBoundingBox" func GetMeshBoundingBox(mesh: Mesh): BoundingBox -export extern "GenMeshTangents" func GenMeshTangents(mesh: ^Mesh): void -export extern "ExportMesh" func ExportMesh(mesh: Mesh, fileName: ^i8): bool -export extern "ExportMeshAsCode" func ExportMeshAsCode(mesh: Mesh, fileName: ^i8): bool -export extern "GenMeshPoly" func GenMeshPoly(sides: i32, radius: f32): Mesh -export extern "GenMeshPlane" func GenMeshPlane(width: f32, length: f32, resX: i32, resZ: i32): Mesh -export extern "GenMeshCube" func GenMeshCube(width: f32, height: f32, length: f32): Mesh -export extern "GenMeshSphere" func GenMeshSphere(radius: f32, rings: i32, slices: i32): Mesh -export extern "GenMeshHemiSphere" func GenMeshHemiSphere(radius: f32, rings: i32, slices: i32): Mesh -export extern "GenMeshCylinder" func GenMeshCylinder(radius: f32, height: f32, slices: i32): Mesh -export extern "GenMeshCone" func GenMeshCone(radius: f32, height: f32, slices: i32): Mesh -export extern "GenMeshTorus" func GenMeshTorus(radius: f32, size: f32, radSeg: i32, sides: i32): Mesh -export extern "GenMeshKnot" func GenMeshKnot(radius: f32, size: f32, radSeg: i32, sides: i32): Mesh -export extern "GenMeshHeightmap" func GenMeshHeightmap(heightmap: Image, size: Vector3): Mesh -export extern "GenMeshCubicmap" func GenMeshCubicmap(cubicmap: Image, cubeSize: Vector3): Mesh -export extern "LoadMaterials" func LoadMaterials(fileName: ^i8, materialCount: ^i32): ^Material -export extern "LoadMaterialDefault" func LoadMaterialDefault(): Material -export extern "IsMaterialValid" func IsMaterialValid(material: Material): bool -export extern "UnloadMaterial" func UnloadMaterial(material: Material): void -export extern "SetMaterialTexture" func SetMaterialTexture(material: ^Material, mapType: i32, texture: Texture): void -export extern "SetModelMeshMaterial" func SetModelMeshMaterial(model: ^Model, meshId: i32, materialId: i32): void -export extern "LoadModelAnimations" func LoadModelAnimations(fileName: ^i8, animCount: ^i32): ^ModelAnimation -export extern "UpdateModelAnimation" func UpdateModelAnimation(model: Model, anim: ModelAnimation, frame: i32): void -export extern "UpdateModelAnimationBones" func UpdateModelAnimationBones(model: Model, anim: ModelAnimation, frame: i32): void -export extern "UnloadModelAnimation" func UnloadModelAnimation(anim: ModelAnimation): void -export extern "UnloadModelAnimations" func UnloadModelAnimations(animations: ^ModelAnimation, animCount: i32): void -export extern "IsModelAnimationValid" func IsModelAnimationValid(model: Model, anim: ModelAnimation): bool -export extern "CheckCollisionSpheres" func CheckCollisionSpheres(center1: Vector3, radius1: f32, center2: Vector3, radius2: f32): bool -export extern "CheckCollisionBoxes" func CheckCollisionBoxes(box1: BoundingBox, box2: BoundingBox): bool -export extern "CheckCollisionBoxSphere" func CheckCollisionBoxSphere(box: BoundingBox, center: Vector3, radius: f32): bool -export extern "GetRayCollisionSphere" func GetRayCollisionSphere(ray: Ray, center: Vector3, radius: f32): RayCollision -export extern "GetRayCollisionBox" func GetRayCollisionBox(ray: Ray, box: BoundingBox): RayCollision -export extern "GetRayCollisionMesh" func GetRayCollisionMesh(ray: Ray, mesh: Mesh, transform: Matrix): RayCollision -export extern "GetRayCollisionTriangle" func GetRayCollisionTriangle(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3): RayCollision -export extern "GetRayCollisionQuad" func GetRayCollisionQuad(ray: Ray, p1: Vector3, p2: Vector3, p3: Vector3, p4: Vector3): RayCollision -export extern "InitAudioDevice" func InitAudioDevice(): void -export extern "CloseAudioDevice" func CloseAudioDevice(): void -export extern "IsAudioDeviceReady" func IsAudioDeviceReady(): bool -export extern "SetMasterVolume" func SetMasterVolume(volume: f32): void -export extern "GetMasterVolume" func GetMasterVolume(): f32 -export extern "LoadWave" func LoadWave(fileName: ^i8): Wave -export extern "LoadWaveFromMemory" func LoadWaveFromMemory(fileType: ^i8, fileData: ^u8, dataSize: i32): Wave -export extern "IsWaveValid" func IsWaveValid(wave: Wave): bool -export extern "LoadSound" func LoadSound(fileName: ^i8): Sound -export extern "LoadSoundFromWave" func LoadSoundFromWave(wave: Wave): Sound -export extern "LoadSoundAlias" func LoadSoundAlias(source: Sound): Sound -export extern "IsSoundValid" func IsSoundValid(sound: Sound): bool -export extern "UpdateSound" func UpdateSound(sound: Sound, data: ^void, sampleCount: i32): void -export extern "UnloadWave" func UnloadWave(wave: Wave): void -export extern "UnloadSound" func UnloadSound(sound: Sound): void -export extern "UnloadSoundAlias" func UnloadSoundAlias(alias: Sound): void -export extern "ExportWave" func ExportWave(wave: Wave, fileName: ^i8): bool -export extern "ExportWaveAsCode" func ExportWaveAsCode(wave: Wave, fileName: ^i8): bool -export extern "PlaySound" func PlaySound(sound: Sound): void -export extern "StopSound" func StopSound(sound: Sound): void -export extern "PauseSound" func PauseSound(sound: Sound): void -export extern "ResumeSound" func ResumeSound(sound: Sound): void -export extern "IsSoundPlaying" func IsSoundPlaying(sound: Sound): bool -export extern "SetSoundVolume" func SetSoundVolume(sound: Sound, volume: f32): void -export extern "SetSoundPitch" func SetSoundPitch(sound: Sound, pitch: f32): void -export extern "SetSoundPan" func SetSoundPan(sound: Sound, pan: f32): void -export extern "WaveCopy" func WaveCopy(wave: Wave): Wave -export extern "WaveCrop" func WaveCrop(wave: ^Wave, initFrame: i32, finalFrame: i32): void -export extern "WaveFormat" func WaveFormat(wave: ^Wave, sampleRate: i32, sampleSize: i32, channels: i32): void -export extern "LoadWaveSamples" func LoadWaveSamples(wave: Wave): ^f32 -export extern "UnloadWaveSamples" func UnloadWaveSamples(samples: ^f32): void -export extern "LoadMusicStream" func LoadMusicStream(fileName: ^i8): Music -export extern "LoadMusicStreamFromMemory" func LoadMusicStreamFromMemory(fileType: ^i8, data: ^u8, dataSize: i32): Music -export extern "IsMusicValid" func IsMusicValid(music: Music): bool -export extern "UnloadMusicStream" func UnloadMusicStream(music: Music): void -export extern "PlayMusicStream" func PlayMusicStream(music: Music): void -export extern "IsMusicStreamPlaying" func IsMusicStreamPlaying(music: Music): bool -export extern "UpdateMusicStream" func UpdateMusicStream(music: Music): void -export extern "StopMusicStream" func StopMusicStream(music: Music): void -export extern "PauseMusicStream" func PauseMusicStream(music: Music): void -export extern "ResumeMusicStream" func ResumeMusicStream(music: Music): void -export extern "SeekMusicStream" func SeekMusicStream(music: Music, position: f32): void -export extern "SetMusicVolume" func SetMusicVolume(music: Music, volume: f32): void -export extern "SetMusicPitch" func SetMusicPitch(music: Music, pitch: f32): void -export extern "SetMusicPan" func SetMusicPan(music: Music, pan: f32): void -export extern "GetMusicTimeLength" func GetMusicTimeLength(music: Music): f32 -export extern "GetMusicTimePlayed" func GetMusicTimePlayed(music: Music): f32 -export extern "LoadAudioStream" func LoadAudioStream(sampleRate: u32, sampleSize: u32, channels: u32): AudioStream -export extern "IsAudioStreamValid" func IsAudioStreamValid(stream: AudioStream): bool -export extern "UnloadAudioStream" func UnloadAudioStream(stream: AudioStream): void -export extern "UpdateAudioStream" func UpdateAudioStream(stream: AudioStream, data: ^void, frameCount: i32): void -export extern "IsAudioStreamProcessed" func IsAudioStreamProcessed(stream: AudioStream): bool -export extern "PlayAudioStream" func PlayAudioStream(stream: AudioStream): void -export extern "PauseAudioStream" func PauseAudioStream(stream: AudioStream): void -export extern "ResumeAudioStream" func ResumeAudioStream(stream: AudioStream): void -export extern "IsAudioStreamPlaying" func IsAudioStreamPlaying(stream: AudioStream): bool -export extern "StopAudioStream" func StopAudioStream(stream: AudioStream): void -export extern "SetAudioStreamVolume" func SetAudioStreamVolume(stream: AudioStream, volume: f32): void -export extern "SetAudioStreamPitch" func SetAudioStreamPitch(stream: AudioStream, pitch: f32): void -export extern "SetAudioStreamPan" func SetAudioStreamPan(stream: AudioStream, pan: f32): void -export extern "SetAudioStreamBufferSizeDefault" func SetAudioStreamBufferSizeDefault(size: i32): void -export extern "SetAudioStreamCallback" func SetAudioStreamCallback(stream: AudioStream, callback: func(^void, u32): void): void -export extern "AttachAudioStreamProcessor" func AttachAudioStreamProcessor(stream: AudioStream, processor: func(^void, u32): void): void -export extern "DetachAudioStreamProcessor" func DetachAudioStreamProcessor(stream: AudioStream, processor: func(^void, u32): void): void -export extern "AttachAudioMixedProcessor" func AttachAudioMixedProcessor(processor: func(^void, u32): void): void -export extern "DetachAudioMixedProcessor" func DetachAudioMixedProcessor(processor: func(^void, u32): void): void diff --git a/examples/raylib/main.nub b/examples/raylib/main.nub deleted file mode 100644 index fd0fc2e..0000000 --- a/examples/raylib/main.nub +++ /dev/null @@ -1,55 +0,0 @@ -import "raylib" - -module "main" - -extern "main" func main(argc: i64, argv: [?]^i8): i64 -{ - let uwu: []i32 = [1, 2] - - raylib::SetConfigFlags(raylib::ConfigFlags.FLAG_VSYNC_HINT | raylib::ConfigFlags.FLAG_WINDOW_RESIZABLE) - - raylib::InitWindow(1600, 900, "Hi from nub-lang") - defer raylib::CloseWindow() - - raylib::SetTargetFPS(240) - - let width: i32 = 150 - let height: i32 = 150 - - let x: i32 = raylib::GetScreenWidth() / 2 - (width / 2) - let y: i32 = raylib::GetScreenHeight() / 2 - (height / 2) - - let direction: raylib::Vector2 = { x = 1 y = 1 } - let speed: f32 = 250 - - let bgColor: raylib::Color = { r = 0 g = 0 b = 0 a = 255 } - let color: raylib::Color = { r = 255 g = 255 b = 255 a = 255 } - - while !raylib::WindowShouldClose() - { - if x <= 0 { - direction.x = 1 - } else if x + width >= raylib::GetScreenWidth() { - direction.x = -1 - } - - if y <= 0 { - direction.y = 1 - } else if y + height >= raylib::GetScreenHeight() { - direction.y = -1 - } - - x = x + @cast(direction.x * speed * raylib::GetFrameTime()) - y = y + @cast(direction.y * speed * raylib::GetFrameTime()) - - raylib::BeginDrawing() - { - raylib::ClearBackground(bgColor) - raylib::DrawFPS(10, 10) - raylib::DrawRectangle(x, y, width, height, color) - } - raylib::EndDrawing() - } - - return 0 -} \ No newline at end of file diff --git a/examples/raylib/raylib-5.5_linux_amd64/CHANGELOG b/examples/raylib/raylib-5.5_linux_amd64/CHANGELOG deleted file mode 100644 index 61e12a3..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/CHANGELOG +++ /dev/null @@ -1,2599 +0,0 @@ -changelog ---------- - -Current Release: raylib 5.5 (18 November 2024) - -------------------------------------------------------------------------- -Release: raylib 5.5 (18 November 2024) -------------------------------------------------------------------------- -KEY CHANGES: - - New tool: raylib project creator - - New rcore backends: RGFW and SDL3 - - New platforms supported: Dreamcast, N64, PSP, PSVita, PS4 - - Added GPU Skinning support (all platforms and GL versions) - - Added raymath C++ operators - -Detailed changes: - -WIP: Last update with commit from 02-Nov-2024 - -[rcore] ADDED: Working directory info at initialization by @Ray -[rcore] ADDED: `GetClipboardImage()`, supported by multiple backends (#4459) by @evertonse -[rcore] ADDED: `MakeDirectory()`, supporting recursive directory creation by @Ray -[rcore] ADDED: `ComputeSHA1()` (#4390) by @Anthony Carbajal -[rcore] ADDED: `ComputeCRC32()` and `ComputeMD5()` by @Ray -[rcore] ADDED: `GetKeyName()` (#4161) by @MrScautHD -[rcore] ADDED: `IsFileNameValid()` by @Ray -[rcore] ADDED: `GetViewRay()`, viewport independent raycast (#3709) by @Luís Almeida -[rcore] RENAMED: `GetMouseRay()` to `GetScreenToWorldRay()` (#3830) by @Ray -[rcore] RENAMED: `GetViewRay()` to `GetScreenToWorldRayEx()` (#3830) by @Ray -[rcore] REVIEWED: `GetApplicationDirectory()` for FreeBSD (#4318) by @base -[rcore] REVIEWED: `LoadDirectoryFilesEx()`/`ScanDirectoryFiles()`, support directory on filter (#4302) by @foxblock -[rcore] REVIEWED: Update comments on fullscreen and boderless window to describe what they do (#4280) by @Jeffery Myers -[rcore] REVIEWED: Correct processing of mouse wheel on Automation events #4263 by @Ray -[rcore] REVIEWED: Fix gamepad axis movement and its automation event recording (#4184) by @maxmutant -[rcore] REVIEWED: Do not set RL_TEXTURE_FILTER_LINEAR when high dpi flag is enabled (#4189) by @Dave Green -[rcore] REVIEWED: `GetScreenWidth()`/`GetScreenHeight()` (#4074) by @Anthony Carbajal -[rcore] REVIEWED: Initial window dimensions checks (#3950) by @Christian Haas -[rcore] REVIEWED: Set default init values for random #3954 by @Ray -[rcore] REVIEWED: Window positioning, avoid out-of-screen window-bar by @Ray -[rcore] REVIEWED: Fix framerate recording for .gif (#3894) by @Rob Loach -[rcore] REVIEWED: Screen space related functions consistency (#3830) by @aiafrasinei -[rcore] REVIEWED: `GetFileNameWithoutExt()` (#3771) by @oblerion -[rcore] REVIEWED: `GetWindowScaleDPI()`, simplified (#3701) by @Karl Zylinski -[rcore] REVIEWED: `UnloadAutomationEventList()` (#3658) by @Antonis Geralis -[rcore] REVIEWED: Flip VR screens (#3633) by @Matthew Oros -[rcore] REVIEWED: Remove unused vScreenCenter (#3632) by @Matthew Oros -[rcore] REVIEWED: `LoadRandomSequence()`, issue in sequence generation #3612 by @Ray -[rcore] REVIEWED: `IsMouseButtonUp()` (#3609) by @Kenneth M -[rcore] REVIEWED: Fix typos in src/platforms/rcore_*.c (#3581) by @RadsammyT -[rcore] REVIEWED: `ExportDataAsCode()`, change sanitization check (#3837) by @Laurentino Luna -[rcore] REVIEWED: `ExportDataAsCode()`, add little sanitization to indentifier names (#3832) by @4rk -[rcore] REVIEWED: `GetScreenWidth()`/`GetScreenHeight()` align with all platforms (#4451) by @Arche Washi -[rcore] REVIEWED: `SetGamepadVibration()`, added duration parameter (#4410) by @Asdqwe -WARNING- -[rcore] REVIEWED: `GetGamepadAxisMovement()`, fix #4405 (#4420) by @Asdqwe -[rcore] REVIEWED: `GetGestureHoldDuration()` comments by @Ray -[rcore][rlgl] REVIEWED: Fix scale issues when ending a view mode (#3746) by @Jeffery Myers -[rcore][GLFW] REVIEWED: Keep CORE.Window.position properly in sync with glfw window position (#4190) by @Dave Green -[rcore][GLFW] REVIEWED: Set AUTO_ICONIFY flag to false per default (#4188) by @Dave Green -[rcore][GLFW] REVIEWED: `InitPlatform()`, add workaround for NetBSD (#4139) by @NishiOwO -[rcore][GLFW] REVIEWED: Fix window not initializing on primary monitor (#3923) by @Rafael Bordoni -[rcore][GLFW] REVIEWED: Set relative mouse mode when the cursor is disabled (#3874) by @Jeffery Myers -[rcore][GLFW] REVIEWED: Remove GLFW mouse passthrough hack and increase GLFW version in CMake (#3852) by @Alexandre Almeida -[rcore][GLFW] REVIEWED: Updated GLFW to 3.4 (#3827) by @Alexandre Almeida -[rcore][GLFW] REVIEWED: Feature test macros before include (#3737) by @John -[rcore][GLFW] REVIEWED: Fix inconsistent dll linkage warning on windows (#4447) by @Jeffery Myers -[rcore][Web] ADDED: `SetWindowOpacity()` implementation (#4403) by @Asdqwe -[rcore][Web] ADDED: `MaximizeWindow()` and `RestoreWindow()` implementations (#4397) by @Asdqwe -[rcore][Web] ADDED: `ToggleFullscreen()` implementation (#3634) by @ubkp -[rcore][Web] ADDED: `GetWindowPosition()` implementation (#3637) by @ubkp -[rcore][Web] ADDED: `ToggleBorderlessWindowed()` implementation (#3622) by @ubkp -[rcore][Web] ADDED: `GetMonitorWidth()` and `GetMonitorHeight()` implementations (#3636) by @ubkp -[rcore][Web] REVIEWED: Update `SetWindowState()` and `ClearWindowState()` to handle `FLAG_WINDOW_MAXIMIZED` (#4402) by @Asdqwe -[rcore][Web] REVIEWED: `WindowSizeCallback()`, do not try to handle DPI, already managed by GLFW (#4143) by @SuperUserNameMan -[rcore][Web] REVIEWED: Relative mouse mode issues (#3940) by @Cemal Gönültaş -[rcore][Web] REVIEWED: `ShowCursor()`, `HideCursor()` and `SetMouseCursor()` (#3647) by @ubkp -[rcore][Web] REVIEWED: Fix CORE.Input.Mouse.cursorHidden with callbacks (#3644) by @ubkp -[rcore][Web] REVIEWED: Fix `IsMouseButtonUp()` (#3611) by @ubkp -[rcore][Web] REVIEWED: HighDPI support #3372 by @Ray -[rcore][Web] REVIEWED: `SetWindowSize()` (#4452) by @Asdqwe -[rcore][Web] REVIEWED: `EmscriptenResizeCallback()`, simplified (#4415) by @Asdqwe -[rcore][SDL] ADDED: `IsCursorOnScreen()` (#3862) by @Peter0x44 -[rcore][SDL] ADDED: Gamepad rumble/vibration support (#3819) by @GideonSerf -[rcore][SDL] REVIEWED: Gamepad support (#3776) by @A -[rcore][SDL] REVIEWED: `GetWorkingDirectory()`, return correct path (#4392) by @Asdqwe -[rcore][SDL] REVIEWED: `GetClipboardText()`, fix memory leak (#4354) by @Asdqwe -[rcore][SDL] REVIEWED: Change SDL_Joystick to SDL_GameController (#4129) by @Frank Kartheuser -[rcore][SDL] REVIEWED: Update storage base path, use provided SDL base path by @Ray -[rcore][SDL] REVIEWED: Call SDL_GL_SetSwapInterval() after GL context creation (#3997) by @JupiterRider -[rcore][SDL] REVIEWED: `GetKeyPressed()` (#3869) by @Arthur -[rcore][SDL] REVIEWED: Fix SDL multitouch tracking (#3810) by @mooff -[rcore][SDL] REVIEWED: Fix `SUPPORT_WINMM_HIGHRES_TIMER` (#3679) by @ubkp -[rcore][SDL] REVIEWED: SDL text input to Unicode codepoints #3650 by @Ray -[rcore][SDL] REVIEWED: `IsMouseButtonUp()` and add touch events (#3610) by @ubkp -[rcore][SDL] REVIEWED: Fix real touch gestures (#3614) by @ubkp -[rcore][SDL] REVIEWED: `IsKeyPressedRepeat()` (#3605) by @ubkp -[rcore][SDL] REVIEWED: `GetKeyPressed()` and `GetCharPressed()` for SDL (#3604) by @ubkp -[rcore][SDL] REVIEWED: `SetMousePosition()` for SDL (#3580) by @ubkp -[rcore][SDL] REVIEWED: `SetWindowIcon()` for SDL (#3578) by @ubkp -[rcore][SDL][rlgl] REVIEWED: Fix for running gles2 with SDL on desktop (#3542) by @_Tradam -[rcore][Android] REVIEWED: Issue with isGpuReady flag (#4340) by @Menno van der Graaf -[rcore][Android] REVIEWED: Allow main() to return it its caller on configuration changes (#4288) by @Hesham Abourgheba -[rcore][Android] REVIEWED: Replace deprecated Android function ALooper_pollAll with ALooper_pollOnce (#4275) by @Menno van der Graaf -[rcore][Android] REVIEWED: `PollInputEvents()`, register previous gamepad events (#3910) by @Aria -[rcore][Android] REVIEWED: Fix Android keycode translation and duplicate key constants (#3733) by @Alexandre Almeida -[rcore][DRM] ADDED: uConsole keys mapping (#4297) by @carverdamien -[rcore][DRM] ADDED: `GetMonitorWidth/Height()` (#3956) by @gabriel-marques -[rcore][DRM] REVIEWED: `IsMouseButtonUp()` (#3611) by @ubkp -[rcore][DRM] REVIEWED: Optimize gesture handling (#3616) by @ubkp -[rcore][DRM] REVIEWED: `IsKeyPressedRepeat()` for PLATFORM_DRM direct input (#3583) by @ubkp -[rcore][DRM] REVIEWED: Fix gamepad buttons not working in drm backend (#3888) by @MrMugame -[rcore][DRM] REVIEWED: DRM backend to only use one api to allow for more devices (#3879) by @MrMugame -[rcore][DRM] REVIEWED: Avoid separate thread when polling for gamepad events (#3641) by @Cinghy Creations -[rcore][DRM] REVIEWED: Connector status reported as UNKNOWN but should be considered as CONNECTED (#4305) by @Michał Jaskólski -[rcore][RGFW] ADDED: RGFW, new rcore backend platform (#3941) by @Colleague Riley -[rcore][RGFW] REVIEWED: RGFW 1.0 (#4144) by @Colleague Riley -[rcore][RGFW] REVIEWED: Fix errors when compiling with mingw (#4282) by @Colleague Riley -[rcore][RGFW] REVIEWED: Replace long switch with a lookup table (#4108) by @Colleague Riley -[rcore][RGFW] REVIEWED: Fix MSVC build errors (#4441) by @Colleague Riley -[rlgl] ADDED: More uniform data type options #4137 by @Ray -[rlgl] ADDED: Vertex normals for RLGL immediate drawing mode (#3866) by @bohonghuang -WARNING- -[rlgl] ADDED: `rlCullDistance*()` variables and getters (#3912) by @KotzaBoss -[rlgl] ADDED: `rlSetClipPlanes()` function (#3912) by @KotzaBoss -[rlgl] ADDED: `isGpuReady` flag, allow font loading with no GPU acceleration by @Ray -WARNING- -[rlgl] REVIEWED: Changed RLGL_VERSION from 4.5 to 5.0 (#3914) by @Mute -[rlgl] REVIEWED: Shader load failing returns 0, instead of fallback by @Ray -WARNING- -[rlgl] REVIEWED: Standalone mode default flags (#4334) by @Asdqwe -[rlgl] REVIEWED: Fix hardcoded index values in vboID array (#4312) by @Jett -[rlgl] REVIEWED: GLint64 did not exist before OpenGL 3.2 (#4284) by @Tchan0 -[rlgl] REVIEWED: Extra warnings in case OpenGL 4.3 is not enabled (#4202) by @Maxim Knyazkin -[rlgl] REVIEWED: Using GLint64 for glGetBufferParameteri64v() (#4197) by @Randy Palamar -[rlgl] REVIEWED: Replace `glGetInteger64v()` with `glGetBufferParameteri64v()` (#4154) by @Kai Kitagawa-Jones -[rlgl] REVIEWED: `rlMultMatrixf()`, fix matrix multiplication order (#3935) by @bohonghuang -[rlgl] REVIEWED: `rlSetVertexAttribute()`, define last parameter as offset #3800 by @Ray -[rlgl] REVIEWED: `rlDisableVertexAttribute()`, remove redundat calls for SHADER_LOC_VERTEX_COLOR (#3871) by @Kacper Zybała -[rlgl] REVIEWED: `rlLoadTextureCubemap()`, load mipmaps for cubemaps (#4429) by @Nikolas -[rlgl] REVIEWED: `rlLoadFramebuffer()`, parameters not required by @Ray -[rlgl] REVIEWED: `rlSetUniformSampler()` (#3759) by @veins1 -[rlgl] REVIEWED: Renamed near/far variables (#4039) by @jgabaut -[rlgl] REVIEWED: Expose OpenGL symbols (#3588) by @Peter0x44 -[rlgl] REVIEWED: Fix OpenGL 1.1 build issues (#3876) by @Ray -[rlgl] REVIEWED: Fixed compilation for OpenGL ES (#4243) by @Maxim Knyazkin -[rlgl] REVIEWED: rlgl function description and comments by @Ray -[rlgl] REVIEWED: Expose glad functions when building raylib as a shared lib (#3572) by @Peter0x44 -[rlgl] REVIEWED: Fix version info in rlgl.h (#3558) by @Steven Schveighoffer -[rlgl] REVIEWED: Use the vertex color to the base shader in GLSL330 (#4431) by @Jeffery Myers -[rcamera] REVIEWED: Make camera movement independant of framerate (#4247) by @hanaxars -WARNING- -[rcamera] REVIEWED: Updated camera speeds with GetFrameTime() (#4362) by @Anthony Carbajal -[rcamera] REVIEWED: `UpdateCamera()`, added CAMERA_CUSTOM check (#3938) by @Tomas Fabrizio Orsi -[rcamera] REVIEWED: Support mouse/keyboard and gamepad coexistence for input (#3579) by @ubkp -[rcamera] REVIEWED: Cleaned away unused macros(#3762) by @Brian E -[rcamera] REVIEWED: Fix for free camera mode (#3603) by @lesleyrs -[rcamera] REVIEWED: `GetCameraRight()` (#3784) by @Danil -[raymath] ADDED: C++ operator overloads for common math function (#4385) by @Jeffery Myers -WARNING- -[raymath] ADDED: Vector4 math functions and Vector2 variants of some Vector3 functions (#3828) by @Bowserinator -[raymath] REVIEWED: Fix MSVC warnings/errors in C++ (#4125) by @Jeffery Myers -[raymath] REVIEWED: Add extern "C" to raymath header for C++ (#3978) by @Jeffery Myers -[raymath] REVIEWED: `QuaternionFromAxisAngle()`, remove redundant axis length calculation (#3900) by @jtainer -[raymath] REVIEWED: `Vector3Perpendicular()`, avoid implicit conversion from float to double (#3799) by @João Foscarini -[raymath] REVIEWED: `MatrixDecompose()`, incorrect output for certain scale and rotations (#4461) by @waveydave -[raymath] REVIEWED: Small code refactor (#3753) by @Idir Carlos Aliane -[rshapes] ADDED: `CheckCollisionCircleLine()` (#4018) by @kai-z99 -[rshapes] REVIEWED: Multisegment Bezier splines (#3744) by @Santiago Pelufo -[rshapes] REVIEWED: Expose shapes drawing texture and rectangle (#3677) by @Jeffery Myers -[rshapes] REVIEWED: `DrawLine()` #4075 by @Ray -[rshapes] REVIEWED: `DrawPixel()` drawing by @Ray -[rshapes] REVIEWED: `DrawLine()` to avoid pixel rounding issues #3931 by @Ray -[rshapes] REVIEWED: `DrawRectangleLines()`, considering view matrix for lines "alignment" by @Ray -[rshapes] REVIEWED: `DrawRectangleLines()`, pixel offset (#4261) by @RadsammyT -[rshapes] REVIEWED: `DrawRectangleLines()`, pixel offset when scaling (#3884) by @Ray -[rshapes] REVIEWED: `DrawRectangleLinesEx()`, make sure accounts for square tiles (#4382) by @Jojaby -[rshapes] REVIEWED: `Draw*Gradient()` color parameter names (#4270) by @Paperdomo101 -[rshapes] REVIEWED: `DrawGrid()`, remove duplicate color calls (#4148) by @Jeffery Myers -[rshapes] REVIEWED: `DrawSplineLinear()` to `SUPPORT_SPLINE_MITERS` by @Ray -[rshapes] REVIEWED: `DrawSplineLinear()`, implement miters (#3585) by @Toctave -[rshapes] REVIEWED: `CheckCollisionPointRec()` by @Ray -[rshapes] REVIEWED: `CheckCollisionPointCircle()`, new implementation (#4135) by @kai-z99 -[rshapes] REVIEWED: `CheckCollisionCircles()`, optimized (#4065) by @kai-z99 -[rshapes] REVIEWED: `CheckCollisionPointPoly()` (#3750) by @Antonio Raúl -[rshapes] REVIEWED: `CheckCollisionCircleRec()` (#3584) by @ubkp -[rshapes] REVIEWED: Add more detail to function comment (#4344) by @Jeffery Myers -[rshapes] REVIEWED: Functions that draw point arrays take them as const (#4051) by @Jeffery Myers -[rtextures] ADDED: `ColorIsEqual()` by @Ray -[rtextures] ADDED: `ColorLerp()`, to mix 2 colors together (#4310) by @SusgUY446 -[rtextures] ADDED: `LoadImageAnimFromMemory()` (#3681) by @IoIxD -[rtextures] ADDED: `ImageKernelConvolution()` (#3528) by @Karim -[rtextures] ADDED: `ImageFromChannel()` (#4105) by @Bruno Cabral -[rtextures] ADDED: `ImageDrawLineEx()` (#4097) by @Le Juez Victor -[rtextures] ADDED: `ImageDrawTriangle()` (#4094) by @Le Juez Victor -[rtextures] REMOVED: SVG files loading and drawing, moving it to raylib-extras by @Ray -WARNING- -[rtextures] REVIEWED: `LoadImage()`, added support for 3-channel QOI images (#4384) by @R-YaTian -[rtextures] REVIEWED: `LoadImageRaw()` #3926 by @Ray -[rtextures] REVIEWED: `LoadImageColors()`, advance k in loop (#4120) by @Bruno Cabral -[rtextures] REVIEWED: `LoadTextureCubemap()`, added `mipmaps` #3665 by @Ray -[rtextures] REVIEWED: `LoadTextureCubemap()`, assign format to cubemap (#3823) by @Gary M -[rtextures] REVIEWED: `LoadTextureCubemap()`, load mipmaps for cubemaps (#4429) by @Nikolas -[rtextures] REVIEWED: `LoadTextureCubemap()`, avoid dangling re-allocated pointers (#4439) by @Nikolas -[rtextures] REVIEWED: `LoadImageFromScreen()`, fix scaling (#3881) by @proberge-dev -[rtextures] REVIEWED: `LoadImageFromMemory()`, warnings on invalid image data (#4179) by @Jutastre -[rtextures] REVIEWED: `LoadImageAnimFromMemory()`, added security checks (#3924) by @Ray -[rtextures] REVIEWED: `ImageColorTint()` and `ColorTint()`, optimized (#4015) by @Le Juez Victor -[rtextures] REVIEWED: `ImageKernelConvolution()`, formating and warnings by @Ray -[rtextures] REVIEWED: `ImageDrawRectangleRec`, fix bounds check (#3732) by @Blockguy24 -[rtextures] REVIEWED: `ImageResizeCanvas()`, implemented fill color (#3720) by @Lieven Petersen -[rtextures] REVIEWED: `ImageDrawRectangleRec()` (#3721) by @Le Juez Victor -[rtextures] REVIEWED: `ImageDraw()`, don't try to blend images without alpha (#4395) by @Nikolas -[rtextures] REVIEWED: `GenImagePerlinNoise()` being stretched (#4276) by @Bugsia -[rtextures] REVIEWED: `GenImageGradientLinear()`, fix some angles (#4462) by @decromo -[rtextures] REVIEWED: `DrawTexturePro()` to avoid negative dest rec #4316 by @Ray -[rtextures] REVIEWED: `ColorToInt()`, fix undefined behaviour (#3996) by @OetkenPurveyorOfCode -[rtextures] REVIEWED: Remove panorama cubemap layout option (#4425) by @Jeffery Myers -[rtextures] REVIEWED: Removed unneeded module check, `rtextures` should not depend on `rtext` by @Ray -[rtextures] REVIEWED: Simplified for loop for some image manipulation functions (#3712) by @Alice Nyaa -[rtext] ADDED: BDF fonts support (#3735) by @Stanley Fuller -WARNING- -[rtext] ADDED: `TextToCamel()` (#4033) by @IoIxD -[rtext] ADDED: `TextToSnake()` (#4033) by @IoIxD -[rtext] ADDED: `TextToFloat()` (#3627) by @Benjamin Schmid Ties -[rtext] REDESIGNED: `SetTextLineSpacing()` by @Ray -WARNING- -[rtext] REVIEWED: `LoadFontDataBDF()` name and formating by @Ray -[rtext] REVIEWED: `LoadFontDefault()`, initialize glyphs and recs to zero #4319 by @Ray -[rtext] REVIEWED: `LoadFontEx()`, avoid default font fallback (#4077) by @Peter0x44 -WARNING- -[rtext] REVIEWED: `LoadBMFont()`, extended functionality (#3536) by @Dongkun Lee -[rtext] REVIEWED: `LoadBMFont()`, issue on not glyph data initialized by @Ray -[rtext] REVIEWED: `LoadFontFromMemory()`, use strncpy() to fix buffer overflow (#3795) by @Mingjie Shen -[rtext] REVIEWED: `LoadCodepoints()` returning a freed ptr when count is 0 (#4089) by @Alice Nyaa -[rtext] REVIEWED: `LoadFontData()` avoid fallback glyphs by @Ray -WARNING- -[rtext] REVIEWED: `LoadFontData()`, load image only if glyph has been found in font by @Ray -[rtext] REVIEWED: `ExportFontAsCode()`, fix C++ compiler errors (#4013) by @DarkAssassin23 -[rtext] REVIEWED: `MeasureTextEx()` height calculation (#3770) by @Marrony Neris -[rtext] REVIEWED: `MeasureTextEx()`, additional check for empty input string (#4448) by @mpv-enjoyer -[rtext] REVIEWED: `CodepointToUTF8()`, clean static buffer #4379 by @Ray -[rtext] REVIEWED: `TextToFloat()`, always multiply by sign (#4273) by @listeria -[rtext] REVIEWED: `TextReplace()` const correctness (#3678) by @maverikou -[rtext] REVIEWED: `TextToFloat()`, coding style (#3627) by @Benjamin Schmid Ties -[rtext] REVIEWED: Some comments to align to style (#3756) by @Idir Carlos Aliane -[rtext] REVIEWED: Adjust font atlas area calculation so padding area is not underestimated at small font sizes (#3719) by @Tim Romero -[rmodels] ADDED: GPU skinning support for models animations (#4321) by @Daniel Holden -WARNING- -[rmodels] ADDED: Support 16-bit unsigned short vec4 format for gltf joint loading (#3821) by @Gary M -[rmodels] ADDED: Support animation names for the m3d model format (#3714) by @kolunmi -[rmodels] ADDED: `DrawModelPoints()`, more performant point cloud rendering (#4203) by @Reese Gallagher -[rmodels] ADDED: `ExportMeshAsCode()` by @Ray -[rmodels] REVIEWED: Multiple updates to gltf loading, improved macro (#4373) by @Harald Scheirich -[rmodels] REVIEWED: `LoadOBJ()`, correctly split obj meshes by material (#4285) by @Jeffery Myers -[rmodels] REVIEWED: `LoadOBJ()`, add warning when loading an OBJ with multiple materials (#4271) by @Jeffery Myers -[rmodels] REVIEWED: `LoadOBJ()`, fix bug that fragmented the loaded meshes (#4494) by @Eike Decker -[rmodels] REVIEWED: `LoadIQM()`, set model.meshMaterial[] (#4092) by @SuperUserNameMan -[rmodels] REVIEWED: `LoadIQM()`, attempt to load texture from IQM at loadtime (#4029) by @Jett -[rmodels] REVIEWED: `LoadM3D(), fix vertex colors for m3d files (#3859) by @Jeffery Myers -[rmodels] REVIEWED: `LoadGLTF()`, supporting additional vertex data formats (#3546) by @MrScautHD -[rmodels] REVIEWED: `LoadGLTF()`, correctly handle the node hierarchy in a glTF file (#4037) by @Paul Melis -[rmodels] REVIEWED: `LoadGLTF()`, replaced SQUAD quat interpolation with cubic hermite (gltf 2.0 specs) (#3920) by @Benji -[rmodels] REVIEWED: `LoadGLTF()`, support 2nd texture coordinates loading by @Ray -[rmodels] REVIEWED: `LoadGLTF()`, support additional vertex attributes data formats #3890 by @Ray -[rmodels] REVIEWED: `LoadGLTF()`, set cgltf callbacks to use `LoadFileData()` and `UnloadFileData()` (#3652) by @kolunmi -[rmodels] REVIEWED: `LoadGLTF()`, JOINTS loading #3836 by @Ray -[rmodels] REVIEWED: `LoadImageFromCgltfImage()`, fix base64 padding support (#4112) by @SuperUserNameMan -[rmodels] REVIEWED: `LoadModelAnimationsIQM()`, fix corrupted animation names (#4026) by @Jett -[rmodels] REVIEWED: `LoadModelAnimationsGLTF()`, load animations with 1 frame (#3804) by @Nikita Blizniuk -[rmodels] REVIEWED: `LoadModelAnimationsGLTF()`, added missing interpolation types (#3919) by @Benji -[rmodels] REVIEWED: `LoadModelAnimationsGLTF()` (#4107) by @VitoTringolo -[rmodels] REVIEWED: `LoadBoneInfoGLTF()`, add check for animation name being NULL (#4053) by @VitoTringolo -[rmodels] REVIEWED: `GenMeshSphere()`, fix artifacts (#4460) by @MikiZX1 -[rmodels] REVIEWED: `GenMeshTangents()`, read uninitialized values, fix bounding case (#4066) by @kai-z99 -[rmodels] REVIEWED: `GenMeshTangents()`, fixed out of bounds error (#3990) by @Salvador Galindo -[rmodels] REVIEWED: `UpdateModelAnimation()`, performance speedup (#4470) by @JettMonstersGoBoom -[rmodels] REVIEWED: `DrawCylinder()`, fix drawing due to imprecise angle (#4034) by @Paul Melis -[rmodels] REVIEWED: `DrawCylinder()`, fix drawing of cap (#4478) by @JeffM2501 -[rmodels] REVIEWED: `DrawMesh()`, send full matModel to shader in DrawMesh (#4005) (#4022) by @David Holland -[rmodels] REVIEWED: `DrawMesh()`, fix material specular map retrieval (#3758) by @Victor Gallet -[rmodels] REVIEWED: `DrawModelEx()`, simplified multiplication of colors (#4002) by @Le Juez Victor -[rmodels] REVIEWED: `DrawBillboardPro()`, to be consistend with `DrawTexturePro()` (#4132) by @bohonghuang -[rmodels] REVIEWED: `DrawSphereEx()` optimization (#4106) by @smalltimewizard -[raudio] REVIEWED: `LoadMusicStreamFromMemory()`, support 24-bit FLACs (#4279) by @konstruktor227 -[raudio] REVIEWED: `LoadWaveSamples()`, fix mapping of wave data (#4062) by @listeria -[raudio] REVIEWED: `LoadMusicStream()`, remove drwav_uninit() (#3986) by @FishingHacks -[raudio] REVIEWED: `LoadMusicStream()` qoa and wav loading (#3966) by @veins1 -[raudio] REVIEWED: `ExportWaveAsCode()`, segfault (#3769) by @IoIxD -[raudio] REVIEWED: `WaveCrop()`, fix issues and use frames instead of samples (#3994) by @listeria -[raudio] REVIEWED: Crash from multithreading issues (#3907) by @Christian Haas -[raudio] REVIEWED: Reset music.ctxType if loading wasn't succesful (#3917) by @veins1 -[raudio] REVIEWED: Added missing functions in "standalone" mode (#3760) by @Alessandro Nikolaev -[raudio] REVIEWED: Disable unused miniaudio features (#3544) by @Alexandre Almeida -[raudio] REVIEWED: Fix crash when switching playback device at runtime (#4102) by @jkaup -[raudio] REVIEWED: Support 24 bits samples for FLAC format (#4058) by @Alexey Kutepov -[examples] ADDED: `core_random_sequence` (#3846) by @Dalton Overmyer -[examples] ADDED: `core_input_virtual_controls` (#4342) by @oblerion -[examples] ADDED: `shapes_rectangle_advanced `, implementing `DrawRectangleRoundedGradientH()` (#4435) by @Everton Jr. -[examples] ADDED: `models_bone_socket` (#3833) by @iP -[examples] ADDED: `shaders_vertex_displacement` (#4186) by @Alex ZH -[examples] ADDED: `shaders_shadowmap` (#3653) by @TheManTheMythTheGameDev -[examples] REVIEWED: `core_2d_camera_platformer` by @Ray -[examples] REVIEWED: `core_2d_camera_mouse_zoom`, use logarithmic scaling for a 2d zoom functionality (#3977) by @Mike Will -[examples] REVIEWED: `core_input_gamepad_info`, all buttons displayed within the window (#4241) by @Asdqwe -[examples] REVIEWED: `core_input_gamepad_info`, show ps3 controller (#4040) by @Konrad Gutvik Grande -[examples] REVIEWED: `core_input_gamepad`, add drawing for generic gamepad (#4424) by @Asdqwe -[examples] REVIEWED: `core_input_gamepad`, add deadzone handling (#4422) by @Asdqwe -[examples] REVIEWED: `shapes_bouncing_ball` (#4226) by @Anthony Carbajal -[examples] REVIEWED: `shapes_following_eyes` (#3710) by @Hongyu Ouyang -[examples] REVIEWED: `shapes_draw_rectangle_rounded` by @Ray -[examples] REVIEWED: `shapes_draw_ring`, fix other examples (#4211) by @kai-z99 -[examples] REVIEWED: `shapes_lines_bezier` by @Ray -[examples] REVIEWED: `textures_image_kernel` #3556 by @Ray -[examples] REVIEWED: `text_input_box` (#4229) by @Anthony Carbajal -[examples] REVIEWED: `text_writing_anim` (#4230) by @Anthony Carbajal -[examples] REVIEWED: `models_billboard` by @Ray -[examples] REVIEWED: `models_cubicmap` by @Ray -[examples] REVIEWED: `models_point_rendering` by @Ray -[examples] REVIEWED: `models_box_collisions` (#4224) by @Anthony Carbajal -[examples] REVIEWED: `models_skybox`, do not use HDR by default (#4115) by @Jeffery Myers -[examples] REVIEWED: `shaders_basic_pbr` (#4225) by @Anthony Carbajal -[examples] REVIEWED: `shaders_palette_switch` by @Ray -[examples] REVIEWED: `shaders_hybrid_render` (#3908) by @Yousif -[examples] REVIEWED: `shaders_lighting_instancing`, fix vertex shader (#4056) by @Karl Zylinski -[examples] REVIEWED: `shaders_raymarching`, add `raymarching.fs` for GLSL120 (#4183) by @CDM15y -[examples] REVIEWED: `shaders_shadowmap`, fix shaders for GLSL 1.20 (#4167) by @CDM15y -[examples] REVIEWED: `shaders_deferred_render` (#3655) by @Jett -[examples] REVIEWED: `shaders_basic_pbr` (#3621) by @devdad -[examples] REVIEWED: `shaders_basic_pbr`, remove dependencies (#3649) by @TheManTheMythTheGameDev -[examples] REVIEWED: `shaders_basic_pbr`, added more comments by @Ray -[examples] REVIEWED: `shaders_gpu_skinning`, to work with OpenGL ES 2.0 #4412 by @Ray -[examples] REVIEWED: `shaders_model_shader`, use free camera (#4428) by @IcyLeave6109 -[examples] REVIEWED: `audio_stream_effects` (#3618) by @lipx -[examples] REVIEWED: `audio_raw_stream` (#3624) by @riadbettole -[examples] REVIEWED: `audio_mixed_processor` (#4214) by @Anthony Carbajal -[examples] REVIEWED: `raylib_opengl_interop`, fix building on PLATFORM_DESKTOP_SDL (#3826) by @Peter0x44 -[examples] REVIEWED: Update examples missing UnloadTexture() calls (#4234) by @Anthony Carbajal -[examples] REVIEWED: Added GLSL 100 and 120 shaders to lightmap example (#3543) by @Jussi Viitala -[examples] REVIEWED: Set FPS to always 60 in all exampels (#4235) by @Anthony Carbajal -[build] REVIEWED: Makefile by @Ray -[build] REVIEWED: Makefile, fix wrong flag #3593 by @Ray -[build] REVIEWED: Makefile, disable wayland by default (#4369) by @Anthony Carbajal -[build] REVIEWED: Makefile, VSCode, fix to support multiple .c files (#4391) by @Alan Arrecis -[build] REVIEWED: Makefile, fix -Wstringop-truncation warning (#4096) by @Peter0x44 -[build] REVIEWED: Makefile, fix issues for RGFW on Linux/macOS (#3969) by @Colleague Riley -[build] REVIEWED: Makefile, update RAYLIB_VERSION (#3901) by @Belllg -[build] REVIEWED: Makefile, use mingw32-make for Windows (#4436) by @Asdqwe -[build] REVIEWED: Makefile, move CUSTOM_CFLAGS for better visibility (#4054) by @Lázaro Albuquerque -[build] REVIEWED: Makefile, update emsdk paths to latest versions by @Ray -[build] REVIEWED: Makefile examples, align /usr/local with /src Makefile (#4286) by @Tchan0 -[build] REVIEWED: Makefile examples, added `textures_image_kernel` (#3555) by @Sergey Zapunidi -[build] REVIEWED: Makefile examples (#4209) by @Anthony Carbajal -[build] REVIEWED: Makefile examples, to work on NetBSD (#4438) by @NishiOwO -[build] REVIEWED: Makefile examples, WebGL2 (OpenGL ES 3.0) backend flags #4330 by @Ray -[build] REVIEWED: Makefile examples, web building (#4434) by @Asdqwe -[build] REVIEWED: build.zig, fix various issues around `-Dconfig` (#4398) by @Sage Hane -[build] REVIEWED: build.zig, fix type mismatch (#4383) by @yuval_dev -[build] REVIEWED: build.zig, minor fixes (#4381) by @Sage Hane -[build] REVIEWED: build.zig, fix @src logic and a few things (#4380) by @Sage Hane -[build] REVIEWED: build.zig, improve logic (#4375) by @Sage Hane -[build] REVIEWED: build.zig, issues (#4374) by @William Culver -[build] REVIEWED: build.zig, issues (#4366) by @Visen -[build] REVIEWED: build.zig, support desktop backend change (#4358) by @Nikolas -[build] REVIEWED: build.zig, use zig fmt (#4242) by @freakmangd -[build] REVIEWED: build.zig, check if wayland-scanner is installed (#4217) by @lnc3l0t -[build] REVIEWED: build.zig, override config.h definitions (#4193) by @lnc3l0t -[build] REVIEWED: build.zig, support GLFW platform detection (#4150) by @InventorXtreme -[build] REVIEWED: build.zig, make emscripten build compatible with Zig 0.13.0 (#4121) by @Mike Will -[build] REVIEWED: build.zig, pass the real build.zig file (#4113) by @InKryption -[build] REVIEWED: build.zig, leverage `dependencyFromBuildZig` (#4109) by @InKryption -[build] REVIEWED: build.zig, run examples from their directories (#4063) by @Mike Will -[build] REVIEWED: build.zig, fix raygui build when using addRaygui externally (#4027) by @Viktor Pocedulić -[build] REVIEWED: build.zig, fix emscripten build (#4012) by @Dylan -[build] REVIEWED: build.zig, update to zig 0.12.0dev while keeping 0.11.0 compatibility (#3715) by @freakmangd -[build] REVIEWED: build.zig, drop support for 0.11.0 and use more idiomatic build script code (#3927) by @freakmangd -[build] REVIEWED: build.zig, sdd shared library build option and update to zig 0.12.0-dev.2139 (#3727) by @Andrew Lee -[build] REVIEWED: build.zig, add `opengl_version` option (#3979) by @Alexei Mozaidze -[build] REVIEWED: build.zig, fix local dependency break (#3913) by @freakmangd -[build] REVIEWED: build.zig, fix breaking builds for Zig v0.11.0 (#3896) by @iarkn -[build] REVIEWED: build.zig, update to latest version and simplify (#3905) by @freakmangd -[build] REVIEWED: build.zig, remove all uses of deps/mingw (#3805) by @Peter0x44 -[build] REVIEWED: build.zig, fixed illegal instruction crash (#3682) by @WisonYe -[build] REVIEWED: build.zig, fix broken build on #3863 (#3891) by @Nikolas Mauropoulos -[build] REVIEWED: build.zig, improve cross-compilation (#4468) by @deathbeam -[build] REVIEWED: CMake, update to raylib 5.0 (#3623) by @Peter0x44 -[build] REVIEWED: CMake, added PLATFORM option for Desktop SDL (#3809) by @mooff -[build] REVIEWED: CMake, fix GRAPHICS_* check (#4359) by @Kacper Zybała -[build] REVIEWED: CMake, examples projects (#4332) by @Ridge3Dproductions -[build] REVIEWED: CMake, fix warnings in projects/CMake/CMakeLists.txt (#4278) by @Peter0x44 -[build] REVIEWED: CMake, delete BuildOptions.cmake (#4277) by @Peter0x44 -[build] REVIEWED: CMake, update version to 5.0 so libraries are correctly versioned (#3615) by @David Williams -[build] REVIEWED: CMake, improved linkage flags to save 28KB on the final bundle (#4177) by @Lázaro Albuquerque -[build] REVIEWED: CMake, support OpenGL ES3 in `LibraryConfigurations.cmake` (#4079) by @manuel5975p -[build] REVIEWED: CMake, `config.h` fully available to users (#4044) by @Lázaro Albuquerque -[build] REVIEWED: CMake, pass -sFULL_ES3 instead of -sFULL_ES3=1 (#4090) by @manuel5975p -[build] REVIEWED: CMake, SDL build link the glfw dependency (#3860) by @Rob Loach -[build] REVIEWED: CMake, infer CMAKE_MODULE_PATH in super-build (#4042) by @fruzitent -[build] REVIEWED: CMake, remove USE_WAYLAND option (#3851) by @Alexandre Almeida -[build] REVIEWED: CMake, disable SDL rlgl_standalone example (#3861) by @Rob Loach -[build] REVIEWED: CMake, bump version required to avoid deprecated #3639 by @Ray -[build] REVIEWED: CMake, fix examples linking -DPLATFORM=SDL (#3825) by @Peter0x44 -[build] REVIEWED: CMake, don't build for wayland by default (#4432) by @Peter0x44 -[build] REVIEWED: VS2022, misc improvements by @Ray -[build] REVIEWED: VS2022, fix build warnings (#4095) by @Jeffery Myers -[build] REVIEWED: VS2022, added new examples (#4492) by @Jeffery Myers -[build] REVIEWED: Fix fix-build-paths (#3849) by @Caleb Barger -[build] REVIEWED: Fix build paths (#3835) by @Steve Biedermann -[build] REVIEWED: Fix VSCode sample project for macOS (#3666) by @Tim Romero -[build] REVIEWED: Fix some warnings on web builds and remove some redundant flags (#4069) by @Lázaro Albuquerque -[build] REVIEWED: Fix examples not building with gestures system disabled (#4020) by @Sprix -[build] REVIEWED: Fix GLFW runtime platform detection (#3863) by @Alexandre Almeida -[build] REVIEWED: Fix DRM cross-compile without sysroot (#3839) by @Christian W. Zuckschwerdt -[build] REVIEWED: Fix cmake-built libraylib.a to properly include GLFW's object files (#3598) by @Peter0x44 -[build] REVIEWED: Hide unneeded internal symbols when building raylib as an so or dylib (#3573) by @Peter0x44 -[build] REVIEWED: Corrected the path of android ndk toolchains for OSX platforms (#3574) by @Emmanuel Méra -[build][CI] ADDED: Automatic update for raylib_api.* (#3692) by @seiren -[build][CI] REVIEWED: Update workflows to use latest actions/upload-artifact by @Ray -[build][CI] REVIEWED: CodeQL minor tweaks to avoid some warnings by @Ray -[build][CI] REVIEWED: Update linux_examples.yml by @Ray -[build][CI] REVIEWED: Update linux.yml by @Ray -[build][CI] REVIEWED: Update webassembly.yml by @Ray -[build][CI] REVIEWED: Update cmake.yml by @Ray -[build][CI] REVIEWED: Update codeql.yml, exclude src/external files by @Ray -[bindings] ADDED: raylib-APL (#4253) by @Brian E -[bindings] ADDED: raylib-bqn, moved rayed-bqn (#4331) by @Brian E -[bindings] ADDED: brainfuck binding (#4169) by @_Tradam -[bindings] ADDED: raylib-zig-bindings (#4004) by @Lionel Briand -[bindings] ADDED: Raylib-CSharp wrapper (#3963) by @MrScautHD -[bindings] ADDED: COBOL binding (#3661) by @glowiak -[bindings] ADDED: raylib-beef binding (#3640) by @Braedon Lewis -[bindings] ADDED: Raylib-CSharp-Vinculum (#3571) by @Danil -[bindings] REVIEWED: Remove broken-link bindings #3899 by @Ray -[bindings] REVIEWED: Updated some versions on BINDINGS.md by @Ray -[bindings] REVIEWED: Removed umaintained repos (#3999) by @Antonis Geralis -[bindings] REDESIGNED: Add binding link to name, instead of separate column (#3995) by @Carmine Pietroluongo -[bindings] UPDATED: h-raylib (#4378) by @Anand Swaroop -[bindings] UPDATED: Raylib.lean, to master version (#4337) by @Daniil Kisel -[bindings] UPDATED: raybit, to latest master (#4311) by @Alex -[bindings] UPDATED: dray binding (#4163) by @red thing -[bindings] UPDATED: Julia (#4068) by @ShalokShalom -[bindings] UPDATED: nim to latest master (#3999) by @Antonis Geralis -[bindings] UPDATED: raylib-rs (#3991) by @IoIxD -[bindings] UPDATED: raylib-zig version (#3902) by @Nikolas -[bindings] UPDATED: raylib-odin (#3868) by @joyousblunder -[bindings] UPDATED: Raylib VAPI (#3829) by @Alex Macafee -[bindings] UPDATED: Raylib-cs (#3774) by @Brandon Baker -[bindings] UPDATED: h-raylib (#3739) by @Anand Swaroop -[bindings] UPDATED: OCaml bindings version (#3730) by @Tobias Mock -[bindings] UPDATED: Raylib.c3 (#3689) by @Kenta -[bindings] UPDATED: ray-cyber to 5.0 (#3654) by @fubark -[bindings] UPDATED: raylib-freebasic binding (#3591) by @WIITD -[bindings] UPDATED: SmallBASIC (#3562) by @Chris Warren-Smith -[bindings] UPDATED: Python raylib-py v5.0.0beta1 (#3557) by @Jorge A. Gomes -[bindings] UPDATED: raylib-d binding (#3561) by @Steven Schveighoffer -[bindings] UPDATED: Janet (#3553) by @Dmitry Matveyev -[bindings] UPDATED: Raylib.nelua (#3552) by @Auz -[bindings] UPDATED: raylib-cpp to 5.0 (#3551) by @Rob Loach -[bindings] UPDATED: Pascal binding (#3548) by @Gunko Vadim -[external] UPDATED: stb_truetype.h to latest version by @Ray -[external] UPDATED: stb_image_resize2.h to latest version by @Ray -[external] UPDATED: stb_image.h to latest version by @Ray -[external] UPDATED: qoa.h to latest version by @Ray -[external] UPDATED: dr_wav.h to latest version by @Ray -[external] UPDATED: dr_mp3.h to latest version by @Ray -[external] UPDATED: cgltf.h to latest version by @Ray -[external] REVIEWED: rl_gputex, correctly load mipmaps from DDS files (#4399) by @Nikolas -[external] REVIEWED: stb_image_resize2, dix vld1q_f16 undeclared in arm (#4309) by @masnm -[external] REVIEWED: miniaudio, fix library and Makefile for NetBSD (#4212) by @NishiOwO -[external] REVIEWED: raygui, update to latest version 4.5-dev (#4238) by @Anthony Carbajal -[external] REVIEWED: jar_xml, replace unicode characters by ascii characters to avoid warning in MSVC (#4196) by @Rico P -[external] REVIEWED: vox_loader, normals and new voxels shader (#3843) by @johann nadalutti -[parser] REVIEWED: README.md, to mirror fixed help text (#4336) by @Daniil Kisel -[parser] REVIEWED: Fix seg fault with long comment lines (#4306) by @Chris Warren-Smith -[parser] REVIEWED: Don't crash for files that don't end in newlines (#3981) by @Peter0x44 -[parser] REVIEWED: Issues in usage example help text (#4084) by @Peter0x44 -[parser] REVIEWED: Fix parsing of empty parentheses (#3974) by @Filyus -[parser] REVIEWED: Address parsing issue when generating XML #3893 by @Ray -[parser] REVIEWED: `MemoryCopy()`, prevent buffer overflow by replacing hard-coded arguments (#4011) by @avx0 -[misc] ADDED: Create logo/raylib.icns by @Ray -[misc] ADDED: Create logo/raylib_1024x1024.png by @Ray -[misc] ADDED: Default vertex/fragment shader for OpenGL ES 3.0 (#4178) by @Lázaro Albuquerque -[misc] REVIEWED: README.md, fix Reddit badge (#4136) by @Ninad Sachania -[misc] REVIEWED: .gitignore, ignore compiled dll binaries (#3628) by @2Bear -[misc] REVIEWED: Fix undesired scrollbars on web shell files (#4104) by @jspast -[misc] REVIEWED: Made comments on raylib.h match comments in rcamera.h (#3942) by @Tomas Fabrizio Orsi -[misc] REVIEWED: Make raylib/raygui work better on touchscreen (#3728) by @Hongyu Ouyang -[misc] REVIEWED: Update config.h by @Ray - -------------------------------------------------------------------------- -Release: raylib 5.0 - 10th Anniversary Edition (18 November 2023) -------------------------------------------------------------------------- -KEY CHANGES: - - REDESIGNED: rcore module platform-split, by @ubkp, @michaelfiber, @Bigfoot71, @raysan5 - - ADDED: New platform backend supported: SDL - - ADDED: New platform backend supported: Nintendo Switch (closed source) - - ADDED: New Splines drawing and evaluation API - - ADDED: New pseudo-random numbers generator: rprand - - ADDED: Automation Events System API - - UPDATED: raygui 4.0: New version of this immediate-mode gui system for tools development with raylib - -Detailed changes: -[rcore] ADDED: RAYLIB_VERSION_* values to raylib.h (#2856) by @RobLoach -[rcore] ADDED: IsKeyPressedRepeat() on PLATFORM_DESKTOP (#3245) by @actondev -[rcore] ADDED: SetWindowTitle() for PLATFORM_WEB (#3222) by @VitusVeit -[rcore] ADDED: FLAG_WINDOW_RESIZABLE for web (#3305) by @Peter0x44 -[rcore] ADDED: SetWindowMaxSize() for desktop and web (#3309) by @ubkp -[rcore] ADDED: SetMouseCursor() for PLATFORM_WEB (#3414) by @BeardedBread -[rcore] ADDED: LoadRandomSequence()/UnloadRandomSequence() by @raysan5 -[rcore] REMOVED: PLATFORM_RPI (#3232) by @michaelfiber -[rcore] REVIEWED: GetFileLength(), added comment (#3262) by @raysan5 -[rcore] REVIEWED: Default shaders precission issue on PLATFORM_WEB (#3261) by @branc116 -[rcore] REVIEWED: IsKey*() key validation checks (#3256) by @n77y -[rcore] REVIEWED: SetClipboardText() for PLATFORM_WEB (#3257) by @ubkp -[rcore] REVIEWED: Check if Ctrl modifier is among the currently set modifiers (#3230) by @mohad12211 -[rcore] REVIEWED: Android app black screen when reopening by @Bigfoot71 -[rcore] REVIEWED: Warnings when casting int to floats (#3218) by @JeffM2501 -[rcore] REVIEWED: GetCurrentMonitor() detection inconsistency issue (#3215) by @ubkp -[rcore] REVIEWED: SetWindowMonitor() to no longer force fullscreen (#3209) by @ubkp -[rcore] REVIEWED: Fix mouse wheel not working in PLATFORM_RPI or PLATFORM_DRM (#3193) by @ubkp -[rcore] REVIEWED: GetMonitorName() description (#3184) (#3189) by @danilwhale -[rcore] REVIEWED: BeginScissorMode(), identify rendering to texture (#3510) by @gulrak -[rcore] REVIEWED: Window flags order (#3114) by @lesleyrs -[rcore] REVIEWED: Full movement for right analog stick (#3095) by @PixelPhobicGames -[rcore] REVIEWED: Fix Android app freeze after calling CloseWindow() (#3067) by @Bigfoot71 -[rcore] REVIEWED: Lazy loading of default font used on image drawing (no InitWindow) by @raysan5 -[rcore] REVIEWED: Minor tweaks to raylib events automation system @raysan5 -[rcore] REVIEWED: GetCurrentMonitor() bugfix (#3058) by @hamyyy -[rcore] REVIEWED: Update CORE.Input.Touch.pointCount (#3024) by @raysan5 -[rcore] REVIEWED: Mouse offset and scaling must be considered also on web! -[rcore] REVIEWED: CompressData(), possible stack overflow -[rcore] REVIEWED: GetWorldToScreenEx() (#3351) by @Brian-ED -[rcore] REVIEWED: Fix GetMouseDelta() issue for Android (#3404) by @Bigfoot71 -[rcore] REVIEWED: GetFPS(), reset FPS averages when window is inited (#3445) by @JeffM2501 -[rcore] REVIEWED: GetCurrentMonitor(), check window center position by @M374LX -[rcore] REVIEWED: GetRender*() issue on macOS highDPI (#3367) by @raysan5 -[rcore] REVIEWED: ScanDirectoryFiles*(), paths building slashes sides (#3507) -[rlgl] ADDED: Experimental support for OpenGL ES 3.0 by @raysan5 -[rlgl] ADDED: Support 16-Bit HDR textures (#3220) by @Not-Nik -[rlgl] ADDED: rlEnablePointMode() (#3490) by @JettMonstersGoBoom -[rlgl] ADDED: rlBlitFramebuffer(), required for deferred render -[rlgl] REVIEWED: LoadModel(), removed cube fallback mechanism (#3459) -[rlgl] REVIEWED: Improved support for ES3/WebGL2 (#3107) by @chemaguerra -[rlgl] REVIEWED: OpenGL 2.1 half floats support as part of an extension by @Not-Nik -[rlgl] REVIEWED: Avoid shader attribute not found log by @raysan5 -[rlgl] REVIEWED: Avoid tracelog about not found uniforms (#3003) by @raysan5 -[rlgl] REVIEWED: rLoadTexture() UBSAN complaints #1891 (#3321) by @Codom -[rlgl] REVIEWED: glInternalFormat as unsigned int -[rlgl] REVIEWED: OpenGL ES 3.0 support -[rshapes] ADDED: Spline drawing functions by @raysan5 -[rshapes] ADDED: GetSplinePoint*() functions for spline evaluation by @raysan5 -[rshapes] ADDED: DrawCircleLinesV() for consistency (#3452) by @Peter0x44 -[rshapes] REVIEWED: DrawSplineCatmullRom() by @raysan5 -[rshapes] REVIEWED: Minor fix in DrawLineBezier* (#3006) by @eternalStudent -[rshapes] REVIEWED: GetCollisionRec(), more performant (#3052) by @manuel5975p -[rshapes] REVIEWED: Fix off-by-one error in CheckCollisionPointRec() (#3022) by @dbechrd -[rtextures] ADDED: Basic SVG loading support (#2738) by @bXi -[rtextures] ADDED: Support 16-Bit HDR textures (#3220) by @Not-Nik -[rtextures] ADDED: ExportImageToMemory() by @raysan5 -[rtextures] ADDED: ImageRotate() (#3078) by @danemadsen -[rtextures] ADDED: GenImageGradientSquare() (#3077) by @danemadsen -[rtextures] ADDED: GenImageLinearGradient() by @danemadsen -[rtextures] REMOVED: GenImageGradientH() and GenImageGradientV() by @danemadsen -[rtextures] REVIEWED: LoadImageSvg() by @raysan5 -[rtextures] REVIEWED: Uninitialized thread-locals in stbi (#3282) (#3283) by @jbarthelmes -[rtextures] REVIEWED: ImageDrawRectangleRec(), validate drawing inside bounds by @JeffM2501 -[rtextures] REVIEWED: LoadTextureCubemap() for manual layouts (#3204) by @Not-Nik -[rtextures] REVIEWED: Optimization of ImageDrawRectangleRec() (#3185) by @smalltimewizard -[rtextures] REVIEWED: ImageRotate() formatting by @raysan5 -[rtextures] REVIEWED: GenImagePerlinNoise(), clamp values (#3071) by @raysan5 -[rtextures] REVIEWED: Packing logic error in GenImageFontAtlas() (#2979) by @hanaxar -[rtextures] REVIEWED: Calculate exact image size in GenImageFontAtlas() (#2963) by @hanaxar -[rtextures] REVIEWED: ImageDrawRectangleRec() (#3027) by @raysan5 -[rtextures] REVIEWED: ImageDraw() source clipping when drawing beyond top left (#3306) by @RobLoach -[rtextures] REVIEWED: UnloadRenderTexture(), additional checks -[rtextures] REVIEWED: Fixed compressed DDS texture loading issues (#3483) by @JaanDev -[rtext] ADDED: Font altas white rectangle and flag SUPPORT_FONT_ATLAS_WHITE_REC by @raysan5 -[rtext] ADDED: SetTextLineSpacing() to define line breaks text drawing spacing by @raysan5 -[rtext] RENAMED: LoadFont*() parameter names for consistency and coherence by @raysan5 -[rtext] REVIEWED: GetCodepointCount(), ignore unused return value of GetCodepointNext by @ashn-dot-dev -[rtext] REVIEWED: TextFormat() warn user if buffer overflow occured (#3399) by @Murlocohol -[rtext] REVIEWED: TextFormat(), added "..." for truncation (#3366) by @raysan5 -[rtext] REVIEWED: GetGlyphIndex() (#3000) by @raysan5 -[rtext] REVIEWED: GetCodepointNext() to return default value by @chocolate42 -[rtext] REVIEWED: TextToPascal() issue when first char is uppercase -[rmodels] ADDED: ModelAnimation.name field, initially with GLTF animation names by @alfredbaudisch -[rmodels] REDESIGNED: LoadOBJ(), avoid mesh splitting by materials, fix (#3398) by @raysan5 -[rmodels] REVIEWED: Support .vox model files version 200 (#3097) by @Bigfoot71 -[rmodels] REVIEWED: Materials loading (#3126) @raysan5 -[rmodels] REVIEWED: DrawBillboardPro() to allow source of negative size (#3197) by @bohonghuang -[rmodels] REVIEWED: glTF loading segfault in animNormals memcpy by @charles-l -[rmodels] REVIEWED: LoadModelAnimationsGLTF(), free fileData after use (#3065) by @crynux -[rmodels] REVIEWED: GenMeshCubicmap(), correction of values (#3032) by @Bigfoot71 -[rmodels] REVIEWED: DrawMesh() to avoid UBSAN complaining (#1891) -[rmodels] REVIEWED: GenMeshPlane() when resX != resZ (#3425) by @neyrox, @s-yablonskiy -[rmodels] REVIEWED: GetModelBoundingBox() (#3485) -[raudio] ADDED: LoadSoundAlias() by @JeffM2501 -[raudio] ADDED: Missing structure on standalone mode (#3160) by @raysan5 -[raudio] ADDED: GetMasterVolume() (#3434) by @rexim -[raudio] REVIEWED: Comments about sample format to AttachAudioStreamProcessor() (#3188) by @AlbertoGP -[raudio] REVIEWED: Documented buffer format for audio processors (#3186) by @AlbertoGP -[raudio] REVIEWED: ExportWaveAsCode() file saving by @RadsammyT -[raudio] REVIEWED: Fix warning on discarded const qualifier (#2967) by @RobLoach -[raudio] REVIEWED: Move mutex initialization before ma_device_start() (#3325) by @Bigfoot71 -[raudio] REVIEWED: Fix UpdateSound() parameter name (#3405) by @KislyjKisel -[raudio] REVIEWED: Fix QOA seeking (#3494) by @veins1 -[rcamera] REVIEWED: File-macros for consistency (#3161) by @raysan5 -[rcamera] REVIEWED: Support analog stick camera controls (#3066) by @PixelPhobicGames -[rcamera] REVIEWED: CameraMoveToTarget(), ensure distance is greater than 0 (#3031) by @kolunmi -[rcamera] REVIEWED: Exposing rcamera functions to the dll (#3355) by @JeffM2501 -[raymath] ADDED: Vector3Projection() and Vector3Rejection() (#3263) by @Dial0 -[raymath] ADDED: EPSILON macro to each function requiring it (#3330) by @Brian-ED -[raymath] REVIEWED: Usage of 'sinf()' and 'cosf()' to be correct (#3181) by @RokasPuzonas -[raymath] REVIEWED: Slightly optimized Vector3Normalize() (#2982) by @RicoP -[raymath] REVIEWED: Comment to clarify raymath semantics by @raysan5 -[raymath] REVIEWED: Comment about Matrix conventions by @raysan5 -[raymath] REVIEWED: Vector2Angle() and Vector2LineAngle() (#3396) by @Murlocohol -[rgestures] REVIEWED: Optimize and simplify the gesture system (#3190) by @ubkp -[rgestures] REVIEWED: GESTURE_DRAG and GESTURE_SWIPE_* issues (mostly) for web (#3183) by @ubkp -[rgestures] REVIEWED: Touch pointCount for web (#3163) by @ubkp -[rgestures] REVIEWED: IsGestureDetected() parameter type -[utils] ADDED: Security checks to file reading (memory allocations) by @raysan5 -[utils] REVIEWED: LoadFileData() potential issues with dataSize -[examples] ADDED: shaders_lightmap (#3043) by @nullstare -[examples] ADDED: core_2d_camera_split_screen (#3298) by @gabrielssanches -[examples] ADDED: LoadSoundAlias() usage example (#3223) by @JeffM2501 -[examples] ADDED: textures_tiling (#3353) by @luis605 -[examples] ADDED: shader_deferred_render (#3496) by @27justin -[examples] RENAMED: 2d_camera examples for consistency -[examples] REVIEWED: Text examples SetTextLineSpacing() to multiline examples by @raysan5 -[examples] REVIEWED: examples/shapes/shapes_collision_area.c help instructions (#3279) by @asdqwe -[examples] REVIEWED: examples/shaders/shaders_texture_outline.c help instructions (#3278) by @asdqwe -[examples] REVIEWED: examples/others/easings_testbed.c help instructions and small twe… by @asdqwe -[examples] REVIEWED: example/audio/audio_module_player.c help instructions and small b… by @asdqwe -[examples] REVIEWED: example/models/models_loading_m3d.c controls (#3269) by @asdqwe -[examples] REVIEWED: example/models/models_loading_gltf.c controls (#3268) by @asdqwe -[examples] REVIEWED: text_unicode.c example crashing (#3250) by @ubkp -[examples] REVIEWED: rlgl_standalone.c compilation issue (#3242) by @ubkp -[examples] REVIEWED: core_input_gestures for Web (#3172) by @ubkp -[examples] REVIEWED: core_input_gamepad (#3110) by @iacore -[examples] REVIEWED: examples using raygui to raygui 4.0 by @raysan5 -[examples] REVIEWED: Julia set shader example (#3467) by @joshcol9232 -[build] ADDED: CMake option for SUPPORT_CUSTOM_FRAME_CONTROL (#3221) by @ubkp -[build] ADDED: New BORDERLESS_WINDOWED_MODE for PLATFORM_DESKTOP (#3216) by @ubkp -[build] ADDED: New examples to VS2022 solution by @raysan5 -[build] REVIEWED: Updated Makefile and Makefile.Web, include new examples -[build] REVIEWED: Fix CMake extraneous -lglfw (#3266) by @iacore -[build] REVIEWED: Add missing cmake options (#3267) by @asdqwe -[build] REVIEWED: Match CMakeOptions.txt options default values (#3258) by @asdqwe -[build] REVIEWED: Add build.zig options for individual modules (#3254) by @actondev -[build] REVIEWED: build.zig to work with cross-compiling (#3225) by @yujiri8 -[build] REVIEWED: Makefile build on PLATFORM_ANDROID, soname (#3211) by @ndytts -[build] REVIEWED: src/Makefile, fix misleading indentation (#3202) by @ashn-dot-dev -[build] REVIEWED: build.zig: Support for building with PLAFORM_DRM (#3191) by @jakubvf -[build] REVIEWED: Update CMakeOptions.txt by @raysan5 -[build] REVIEWED: fix: cmake option "OPENGL_VERSION" doesn't work (#3170) by @royqh1979 -[build] REVIEWED: Add error if raylib.h is included in a C++98 program (#3093) by @Peter0x44 -[build] REVIEWED: Cross compilation for PLATFORM_DRM (#3091) by @TheLastBilly -[build] REVIEWED: build.zigm fixed cross-compiling from Linux (#3090)by @yujiri8 -[build] REVIEWED: Enhanced cmake part for OpenBSD (#3086) by @rayit -[build] REVIEWED: Fixed compile on OpenBSD (#3085)by @rayit -[build] REVIEWED: CMake project example: fix a couple of typos (#3014) by @benjamin-thomas -[build] REVIEWED: Fix warnings in raylib for MSVC (#3004) by @JeffM2501 -[build] REVIEWED: Update cmake example project (#3062) by @lesleyrs -[build] REVIEWED: Update build.zig be be able to build with current zig master (#3064) by @ryupold -[build] REVIEWED: VSCode project template (#3048) by @Shoozza -[build] REVIEWED: Fixed broken build.zig files. Now works with latest stable compiler (… by @Gamer-Kold -[build] REVIEWED: Fix missing symbol when rglfw.c on BSD platforms (#2968) by @Koromix -[build] REVIEWED: Update Makefile comment to indicate arm64 as a supported Linux deskto… @ashn-dot-dev -[build] REVIEWED: Update Makefile : clean raygui.c & physac.c (#3296) by @SuperUserNameMan -[build] REVIEWED: Update webassembly.yml and linux.yml -[build] REVIEWED: Update zig build system to zig version 0.11.0 (#3393) by @purple4pur -[build] REVIEWED: Fix for latest zig master (#3037) by @star-tek-mb -[build] REVIEWED: Examples Makefile to use Makefile.Web when building for web (#3449) by @keithstellyes -[build] REVIEWED: build.zig updates for 0.11.0 release. (#3501) by @cabarger -[build] REVIEWED: Support OpenGL ES 3.0 building on Web platform -[build] REVIEWED: Fix warnings in Visual Studio (#3512) by @JeffM2501 -[build] REVIEWED: OpenGL ES 3.0 flags on CMakeOptions (#3514) by @awfulcooking -[bindings] ADDED: fortran-raylib -[bindings] ADDED: raylib-raku to bindings (#3299) by @vushu -[bindings] ADDED: claw-raylib to BINDINGS.md (#3310) by @bohonghuang -[bindings] ADDED: vaiorabbit/raylib-bindings (#3318) by @wilsonsilva -[bindings] ADDED: TurboRaylib (#3317) by @turborium -[bindings] ADDED: raylib-ffi to bindings list (#3164) by @ewpratten -[bindings] ADDED: raylib-pkpy-bindings (#3361) by @blueloveTH -[bindings] ADDED: Raylib.lean to BINDINGS.md (#3409) by @KislyjKisel -[bindings] UPDATED: BINDINGS.md (#3217) by @joseph-montanez -[bindings] UPDATED: BINDINGS.md to include rayjs (#3212) by @mode777 -[bindings] UPDATED: latest h-raylib version (#3166) by @Anut-py -[bindings] UPDATED: bindbd-raylib3 to raylib 4.5 (#3157) by @o3o -[bindings] UPDATED: Janet bindings supported version update (#3083)by @archydragon -[bindings] UPDATED: BINDINGS.md (raylib-py -> 4.5) (#2992) by @overdev -[bindings] UPDATED: BINDINGS.md (raylib-lua -> 4.5) (#2989) by @TSnake41 -[bindings] UPDATED: raylib-d binding version to 4.5 (#2988) by @schveiguy -[bindings] UPDATED: raylib-freebasic to 4.5 (#2986) by @WIITD -[bindings] UPDATED: BINDINGS.md (#2983) by @jarroddavis68 -[bindings] UPDATED: BINDINGS.md for raylib Odin 4.5 (#2981) by @gingerBill -[bindings] UPDATED: BINDINGS.md (#2980) by @GuvaCode -[bindings] UPDATED: BINDINGS.md (#3002) by @fubark -[bindings] UPDATED: BINDINGS.md (#3053) by @JupiterRider -[bindings] UPDATED: BINDINGS.md (#3050) by @Its-Kenta -[bindings] UPDATED: CL bindings version (#3049) by @shelvick -[bindings] UPDATED: BINDINGS.md (#3026) by @ChrisDill -[bindings] UPDATED: BINDINGS.md (#3023) by @sDos280 -[bindings] UPDATED: BINDINGS.md (#3017) by @Soutaisei -[bindings] UPDATED: Various versions to 4.5 (#2974) by @RobLoach -[bindings] UPDATED: raylib.zig version to 4.5 (#2971) by @ryupold -[bindings] UPDATED: h-raylib version (#2970) by @Anut-py -[bindings] UPDATED: Factor's raylib binding to v4.5 (#3350) by @WraithGlade -[bindings] UPDATED: raylib-ocaml bindings to 4.5 version (#3322) by @tjammer -[bindings] UPDATED: Jaylib binding (#3508) by @glowiak -[external] UPDATED: sdefl and sinfl DEFLATE compression libraries by @raysan5 -[external] UPDATED: miniaudio v0.11.12 --> v0.11.19 by @raysan5 -[external] UPDATED: rl_gputex.h compressed images loading library by @raysan5 -[external] UPDATED: Replaced stb_image_resize.c by stb_image_resize2.h (#3403) by @BabakSamimi -[external] UPDATED: qoi and qoa libraries -[external] UPDATED: stb libraries (required ones) -[external] UPDATED: cgltf and m3d libraries -[external] REVIEWED: msf_gif.h, some warnings -[external] REVIEWED: sinfl external library to avoid ASAN complaints (#3349) by @raysan5 -[misc] ADDED: New task point to issue template about checking the wiki (#3169) by @ubkp -[misc] ADDED: CodeQL for static code analysis (#3476) by @b4yuan -[misc] REVIEWED: Update FAQ.md by @raysan5 -[misc] REVIEWED: Potential code issues reported by CodeQL (#3476) -[misc] REVIEWED: Fix a link in the FAQ (#3082)by @jasonliang-dev -[misc] REVIEWED: New file formats to FAQ (#3079) by @Luramoth -[misc] REVIEWED: Make assets loading extension case insensitive #3008 by @raysan5 -[misc] REVIEWED: Updated web shells open-graph info by @raysan5 - -------------------------------------------------------------------------- -Release: raylib 4.5 (18 March 2023) -------------------------------------------------------------------------- -KEY CHANGES: - - ADDED: Improved ANGLE support on Desktop platforms - - ADDED: rcamera module, simpler and more extendable - - ADDED: Support for M3D models and M3D/GLTF animations - - ADDED: Support QOA audio format (import/export) - - ADDED: rl_gputex module for compressed textures loading - - REDESIGNED: rlgl module for automatic render-batch limits checking - - REDESIGNED: rshapes module to minimize the rlgl dependency - -Detailed changes: -[core] ADDED: RAYLIB_VERSION_* values to raylib.h (#2856) by @RobLoach -[core] ADDED: Basic gamepad support for Android (#2709) by @deniska -[core] ADDED: Support CAPS/NUM lock keys registering if locked -[core] ADDED: _GNU_SOURCE define on Linux (#2729) -[core] ADDED: SetWindowIcons() to set multiple icon image sizes -[core] `WARNING`: RENAMED: Exported raylib version symbol to raylib_version #2671 -[core] REMOVED: Touch points on touch up events on Android (#2711) by @deniska -[core] REVIEWED: Window position setup on InitWindow() (#2732) by @RandomErrorMessage -[core] REVIEWED: Touchscreen input related functions on Android (#2702) by @deniska -[core] REVIEWED: Viewport scaling on Android after context rebind (#2703) by @deniska -[core] REVIEWED: ScanDirectoryFilesRecursively() (#2704) -[core] REVIEWED: Gamepad mappings with latest gamecontrollerdb (#2725) -[core] REVIEWED: Monitor order check on app initialization -[core] REVIEWED: Application monitor when opening (#2728, #2731) by @RandomErrorMessage -[core] REVIEWED: Gestures module to use GetTime() if available (#2733) by @RobLoach -[core] REVIEWED: Resolve GLFW3 some symbols re-definition of windows.h in glfw3native (#2643) by @daipom -[core] REVIEWED: OpenURL(), string buffer too short sometimes -[core] REVIEWED: GetRandomValue() range limit warning (#2800) by @Pere001 -[core] REVIEWED: UnloadDirectoryFiles() -[core] REVIEWED: GetKeyPressed(), out of range issue (#2814) by @daipom -[core] REVIEWED: GetTime(), renamed variable 'time' to 'nanoSeconds' (#2816) by @jtainer -[core] REVIEWED: LoadShaderFromMemory(), issue with shader linkage -[core] REVIEWED: Avoid possible gamepad index as -1 (#2839) -[core] REVIEWED: SetShaderValue*(), avoid setup uniforms for invalid locations -[core] REVIEWED: GetClipboardText() on PLATFORM_WEB, permissions issues -[core] REVIEWED: Initial window position for display-sized fullscreen (#2742) by @daipom -[core] REVIEWED: Sticky touches input (#2857) by @ImazighenGhost -[core] REVIEWED: Enable GetWindowHandle() on macOS (#2915) by @Not-Nik -[core] REVIEWED: Window position always inits centered in current monitor -[core] REVIEWED: IsWindowFocused() to consider Android App state (#2935) -[core] REVIEWED: GetMonitorWidth() and GetMonitorHeight() (#2934) -[core] REVIEWED: GetWindowHandle() to return Linux window (#2938) -[core] REVIEWED: WindowDropCallback(), additional security check (#2943) -[core] REVIEWED: Security checks for emscripten_run_script() (#2954) -[utils] REVIEWED: TraceLog() message size limit overflow -[rcamera] REDESIGNED: New implementation from scratch (#2563) by @Crydsch -[rcamera] REVIEWED: Make orbital camera work as expected (#2926) by @JeffM2501 -[rcamera] REVIEWED: Multiple reviews on the new implementation -[rcamera] ADDED: UpdateCameraPro(), supporting custom user inputs -[rlgl] ADDED: OpenGL ES 2.0 support on PLATFORM_DESKTOP (#2840) by @wtnbgo -[rlgl] ADDED: Separate blending modes for color and alpha, BLEND_CUSTOM_SEPARATE (#2741) -[rlgl] ADDED: rlSetBlendFactorsSeparate and custom blend mode modification checks (#2741) by @pure01fx -[rlgl] ADDED: RL_TEXTURE_MIPMAP_BIAS_RATIO support to `rlTextureParameters()` for OpenGL 3.3 #2674 -[rlgl] ADDED: rlCubemapParameters() (#2862) by @GithubPrankster -[rlgl] ADDED: rlSetCullFace() (#2797) by @jtainer -[rlgl] REMOVED: Mipmaps software generation for OpenGL 1.1 -[rlgl] REVIEWED: Check for extensions before enabling them (#2706) by @Not-Nik -[rlgl] REVIEWED: SSBO usage to avoid long long data types -[rlgl] REVIEWED: Enable DXT compression on __APPLE__ targets (#2694) by @Not-Nik -[rlgl] REVIEWED: enums exposed and description comments -[rlgl] REVIEWED: rlBindImageTexture(), correct data types (#2808) by @planetis-m -[rlgl] REVIEWED: rlMultMatrixf(), use const pointer (#2807) by @planetis-m -[rlgl] REVIEWED: Expose OpenGL blending mode factors and functions/equations -[rlgl] REVIEWED: rLoadTextureDepth(), issue with depth textures on WebGL (#2824) -[rlgl] REVIEWED: rlUnloadFramebuffer() (#2937) -[raymath] ADDED: Vector2LineAngle() (#2887) -[raymath] REVIEWED: Vector2Angle() (#2829, #2832) by @AlxHnr, @planetis-m -[shapes] ADDED: CheckCollisionPointPoly() (#2685) by @acejacek -[shapes] REVIEWED: DrawPixel*(), use RL_QUADS/RL_TRIANGLES (#2750) by @hatkidchan -[shapes] REVIEWED: DrawLineBezier*(), fix bezier line breaking (#2735, #2767) by @nobytesgiven -[textures] ADDED: ColorBrightness() -[textures] ADDED: ColorTint() -[textures] ADDED: ColorContrast() -[textures] ADDED: Support for PNM images (.ppm, .pgm) -[textures] ADDED: GenImagePerlinNoise() -[textures] ADDED: GenImageText(), generate grayscale image from text byte data -[textures] ADDED: ImageDrawCircleLines(), ImageDrawCircleLinesV() (#2713) by @RobLoach -[textures] ADDED: ImageBlurGaussian() (#2770) by @nobytesgiven -[textures] REVIEWED: Image fileformat support: PIC, PNM -[textures] REVIEWED: ImageTextEx() and ImageDrawTextEx() scaling (#2756) by @hatkidchan -[textures] `WARNING`: REMOVED: DrawTextureQuad() -[textures] `WARNING`: REMOVED: DrawTexturePoly(), function moved to example: `textures_polygon` -[textures] `WARNING`: REMOVED: DrawTextureTiled(),function implementation moved to the textures_tiled.c -[text] ADDED: GetCodepointPrevious() -[text] ADDED: UnloadUTF8(), aligned with LoadUTF8() -[text] `WARNING`: RENAMED: TextCodepointsToUTF8() to LoadUTF8() -[text] `WARNING`: RENAMED: GetCodepoint() -> GetCodepointNext() -[text] REDESIGNED: GetCodepointNext() -[text] REVIEWED: MeasureTextEx(), avoid crash on bad data -[text] REVIEWED: UnloadFontData(), avoid crash on invalid font data -[models] ADDED: Support M3D model file format (meshes and materials) (#2648) by @bztsrc -[models] ADDED: Support for M3D animations (#2648) by @bztsrc -[models] ADDED: GLTF animation support (#2844) by @charles-l -[models] ADDED: DrawCapsule() and DrawCapsuleWires() (#2761) by @IanBand -[models] ADDED: LoadMaterials(), MTL files loading, same code as OBJ loader (#2872) by @JeffM2501 -[models] `WARNING`: REMOVED: UnloadModelKeepMeshes() -[models] `WARNING`: REMOVED: DrawCubeTexture(), DrawCubeTextureRec(), functions moved to new example: `models_draw_cube_texture` -[models] REVIEWED: DrawMesh(), using SHADER_LOC_COLOR_SPECULAR as a material map (#2908) by @haved -[models] REVIEWED: LoadM3D() vertex color support (#2878) by @GithubPrankster, @bztsrc -[models] REVIEWED: GenMeshHeightmap() (#2716) -[models] REVIEWED: LoadIQM() (#2676) -[models] REVIEWED: Simplify .vox signature check (#2752) by @CrezyDud -[models] REVIEWED: LoadIQM(), support bone names loading if available (#2882) by @PencilAmazing -[models] REVIEWED: GenMeshTangents(), avoid crash on missing texcoords data (#2927) -[audio] ADDED: Full support for QOA audio file format -[audio] ADDED: Mixed audio processor (#2929) by @hatkidchan -[audio] ADDED: IsWaveReady()`, IsSoundReady(), IsMusicReady() (#2892) by @RobLoach -[audio] `WARNING`: REMOVED: Multichannel audio API: PlaySoundMulti(), StopSoundMulti() -[audio] REVIEWED: Clear PCM buffer state when closing audio device (#2736) by @veins1 -[audio] REVIEWED: Android backend selected (#2118, #2875) by @planetis-m -[audio] REVIEWED: Change default threading model for COM objects in miniaudio -[multi] ADDED: IsShaderReady(), IsImageReady(), IsFontReady() (#2892) by @RobLoach -[multi] ADDED: IsModelReady(), IsMaterialReady(), IsTextureReady(), IsRenderTextureReady() (#2895) by @RobLoach -[multi] REVIEWED: Multiple code/comment typos by @sDos280 -[multi] REVIEWED: Grammar mistakes and typos (#2914) by @stickM4N -[multi] REVIEWED: Use TRACELOG() macro instead of TraceLog() in internal modules (#2881) by @RobLoach -[examples] ADDED: textures_textured_curve (#2821) by @JeffM2501 -[examples] ADDED: models_draw_cube_texture -[examples] ADDED: models_loading_m3d (#2648) by @bztsrc -[examples] ADDED: shaders_write_depth (#2836) by @BugraAlptekinSari -[examples] ADDED: shaders_hybrid_render (#2919) by @BugraAlptekinSari -[examples] REMOVED: audio_multichannel_sound -[examples] RENAMED: Several shaders for naming consistency (#2707) -[examples] RENAMED: lighting_instanced.fs to lighting_instancing.fs (glsl100) (#2805) by @gtrxAC -[examples] REVIEWED: core_custom_logging.c (#2692) by @hartmannathan -[examples] REVIEWED: core_camera_2d_platformer (#2687) by @skylar779 -[examples] REVIEWED: core_input_gamepad.c (#2903) by @planetis-m -[examples] REVIEWED: core_custom_frame_control -[examples] REVIEWED: core_drop_files (#2943) -[examples] REVIEWED: text_rectangle_bounds (#2746) by @SzieberthAdam -[examples] REVIEWED: textures_image_processing, added gaussian blurring (#2775) by @nobytesgiven -[examples] REVIEWED: models_billboard, highlighting rotation and draw order (#2779) by @nobytesgiven -[examples] REVIEWED: core_loading_thread, join thread on completion (#2845) by @planetis-m -[examples] REVIEWED: models_loading_gltf -[examples] REVIEWED: Shader lighting.fs for GLSL120 (#2651) -[examples] REVIEWED: text_codepoints_loading.c -[parser] REVIEWED: raylib-parser Makefile (#2765) by @Peter0x44 -[build] ADDED: Packaging for distros with deb-based and rpm-based packages (#2877) by @KOLANICH -[build] ADDED: Linkage library -latomic on Linux (only required for ARM32) -[build] ADDED: Required frameworks on macOS (#2793) by @SpexGuy -[build] ADDED: WASM support for Zig build (#2901) by @Not-Nik -[build] ADDED: New raylib examples as VS2022 project (to raylib solution) -[build] REVIEWED: config.h format and inconsistencies -[build] REVIEWED: Zig build to latest master, avoid deprecated functions (#2910) by @star-tek-mb -[build] REVIEWED: CMake project template to easily target raylib version (#2700) by @RobLoach -[build] REVIEWED: PATH for PLATFORM_WEB target (#2647) by @futureapricot -[build] REVIEWED: build.zig to let user decide how to set build mode and linker fixes by @InKryption -[build] REVIEWED: Deprecation error on Android API higher than 23 (#2778) by @anggape -[build] REVIEWED: Android x86 Architecture name (#2783) by @IsaacTCB -[build] REVIEWED: examples/build.zig for the latest Zig version (#2786) by @RomanAkberov -[utils] REVIEWED: ExportDataAsCode() data types (#2787) by @RGDTAB -[build] REVIEWED: Makefile emscripten path (#2785) by @Julianiolo -[build] REVIEWED: Several compilation warnings (for strict rules) -[build] REVIEWED: All github workflows using deprecated actions -[build] REVIEWED: CMake when compiling for web (#2820) by @object71 -[build] REVIEWED: DLL build on Windows (#2951) by @Skaytacium -[build] REVIEWED: Avoid MSVC warnings in raylib project (#2871) by @JeffM2501 -[build] REVIEWED: Paths in .bat files to build examples (#2870) by @masoudd -[build] REVIEWED: CMake, use GLVND for old cmake versions (#2826) by @simendsjo -[build] REVIEWED: Makefile, multiple tweaks -[build] REVIEWED: CI action: linux_examples.yml -[build] REVIEWED: CI action: cmake.yml -[bindings] ADDED: h-raylib (Haskell) by @Anut-py -[bindings] ADDED: raylib-c3 (C3) by @Its-Kenta -[bindings] ADDED: raylib-umka (Umka) by @RobLoach -[bindings] ADDED: chez-raylib (Chez Scheme) by @Yunoinsky -[bindings] ADDED: raylib-python-ctypes (Python) by @sDos280 -[bindings] ADDED: claylib (Common Lisp) by @shelvick -[bindings] ADDED: raylib-vapi (Vala) by @lxmcf -[bindings] ADDED: TurboRaylib (Object Pascal) by @turborium -[bindings] ADDED: Kaylib (Kotlin/Native) by @Its-Kenta -[bindings] ADDED: Raylib-Nelua (Nelua) by @Its-Kenta -[bindings] ADDED: Cyber (Cyber) by @fubark -[bindings] ADDED: raylib-sunder (Sunder) by @ashn-dot-dev -[bindings] ADDED: raylib BQN (#2962) by @Brian-ED -[misc] REVIEWED: Update external libraries to latest versions - -------------------------------------------------------------------------- -Release: raylib 4.2 (11 August 2022) -------------------------------------------------------------------------- -KEY CHANGES: - - REMOVED: extras libraries (raygui, physac, rrem, reasings, raudio.h) moved to independent separate repos - - UPDATED: examples: Added creation and update raylib versions and assigned **DIFFICULTY LEVELS**! - - rres 1.0: A custom resource-processing and packaging file format, including tooling and raylib integration examples - - raygui 3.2: New version of the immediate-mode gui system for tools development with raylib - - raylib_parser: Multiple improvements of the raylib parser to automatize bindings generation - - ADDED: New file system API: Reviewed to be more aligned with raylib conventions and one advance function added - - ADDED: New audio stream processors API (_experimental_): Allowing to add custom audio stream data processors using callbacks - -Detailed changes: -[multi] ADDED: Frequently Asked Questions (FAQ.md) -[multi] REVIEWED: Multiple trace log messages -[multi] REVIEWED: Avoid some float to double promotions -[multi] REVIEWED: Some functions input parametes that should be const -[multi] REVIEWED: Variables initialization, all variables are initialized on declaration -[multi] REVIEWED: Static array buffers are always re-initialized with memset() -[multi] `WARNING`: RENAMED: Some function input parameters from "length" to "size" -[core] ADDED: GetApplicatonDirectory() (#2256, #2285, #2290) by @JeffM2501 -[core] ADDED: raylibVersion symbol, it could be required by some bindings (#2190) -[core] ADDED: SetWindowOpacity() (#2254) by @tusharsingh09 -[core] ADDED: GetRenderWidth() and GetRenderHeight() by @ArnaudValensi -[core] ADDED: EnableEventWaiting() and DisableEventWaiting() -[core] ADDED: GetFileLength() -[core] ADDED: Modules info at initialization -[core] ADDED: Support clipboard copy/paste on web -[core] ADDED: Support OpenURL() on Android platform (#2396) by @futureapricot -[core] ADDED: Support MOUSE_PASSTHROUGH (#2516) -[core] ADDED: GetMouseWheelMoveV() (#2517) by @schveiguy -[core] `WARNING`: REMOVED: LoadStorageValue() / SaveStorageValue(), moved to example -[core] `WARNING`: RENAMED: GetDirectoryFiles() to LoadDirectoryFiles() -[core] `WARNING`: RENAMED: `ClearDroppedFiles()` to `UnloadDroppedFiles()` -[core] `WARNING`: RENAMED: GetDroppedFiles() to LoadDroppedFiles() -[core] `WARNING`: RENAMED: `ClearDirectoryFiles()` to `UnloadDirectoryFiles()` -[core] `WARNING`: REDESIGNED: WaitTime() argument from milliseconds to seconds (#2506) by @flashback-fx -[core] REVIEWED: GetMonitorWidth()/GetMonitorHeight() by @gulrak -[core] REVIEWED: GetDirectoryFiles(), maximum files allocation (#2126) by @ampers0x26 -[core] REVIEWED: Expose MAX_KEYBOARD_KEYS and MAX_MOUSE_BUTTONS (#2127) -[core] REVIEWED: ExportMesh() (#2138) -[core] REVIEWED: Fullscreen switch on PLATFORM_WEB -[core] REVIEWED: GetMouseWheelMove(), fixed bug -[core] REVIEWED: GetApplicationDirectory() on macOS (#2304) -[core] REVIEWED: ToggleFullscreen() -[core] REVIEWED: Initialize/reset CORE.inputs global state (#2360) -[core] REVIEWED: MouseScrollCallback() (#2371) -[core] REVIEWED: SwapScreenBuffers() for PLATFORM_DRM -[core] REVIEWED: WaitTime(), fix regression causing video stuttering (#2503) by @flashback-fx -[core] REVIEWED: Mouse device support on PLATFORM_DRM (#2381) -[core] REVIEWED: Support OpenBSD timming functions -[core] REVIEWED: Improved boolean definitions (#2485) by @noodlecollie -[core] REVIEWED: TakeScreenshot(), use GetWindowScaleDPI() to calculate size in screenshot/recording (#2446) by @gulrak -[core] REVIEWED: Remove fps requirement for drm connector selection (#2468) by @Crydsch -[core] REVIEWED: IsFileExtension() (#2530) -[camera] REVIEWED: Some camera improvements (#2563) -[rlgl] ADDED: Premultiplied alpha blend mode (#2342) by @megagrump -[rlgl] REVIEWED: VR rendering not taking render target size into account (#2424) by @FireFlyForLife -[rlgl] REVIEWED: Set rlgl internal framebuffer (#2420) -[rlgl] REVIEWED: rlGetCompressedFormatName() -[rlgl] REVIEWED: Display OpenGL 4.3 capabilities with a compile flag (#2124) by @GithubPrankster -[rlgl] REVIEWED: rlUpdateTexture() -[rlgl] REVIEWED: Minimize buffer overflow probability -[rlgl] REVIEWED: Fix scissor mode on macOS (#2170) by @ArnaudValensi -[rlgl] REVIEWED: Clear SSBO buffers on loading (#2185) -[rlgl] REVIEWED: rlLoadShaderCode(), improved shader loading code -[rlgl] REVIEWED: Comment notes about custom blend modes (#2260) by @glorantq -[rlgl] REVIEWED: rlGenTextureMipmaps() -[rlgl] REVIEWED: rlTextureParameters() -[raymath] ADDED: Wrap() (#2522) by @Tekkitslime -[raymath] ADDED: Vector2Transform() -[raymath] ADDED: Vector2DistanceSqr() (#2376) by @AnilBK -[raymath] ADDED: Vector3DistanceSqr() (#2376) by @AnilBK -[raymath] ADDED: Vector2ClampValue(), Vector3ClampValue() (#2428) by @saccharineboi -[raymath] ADDED: Vector3RotateByAxisAngle() (#2590) by @Crydsch -[raymath] `WARNING`: REDESIGNED: Vector2Angle() returns radians instead of degrees (#2193) by @schveiguy -[raymath] `WARNING`: REMOVED: MatrixNormalize() (#2412) -[raymath] REVIEWED: Fix inverse length in Vector2Normalize() (#2189) by @HarriP -[raymath] REVIEWED: Vector2Angle() not working as expected (#2196) by @jdeokkim -[raymath] REVIEWED: Vector2Angle() and Vector3Angle() (#2203) by @trikko -[raymath] REVIEWED: QuaternionInvert(), code simplified (#2324) by @megagrump -[raymath] REVIEWED: QuaternionScale() (#2419) by @tana -[raymath] REVIEWED: Vector2Rotate(), optimized (#2340) by @jdeokkim -[raymath] REVIEWED: QuaternionFromMatrix(), QuaternionEquals() (#2591) by @kirigirihitomi -[raymath] REVIEWED: MatrixRotate*() (#2595, #2599) by @GoodNike -[shapes] REVIEWED: CheckCollision*() consistency -[shapes] REVIEWED: DrawRectanglePro(), support TRIANGLES drawing -[textures] ADDED: Support for QOI image format -[textures] REVIEWED: ImageColorTint(), GetImageColor(), ImageDrawRectangleRec(), optimized functions (#2429) by @AnilBK -[textures] REVIEWED: LoadTextureFromImage(), allow texture loading with no data transfer -[textures] REVIEWED: ImageDraw(), comment to note that f32bit is not supported (#2222) -[textures] REVIEWED: DrawTextureNPatch(), avoid batch overflow (#2401) by @JeffM2501 -[textures] REVIEWED: DrawTextureTiled() (#2173) -[textures] REVIEWED: GenImageCellular() (#2178) -[textures] REVIEWED: LoadTextureCubemap() (#2223, #2224) -[textures] REVIEWED: Export format for float 32bit -[textures] REVIEWED: ExportImage(), support export ".jpeg" files -[textures] REVIEWED: ColorAlphaBlend() (#2524) by @royqh1979 -[textures] REVIEWED: ImageResize() (#2572) -[textures] REVIEWED: ImageFromImage() (#2594) by @wiertek -[text] ADDED: ExportFontAsCode() -[text] ADDED: DrawTextCodepoints() (#2308) by @siddharthroy12 -[text] REVIEWED: TextIsEqual(), protect from NULLs (#2121) by @lukekras -[text] REVIEWED: LoadFontEx(), comment to specify how to get the default character set (#2221) by @JeffM2501 -[text] REVIEWED: GenImageFontAtlas(), increase atlas size guesstimate by @megagrump -[text] REVIEWED: GetCodepoint() (#2201) -[text] REVIEWED: GenImageFontAtlas() (#2556) -[text] REVIEWED: ExportFontAsCode() to use given font padding (#2525) by @TheTophatDemon -[models] ADDED: Reference code to load bones id and weight data for animations -[models] `WARNING`: REMOVED: GetRayCollisionModel() (#2405) -[models] REMOVED: GenMeshBinormals() -[models] REVIEWED: External library: vox_loader.h, 64bit issue (#2186) -[models] REVIEWED: Material color loading when no texture material is available (#2298) by @royqh1979 -[models] REVIEWED: Fix Undefined Symbol _ftelli64 in cgltf (#2319) by @audinue -[models] REVIEWED: LoadGLTF(), fix memory leak (#2441, #2442) by @leomonta -[models] REVIEWED: DrawTriangle3D() batch limits check (#2489) -[models] REVIEWED: DrawBillboardPro() (#2494) -[models] REVIEWED: DrawMesh*() issue (#2211) -[models] REVIEWED: ExportMesh() (#2220) -[models] REVIEWED: GenMeshCylinder() (#2225) -[audio] `WARNING`: ADDED: rAudioProcessor pointer to AudioStream struct (used by Sound and Music structs) -[audio] ADDED: SetSoundPan(), SetMusicPan(), SetAudioStreamPan(), panning support (#2205) by ptarabbia -[audio] ADDED: Audio stream input callback (#2212) by ptarabbia -[audio] ADDED: Audio stream processors support (#2212) by ptarabbia -[audio] REVIEWED: GetMusicTimePlayed(), incorrect value after the stream restarted for XM audio (#2092 #2215) by @ptarabbia -[audio] REVIEWED: Turn on interpolation for XM playback (#2216) by @ptarabbia -[audio] REVIEWED: Fix crash with delay example (#2472) by @ptarabbia -[audio] REVIEWED: PlaySoundMulti() (#2231) -[audio] REVIEWED: ExportWaveAsCode() -[audio] REVIEWED: UpdateMusicStream(), reduce dynamic allocations (#2532) by @dbechrd -[audio] REVIEWED: UpdateMusicStream() to support proper stream looping (#2579) by @veins1 -[utils] ADDED: ExportDataAsCode() -[utils] REVIEWED: Force flush stdout after trace messages (#2465) by @nagy -[easings] ADDED: Function descriptions (#2471) by @RobLoach -[camera] REVIEWED: Fix free camera panning in the wrong direction (#2347) by @DavidLyhedDanielsson -[examples] ADDED: core_window_should_close -[examples] ADDED: core_2d_camera_mouse_zoom (#2583) by @JeffM2501 -[examples] ADDED: shapes_top_down_lights (#2199) by @JeffM2501 -[examples] ADDED: textures_fog_of_war -[examples] ADDED: textures_gif_player -[examples] ADDED: text_codepoints_loading -[examples] ADDED: audio_stream_effects -[examples] REMOVED: core_quat_conversion, not working properly -[examples] REMOVED: raudio_standalone, moved to raudio repo -[examples] RENAMED: textures_rectangle -> textures_sprite_anim -[examples] REVIEWED: core_input_gamepad, improve joystick visualisation (#2390) by @kristianlm -[examples] REVIEWED: textures_draw_tiled -[examples] REVIEWED: shaders_mesh_instancing, free allocated matrices (#2425) by @AnilBK -[examples] REVIEWED: shaders_raymarching -[examples] REVIEWED: audio_raw_stream (#2205) by ptarabbia -[examples] REVIEWED: audio_music_stream -[examples] REVIEWED: shaders_mesh_instancing, simplified -[examples] REVIEWED: shaders_basic_lighting, rlights.h simplified -[examples] REVIEWED: All examples descriptions, included creation/update raylib versions -[parser] ADDED: Defines to parser (#2269) by @iskolbin -[parser] ADDED: Aliases to parser (#2444) by @lazaray -[parser] ADDED: Parse struct descriptions (#2214) by @eutro -[parser] ADDED: Parse enum descriptions and value descriptions (#2208) by @eutro -[parser] ADDED: Lua output format for parser by @iskolbin -[parser] ADDED: Makefile for raylib_parser by @iskolbin -[parser] ADDED: Support for truncating parser input (#2464) by @lazaray -[parser] ADDED: Support for calculated defines to parser (#2463) by @lazaray -[parser] REVIEWED: Update parser files (#2125) by @catmanl -[parser] REVIEWED: Fix memory leak in parser (#2136) by @ronnieholm -[parser] REVIEWED: EscapeBackslashes() -[parser] REVIEWED: Parser improvements (#2461 #2462) by @lazaray -[bindings] ADDED: License details for BINDINGS -[bindings] ADDED: dart-raylib (#2149) by @wolfenrain -[bindings] ADDED: raylib-cslo (#2169) by @jasonswearingen -[bindings] ADDED: raylib-d (#2194) by @schveiguy -[bindings] ADDED: raylib-guile (#2202) by @petelliott -[bindings] ADDED: raylib-scopes (#2238) by @salotz -[bindings] ADDED: naylib (Nim) (#2386) by @planetis-m -[bindings] ADDED: raylib.jl (Julia) (#2403) by @irishgreencitrus -[bindings] ADDED: raylib.zig (#2449) by @ryupold -[bindings] ADDED: racket-raylib (#2454) by @eutro -[bindings] ADDED: raylibr (#2611) by @ramiromagno -[bindings] ADDED: Raylib.4.0.Pascal (#2617) by @sysrpl -[bindings] REVIEWED: Multiple bindings updated to raylib 4.0 -[build] ADDED: VS2022 project -[build] ADDED: Support macOS by zig build system (#2175) -[build] ADDED: Support custom modules selection on compilation -[build] ADDED: Minimal web shell for WebAssembly compilation -[build] ADDED: BSD support for zig builds (#2332) by @zigster64 -[build] ADDED: Repology badge (#2367) by @jubalh -[build] ADDED: Support DLL compilation with TCC compiler (#2569) by @audinue -[build] ADDED: Missing examples to VS2022 examples solution -[build] REMOVED: VS2019 project (unmaintained) -[build] REMOVED: SUPPORT_MOUSE_CURSOR_POINT config option -[build] REVIEWED: Fixed RPi make install (#2217) by @wereii -[build] REVIEWED: Fix build results path on Linux and RPi (#2218) by @wereii -[build] REVIEWED: Makefiles debug flag -[build] REVIEWED: Fixed cross-compilation from x86-64 to RPi (#2233) by @pitpit -[build] REVIEWED: All Makefiles, simplified -[build] REVIEWED: All Makefiles, improve organization -[build] REVIEWED: All Makefiles, support CUSTOM_CFLAGS -[build] REVIEWED: Fixed compiling for Android using CMake (#2270) by @hero2002 -[build] REVIEWED: Make zig build functionality available to zig programs (#2271) by @Not-Nik -[build] REVIEWED: Update CMake project template with docs and web (#2274) by @RobLoach -[build] REVIEWED: Update VSCode project to work with latest makefile and web (#2296) by @phil-shenk -[build] REVIEWED: Support audio examples compilation with external glfw (#2329) by @locriacyber -[build] REVIEWED: Fix "make clean" target failing when shell is not cmd (#2338) by @Peter0x44 -[build] REVIEWED: Makefile linkage -latomic, required by miniaudio on ARM 32bit #2452 -[build] REVIEWED: Update raylib-config.cmake (#2374) by @marcogmaia -[build] REVIEWED: Simplify build.zig to not require user to specify raylib path (#2383) by @Hejsil -[build] REVIEWED: Fix OpenGL 4.3 graphics option in CMake (#2427) by @GoldenThumbs -[extras] `WARNING`: REMOVED: physac from raylib sources/examples, use github.com/raysan5/physac -[extras] `WARNING`: REMOVED: raygui from raylib/src/extras, use github.com/raysan5/raygui -[extras] `WARNING`: REMOVED: rmem from raylib/src/extras, moved to github.com/raylib-extras/rmem -[extras] `WARNING`: REMOVED: easings from raylib/src/extras, moved to github.com/raylib-extras/reasings -[extras] `WARNING`: REMOVED: raudio.h from raylib/src, moved to github.com/raysan5/raudio -[misc] REVIEWED: Update some external libraries to latest versions - -------------------------------------------------------------------------- -Release: raylib 4.0 - 8th Anniversary Edition (05 November 2021) -------------------------------------------------------------------------- -KEY CHANGES: - - Naming consistency and coherency: Complete review of the library: syntax, naming, comments, decriptions, logs... - - Event Automation System: Support for input events recording and automatic re-playing, useful for automated testing and more! - - Custom game-loop control: Intended for advanced users that want to control the events polling and the timming mechanisms - - rlgl 4.0: Completely decoupling from platform layer and raylib, intended for standalone usage as single-file header-only - - raymath 1.5: Complete review following new conventions, to make it more portable and self-contained - - raygui 3.0: Complete review and official new release, more portable and self-contained, intended for tools development - - raylib_parser: New tool to parse raylib.h and extract all required info into custom output formats (TXT, XML, JSON...) - - Zig and Odin official support - -Detailed changes: -[core] ADDED: Support canvas resizing on web (#1840) by @skylersaleh -[core] ADDED: GetMouseDelta() (#1832) by @adricoin2010 -[core] ADDED: Support additional mouse buttons (#1753) by @lambertwang -[core] ADDED: SetRandomSeed() (#1994) by @TommiSinivuo -[core] ADDED: GetTouchPointId() #1972 -[core] ADDED: EncodeDataBase64() and DecodeDataBase64() -[core] REMOVED: PLATFORM_UWP, difficult to maintain -[core] REMOVED: IsGamepadName() -[core] RENAMED: SwapBuffers() to SwapScreenBuffer() -[core] RENAMED: Wait() to WaitTime() -[core] RENAMED: RayHitInfo to RayCollision (#1781) -[core] RENAMED: GetRayCollisionGround() to GetRayCollisionQuad() (#1781) -[core] REVIEWED: Support mouse wheel on x-axis (#1948) -[core] REVIEWED: DisableCursor() on web by registering an empty mouse click event function in emscripten (#1900) by @grenappels -[core] REVIEWED: LoadShader() and default locations and descriptions -[core] REVIEWED: LoadShaderFromMemory() (#1851) by @Ruminant -[core] REVIEWED: WaitTime(), avoid global variables dependency to make the function is self-contained (#1841) -[core] REVIEWED: SetWindowSize() to work on web (#1847) by @nikki93 -[core] REVIEWED: Raspberry RPI/DRM keyboard blocking render loop (#1879) @luizpestana -[core] REVIEWED: Android multi-touch (#1869) by @humbe -[core] REVIEWED: Implemented GetGamepadName() for emscripten by @nbarkhina -[core] REVIEWED: HighDPI support (#1987) by @ArnaudValensi -[core] REVIEWED: KeyCallback(), register keys independently of the actions -[rlgl] ADDED: GRAPHIC_API_OPENGL_43 -[rlgl] ADDED: rlUpdateVertexBufferElements() (#1915) -[rlgl] ADDED: rlActiveDrawBuffers() (#1911) -[rlgl] ADDED: rlEnableColorBlend()/rlDisableColorBlend() -[rlgl] ADDED: rlGetPixelFormatName() -[rlgl] REVIEWED: rlUpdateVertexBuffer (#1914) by @630Studios -[rlgl] REVIEWED: rlDrawVertexArrayElements() (#1891) -[rlgl] REVIEWED: Wrong normal matrix calculation (#1870) -[raymath] ADDED: Vector3Angle() -[raymath] REVIEWED: QuaternionFromAxisAngle() (#1892) -[raymath] REVIEWED: QuaternionToMatrix() returning transposed result. (#1793) by @object71 -[shapes] ADDED: RenderPolyLinesEx() (#1758) by @lambertwang -[shapes] ADDED: DrawSplineBezierCubic() (#2021) by @SAOMDVN -[textures] ADDED: GetImageColor() #2024 -[textures] REMOVED: GenImagePerlinNoise() -[textures] RENAMED: GetTextureData() to LoadImageFromTexture() -[textures] RENAMED: GetScreenData() to LoadImageFromScreen() -[textures] REVIEWED: ExportImage() to use SaveFileData() (#1779) -[textures] REVIEWED: LoadImageAnim() #2005 -[text] ADDED: Security check in case of not valid font -[text] ADDED: `GetGlyphInfo()` to get glyph info for a specific codepoint -[text] ADDED: `GetGlyphAtlasRec()` to get glyph rectangle within the generated font atlas -[text] ADDED: DrawTextPro() with text rotation support, WARNING: DrawTextPro() requires including `rlgl.h`, before it was only dependant on `textures` module. -[text] ADDED: UnloadCodepoints() to safely free loaded codepoints -[text] REMOVED: DrawTextRec() and DrawTextRecEx(), moved to example, those functions could be very specific depending on user needs so it's better to give the user the full source in case of special requirements instead of allowing a function with +10 input parameters. -[text] RENAMED: struct `CharInfo` to `GlyphInfo`, actually that's the correct naming for the data contained. It contains the character glyph metrics and the glyph image; in the past it also contained rectangle within the font atlas but that data has been moved to `Font` struct directly, so, `GlyphInfo` is a more correct name. -[text] RENAMED: `CodepointToUtf8()` to `CodepointToUTF8()`, capitalization of UTF-8 is the correct form, it would also require de hyphen but it can be omitted in this case. -[text] RENAMED: `TextToUtf8()` to `TextCodepointsToUTF8` for consistency and more detail on the functionality. -[text] RENAMED: GetCodepoints() to LoadCodepoints(), now codepoint array data is loaded dynamically instead of reusing a limited static buffer. -[text] RENAMED: GetNextCodepoint() to GetCodepoint() -[models] ADDED: MagikaVoxel VOX models loading -[models] ADDED: GenMeshCone() (#1903) -[models] ADDED: GetModelBoundingBox() -[models] ADDED: DrawBillboardPro() (#1759) by @nobytesgiven -[models] ADDED: DrawCubeTextureRec() (#2001) by @tdgroot -[models] ADDED: DrawCylinderEx() and DrawCylinderWiresEx() (#2049) by @Horrowind -[models] REMOVED: DrawBillboardEx() -[models] RENAMED: MeshBoundingBox() to GetMeshBoundingBox() -[models] RENAMED: MeshTangents() to GenMeshTangents() -[models] RENAMED: MeshBinormals() to GenMeshBinormals() -[models] REVIEWED: GenMeshTangents() (#1877) by @630Studios -[models] REVIEWED: CheckCollisionBoxSphere() by @Crydsch -[models] REVIEWED: GetRayCollisionQuad() by @Crydsch -[models] REVIEWED: LoadGLTF(), fixed missing transformations and nonroot skinning by @MrDiver -[models] REVIEWED: LoadGLTF(), rewriten from scratch, removed animations support (broken) -[models] REVIEWED: Decouple DrawMesh() and DrawMeshInstanced() (#1958) -[models] REVIEWED: Support vertex color attribute for GLTF and IQM (#1790) by @object71 -[models] REVIEWED: DrawBillboardPro() (#1941) by @GithubPrankster -[models] REDESIGNED: Major review of glTF loading functionality (#1849) by @object71 -[audio] ADDED: SeekMusicStream() (#2006) by @GithubPrankster -[audio] REMOVED: GetAudioStreamBufferSizeDefault() -[audio] RENAMED: InitAudioStream() to LoadAudioStream() -[audio] RENAMED: CloseAudioStream() to UnloadAudioStream() -[audio] RENAMED: IsMusicPlaying() to IsMusicStreamPlaying() -[audio] REVIEWED: ExportWaveAsCode() -[audio] REDESIGNED: Use frameCount on audio instead of sampleCount -[utils] REVIEWED: exit() on LOG_FATAL instead of LOG_ERROR (#1796) -[examples] ADDED: core_custom_frame_control -[examples] ADDED: core_basic_screen_manager -[examples] ADDED: core_split_screen (#1806) by @JeffM2501 -[examples] ADDED: core_smooth_pixelperfect (#1771) by @NotManyIdeasDev -[examples] ADDED: shaders_texture_outline (#1883) by @GoldenThumbs -[examples] ADDED: models_loading_vox (#1940) by @procfxgen -[examples] ADDED: rlgl_compute_shader by @TSnake41 (#2088) -[examples] REMOVED: models_material_pbr -[examples] REMOVED: models_gltf_animation -[examples] REVIEWED: core_3d_picking -[examples] REVIEWED: core_input_mouse -[examples] REVIEWED: core_vr_simulator, RenderTexture usage -[examples] REVIEWED: core_window_letterbox, RenderTexture usage -[examples] REVIEWED: shapes_basic_shapes -[examples] REVIEWED: shapes_logo_raylib_anim -[examples] REVIEWED: textures_to_image -[examples] REVIEWED: text_rectangle_bounds -[examples] REVIEWED: text_unicode -[examples] REVIEWED: text_draw_3d -[examples] REVIEWED: models_loading -[examples] REVIEWED: models_skybox (#1792) (#1778) -[examples] REVIEWED: models_mesh_picking -[examples] REVIEWED: models_yaw_pitch_roll -[examples] REVIEWED: models_rlgl_solar_system -[examples] REVIEWED: shaders_custom_uniform, RenderTexture usage -[examples] REVIEWED: shaders_eratosthenes, RenderTexture usage -[examples] REVIEWED: shaders_julia_set, RenderTexture usage -[examples] REVIEWED: shaders_postprocessing, RenderTexture usage -[examples] REVIEWED: shaders_basic_lighting, simplified (#1865) -[examples] REVIEWED: audio_raw_stream.c -[examples] REVIEWED: raudio_standalone -[examples] REVIEWED: raylib_opengl_interop -[examples] REVIEWED: rlgl_standalone.c -[examples] REVIEWED: Resources licenses -[examples] REVIEWED: models resources reorganization -[templates] REMOVED: Moved to a separate repo: https://github.com/raysan5/raylib-game-template -[build] ADDED: Zig build file (#2014) by @TommiSinivuo -[build] ADDED: Android VS2019 solution (#2013) by @Kronka -[build] REMOVED: VS2017 project, outdated -[build] RENAMED: All raylib modules prefixed with 'r' (core -> rcore) -[build] RENAMED: SUPPORT_MOUSE_CURSOR_NATIVE to SUPPORT_MOUSE_CURSOR_POINT -[build] REVIEWED: examples/examples_template.c -[build] REVIEWED: Makefile to latest Emscripten SDK r23 -[build] REVIEWED: Makefile for latest Android NDK r32 LTS -[build] REVIEWED: raylib resource files -[build] Moved some extra raylib libraries to /extras/ directory -[*] UPDATED: Multiple bindings to latest version -[*] UPDATED: Most external libraries to latest versions (except GLFW) -[*] Multiple code improvements and fixes by multiple contributors! - -------------------------------------------------------------------------- -Release: raylib 3.7 (26 April 2021) -------------------------------------------------------------------------- -KEY CHANGES: - - [rlgl] REDESIGNED: Greater abstraction level, some functionality moved to core module - - [rlgl] REVIEWED: Instancing and stereo rendering - - [core] REDESIGNED: VR simulator, fbo/shader exposed to user - - [utils] ADDED: File access callbacks system - - [models] ADDED: glTF animations support (#1551) by @object71 - - [audio] ADDED: Music streaming support from memory (#1606) by @nezvers - - [*] RENAMED: enum types and enum values for consistency - -Detailed changes: -[core] ADDED: LoadVrStereoConfig() -[core] ADDED: UnloadVrStereoConfig() -[core] ADDED: BeginVrStereoMode() -[core] ADDED: EndVrStereoMode() -[core] ADDED: GetCurrentMonitor() (#1485) by @object71 -[core] ADDED: SetGamepadMappings() (#1506) -[core] RENAMED: struct Camera: camera.type to camera.projection -[core] RENAMED: LoadShaderCode() to LoadShaderFromMemory() (#1690) -[core] RENAMED: SetMatrixProjection() to rlSetMatrixProjection() -[core] RENAMED: SetMatrixModelview() to rlSetMatrixModelview() -[core] RENAMED: GetMatrixModelview() to rlGetMatrixModelview() -[core] RENAMED: GetMatrixProjection() to rlGetMatrixProjection() -[core] RENAMED: GetShaderDefault() to rlGetShaderDefault() -[core] RENAMED: GetTextureDefault() to rlGetTextureDefault() -[core] REMOVED: GetShapesTexture() -[core] REMOVED: GetShapesTextureRec() -[core] REMOVED: GetMouseCursor() -[core] REMOVED: SetTraceLogExit() -[core] REVIEWED: GetFileName() and GetDirectoryPath() (#1534) by @gilzoide -[core] REVIEWED: Wait() to support FreeBSD (#1618) -[core] REVIEWED: HighDPI support on macOS retina (#1510) -[core] REDESIGNED: GetFileExtension(), includes the .dot -[core] REDESIGNED: IsFileExtension(), includes the .dot -[core] REDESIGNED: Compresion API to use sdefl/sinfl libs -[rlgl] ADDED: SUPPORT_GL_DETAILS_INFO config flag -[rlgl] REMOVED: GenTexture*() functions (#721) -[rlgl] REVIEWED: rlLoadShaderDefault() -[rlgl] REDESIGNED: rlLoadExtensions(), more details exposed -[raymath] REVIEWED: QuaternionFromEuler() (#1651) -[raymath] REVIEWED: MatrixRotateZYX() (#1642) -[shapes] ADDED: DrawSplineBezierQuad() (#1468) by @epsilon-phase -[shapes] ADDED: CheckCollisionLines() -[shapes] ADDED: CheckCollisionPointLine() by @mkupiec1 -[shapes] REVIEWED: CheckCollisionPointTriangle() by @mkupiec1 -[shapes] REDESIGNED: SetShapesTexture() -[shapes] REDESIGNED: DrawCircleSector(), to use float params -[shapes] REDESIGNED: DrawCircleSectorLines(), to use float params -[shapes] REDESIGNED: DrawRing(), to use float params -[shapes] REDESIGNED: DrawRingLines(), to use float params -[textures] ADDED: DrawTexturePoly() and example (#1677) by @chriscamacho -[textures] ADDED: UnloadImageColors() for allocs consistency -[textures] RENAMED: GetImageData() to LoadImageColors() -[textures] REVIEWED: ImageClearBackground() and ImageDrawRectangleRec() (#1487) by @JeffM2501 -[textures] REVIEWED: DrawTexturePro() and DrawRectanglePro() transformations (#1632) by @ChrisDill -[text] REDESIGNED: DrawFPS() -[models] ADDED: UploadMesh() (#1529) -[models] ADDED: UpdateMeshBuffer() -[models] ADDED: DrawMesh() -[models] ADDED: DrawMeshInstanced() -[models] ADDED: UnloadModelAnimations() (#1648) by @object71 -[models] REMOVED: DrawGizmo() -[models] REMOVED: LoadMeshes() -[models] REMOVED: MeshNormalsSmooth() -[models] REVIEWED: DrawLine3D() (#1643) -[audio] REVIEWED: Multichannel sound system (#1548) -[audio] REVIEWED: jar_xm library (#1701) by @jmorel33 -[utils] ADDED: SetLoadFileDataCallback() -[utils] ADDED: SetSaveFileDataCallback() -[utils] ADDED: SetLoadFileTextCallback() -[utils] ADDED: SetSaveFileTextCallback() -[examples] ADDED: text_draw_3d (#1689) by @Demizdor -[examples] ADDED: textures_poly (#1677) by @chriscamacho -[examples] ADDED: models_gltf_model (#1551) by @object71 -[examples] RENAMED: shaders_rlgl_mesh_instanced to shaders_mesh_intancing -[examples] REDESIGNED: shaders_rlgl_mesh_instanced by @moliad -[examples] REDESIGNED: core_vr_simulator -[examples] REDESIGNED: models_yaw_pitch_roll -[build] ADDED: Config flag: SUPPORT_STANDARD_FILEIO -[build] ADDED: Config flag: SUPPORT_WINMM_HIGHRES_TIMER (#1641) -[build] ADDED: Config flag: SUPPORT_GL_DETAILS_INFO -[build] ADDED: Examples projects to VS2019 solution -[build] REVIEWED: Makefile to support PLATFORM_RPI (#1580) -[build] REVIEWED: Multiple typecast warnings by @JeffM2501 -[build] REDESIGNED: VS2019 project build paths -[build] REDESIGNED: CMake build system by @object71 -[*] RENAMED: Several functions parameters for consistency -[*] UPDATED: Multiple bindings to latest version -[*] UPDATED: All external libraries to latest versions -[*] Multiple code improvements and fixes by multiple contributors! - -------------------------------------------------------------------------- -Release: raylib 3.5 - 7th Anniversary Edition (25 December 2020) -------------------------------------------------------------------------- -KEY CHANGES: - - [core] ADDED: PLATFORM_DRM to support RPI4 and other devices (#1388) by @kernelkinetic - - [core] REDESIGNED: Window states management system through FLAGS - - [rlgl] ADDED: RenderBatch type and related functions to allow custom batching (internal only) - - [rlgl] REDESIGNED: Framebuffers API to support multiple attachment types (#721) - - [textures] REDESIGNED: Image*() functions, big performance improvements (software rendering) - - [*] REVIEWED: Multiple functions to replace file accesses by memory accesses - - [*] ADDED: GitHub Actions CI to support multiple raylib build configurations - -Detailed changes: -[core] ADDED: SetWindowState() / ClearWindowState() -> New flags added! -[core] ADDED: IsWindowFocused() -[core] ADDED: GetWindowScaleDPI() -[core] ADDED: GetMonitorRefreshRate() (#1289) by @Shylie -[core] ADDED: IsCursorOnScreen() (#1262) by @ChrisDill -[core] ADDED: SetMouseCursor() and GetMouseCursor() for standard Desktop cursors (#1407) by @chances -[core] REMOVED: struct RenderTexture2D: depthTexture variable -[core] REMOVED: HideWindow() / UnhideWindow() -> Use SetWindowState() -[core] REMOVED: DecorateWindow() / UndecorateWindow() -> Use SetWindowState() -[core] RENAMED: GetExtension() to GetFileExtension() -[core] REVIEWED: Several structs to reduce size and padding -[core] REVIEWED: struct Texture maps to Texture2D and TextureCubemap -[core] REVIEWED: ToggleFullscreen() (#1287) -[core] REVIEWED: InitWindow(), support empty title for window (#1323) -[core] REVIEWED: RPI: Mouse movements are bound to the screen resolution (#1392) (#1410) by @kernelkinetic -[core] REVIEWED: GetPrevDirectoryPath() fixes on Unix-like systems (#1246) by @ivan-cx -[core] REPLACED: rgif.h by msf_gif.h for automatic gif recording -[core] REDESIGNED: GetMouseWheelMove() to return float movement for precise scrolling (#1397) by @Doy-lee -[core] REDESIGNED: GetKeyPressed(), and added GetCharPressed() (#1336) -[core] UWP rework with improvements (#1231) by @Rover656 -[core] Gamepad axis bug fixes and improvement (#1228) by @mmalecot -[core] Updated joystick mappings with latest version of gamecontrollerdb (#1381) by @coderoth -[rlgl] Corrected issue with OpenGL 1.1 support -[rlgl] ADDED: rlDrawMeshInstanced() (#1318) by @seanpringle -[rlgl] ADDED: rlCheckErrors (#1321) by @seanpringle -[rlgl] ADDED: BLEND_SET blending mode (#1251) by @RandomErrorMessage -[rlgl] ADDED: rlSetLineWidth(), rlGetLineWidth(), rlEnableSmoothLines(), rlDisableSmoothLines() (#1457) by @JeffM2501 -[rlgl] RENAMED: rlUnproject() to Vector3Unproject() [raymath] -[rlgl] REVIEWED: Replace rlglDraw() calls by DrawRenderBatch() internal calls -[rlgl] REVIEWED: GenTextureCubemap(), use rlgl functionality only -[rlgl] REVIEWED: rlFramebufferAttach() to support texture layers -[rlgl] REVIEWED: GenDrawCube() and GenDrawQuad() -[rlgl] REVIEWED: Issues with vertex batch overflow (#1223) -[rlgl] REVIEWED: rlUpdateTexture(), issue with offsets -[rlgl] REDESIGNED: GenTexture*() to use the new fbo API (#721) -[raymath] ADDED: Normalize() and Remap() functions (#1247) by @NoorWachid -[raymath] ADDED: Vector2Reflect() (#1400) by @daniel-junior-dube -[raymath] ADDED: Vector2LengthSqr() and Vector3LengthSqr() (#1248) by @ThePituLegend -[raymath] ADDED: Vector2MoveTowards() function (#1233) by @anatagawa -[raymath] REVIEWED: Some functions consistency (#1197) by @Not-Nik -[raymath] REVIEWED: QuaternionFromVector3ToVector3() (#1263) by @jvocaturo -[raymath] REVIEWED: MatrixLookAt(), optimized (#1442) by @RandomErrorMessage -[shapes] ADDED: CheckCollisionLines(), by @Elkantor -[text] Avoid [textures] functions dependencies -[text] ADDED: Config flag: SUPPORT_TEXT_MANIPULATION -[text] ADDED: LoadFontFromMemory() (TTF only) (#1327) -[text] ADDED: UnloadFontData() -[text] RENAMED: FormatText() -> TextFormat() -[text] REVIEWED: Font struct, added charsPadding (#1432) -[text] REVIEWED: TextJoin() -[text] REVIEWED: TextReplace() (#1172) -[text] REVIEWED: LoadBMFont() to load data from memory (#1232) -[text] REVIEWED: GenImageFontAtlas(), fixed offset (#1171) -[text] REDESIGNED: LoadFontData(), reviewed input parameters -[text] REDESIGNED: LoadFontDefault(), some code simplifications -[text] REDESIGNED: LoadFontFromImage(), avoid LoadImageEx() -[text] REDESIGNED: LoadFontData(), avoid GenImageColor(), ImageFormat() -[text] REDESIGNED: LoadBMFont(), avoid ImageCopy(), ImageFormat(), ImageAlphaMask() -[textures] Move Color functions from [core] to [textures] module -[textures] ADDED: ColorAlphaBlend() -[textures] ADDED: GetPixelColor() -[textures] ADDED: SetPixelColor() -[textures] ADDED: LoadImageFromMemory() (#1327) -[textures] ADDED: LoadImageAnim() to load animated sequence of images -[textures] ADDED: DrawTextureTiled() (#1291) - @Demizdor -[textures] ADDED: UpdateTextureRec() -[textures] ADDED: UnloadImageColors(), UnloadImagePalette(), UnloadWaveSamples() -[textures] REMOVED: Config flag: SUPPORT_IMAGE_DRAWING -[textures] REMOVED: LoadImageEx() -[textures] REMOVED: LoadImagePro() -[textures] REMOVED: GetImageDataNormalized(), not exposed in the API -[textures] RENAMED: ImageExtractPalette() to GetImagePalette() -[textures] RENAMED: Fade() to ColorAlpha(), added #define for compatibility -[textures] RENAMED: GetImageData() -> LoadImageColors() -[textures] RENAMED: GetImagePalette() -> LoadImagePalette() -[textures] RENAMED: GetWaveData() -> LoadWaveSamples() -[textures] REVIEWED: GetPixelDataSize() to consider compressed data properly -[textures] REVIEWED: GetTextureData(), allow retrieving 32bit float data -[textures] REVIEWED: ImageDrawText*() params order -[textures] REVIEWED: ColorAlphaBlend(), support tint color -[textures] REVIEWED: ColorAlphaBlend(), integers-version, optimized (#1218) -[textures] REVIEWED: ImageDraw(), consider negative source offset properly (#1283) -[textures] REVIEWED: ImageDraw(), optimizations test (#1218) -[textures] REVIEWED: ImageResizeCanvas(), optimization (#1218) -[textures] REVIEWED: ExportImage(), optimized -[textures] REVIEWED: ImageAlphaPremultiply(), optimization -[textures] REVIEWED: ImageAlphaClear(), minor optimization -[textures] REVIEWED: ImageToPOT(), renamed parameter -[textures] REVIEWED: ImageCrop() (#1218) -[textures] REVIEWED: ImageToPOT() (#1218) -[textures] REVIEWED: ImageAlphaCrop() (#1218) -[textures] REVIEWED: ExportImage(), optimized (#1218) -[textures] REDESIGNED: ImageCrop(), optimized (#1218) -[textures] REDESIGNED: ImageRotateCCW(), optimized (#1218) -[textures] REDESIGNED: ImageRotateCW(), optimized (#1218) -[textures] REDESIGNED: ImageFlipHorizontal(), optimized (#1218) -[textures] REDESIGNED: ImageFlipVertical(), optimized (#1218) -[textures] REDESIGNED: ImageResizeCanvas(), optimized (#1218) -[textures] REDESIGNED: ImageDrawPixel(), optimized -[textures] REDESIGNED: ImageDrawLine(), optimized -[textures] REDESIGNED: ImageDraw(), optimized (#1218) -[textures] REDESIGNED: ImageResize(), optimized (#1218) -[textures] REDESIGNED: ImageFromImage(), optimized (#1218) -[textures] REDESIGNED: ImageDraw(), optimization (#1218) -[textures] REDESIGNED: ImageAlphaClear(), optimized (#1218) -[textures] REDESIGNED: ExportImageAsCode() to use memory buffer (#1232) -[textures] REDESIGNED: ColorFromHSV() -[models] ADDED: DrawTriangle3D() and DrawTriangleStrip3D() -[models] ADDED: UnloadModelKeepMeshes() -[models] REVIEWED: LoadModel(), avoid loading texcoords and normals from model if not existent -[models] REVIEWED: GenMeshCubicmap(), added comments and simplification -[models] REVIEWED: GenMeshCubicmap(), fixed generated normals (#1244) by @GoldenThumbs -[models] REVIEWED: GenMeshPoly(), fixed buffer overflow (#1269) by @frithrah -[models] REVIEWED: LoadOBJ(): Allow for multiple materials in obj files (#1408) by @chriscamacho and @codifies -[models] REVIEWED: LoadIQM() materials loading (#1227) by @sikor666 -[models] REVIEWED: LoadGLTF() to read from memory buffer -[models] REVIEWED: UpdateMesh(), fix extra memory allocated when updating color buffer (#1271) by @4yn -[models] REVIEWED: MeshNormalsSmooth() (#1317) by @seanpringle -[models] REVIEWED: DrawGrid() (#1417) -[models] REDESIGNED: ExportMesh() to use memory buffer (#1232) -[models] REDESIGNED: LoadIQM() and LoadModelAnimations() to use memory buffers -[audio] ADDED: LoadWaveFromMemory() (#1327) -[audio] REMOVED: SetMusicLoopCount() -[audio] REVIEWED: Several functions, sampleCount vs frameCount (#1423) -[audio] REVIEWED: SaveWAV() to use memory write insted of file -[audio] REVIEWED: LoadMusicStream(), support WAV music streaming (#1198) -[audio] REVIEWED: Support multiple WAV sampleSize for MusicStream (#1340) -[audio] REVIEWED: SetAudioBufferPitch() -[audio] REDESIGNED: Audio looping system -[audio] REDESIGNED: LoadSound(): Use memory loading (WAV, OGG, MP3, FLAC) (#1312) -[audio] REDESIGNED: ExportWaveAsCode() to use memory buffers -[utils] ADDED: MemAlloc() / MemFree() (#1440) -[utils] ADDED: UnloadFileData() / UnloadFileText() -[utils] REVIEWED: android_fopen() to support SDCard access -[utils] REDESIGNED: SaveFile*() functions to expose file access results (#1420) -[rmem] REVIEWED: MemPool and other allocators optimization (#1211) by @assyrianic -[examples] ADDED: core/core_window_flags -[examples] ADDED: core/core_quat_conversion by @chriscamacho and @codifies -[examples] ADDED: textures/textures_blend_modes (#1261) by @accidentalrebel -[examples] ADDED: textures/textures_draw_tiled (#1291) by @Demizdor -[examples] ADDED: shaders/shaders_hot_reloading (#1198) -[examples] ADDED: shaders/shaders_rlgl_mesh_instanced (#1318) by @seanpringle -[examples] ADDED: shaders/shaders_multi_sampler2d -[examples] ADDED: others/embedded_files_loading -[examples] REVIEWED: textures/textures_raw_data (#1286) -[examples] REVIEWED: textures/textures_sprite_explosion, replace resources -[examples] REVIEWED: textures/textures_particles_blending, replace resources -[examples] REVIEWED: textures/textures_image_processing, support mouse -[examples] REVIEWED: models/models_skybox to work on OpenGL ES 2.0 -[examples] REVIEWED: audio/resources, use open license resources -[examples] REVIEWED: others/raudio_standalone.c -[build] ADDED: New config.h configuration options exposing multiple #define values -[build] REMOVED: ANGLE VS2017 template project -[build] REVIEWED: All MSVC compile warnings -[build] Updated Makefile for web (#1332) by @rfaile313 -[build] Updated build pipelines to use latest emscripten and Android NDK -[build] Updated emscriptem build script to generate .a on WebAssembly -[build] Updated Android build for Linux, supporting ANDROID_NDK at compile time by @branlix3000 -[build] Updated VSCode project template tasks -[build] Updated VS2017.UWP project template by @Rover656 -[build] Updated Android build pipeline -[build] REMOVED: AppVeyor and Travis CI build systems -[*] Moved raysan5/raylib/games to independent repo: raysan5/raylib-games -[*] Replaced several examples resources with more open licensed alternatives -[*] Updated BINDINGS.md with NEW bindings and added raylib version binding! -[*] Updated all external libraries to latest versions -[*] Multiple code improvements and small fixes - ------------------------------------------------ -Release: raylib 3.0 (01 April 2020) ------------------------------------------------ -KEY CHANGES: - - Global context states used on all modules. - - Custom memory allocators for all modules and dependencies. - - Centralized file access system and memory data loading. - - Structures reviewed to reduce size and always be used as pass-by-value. - - Tracelog messages completely reviewed and categorized. - - raudio module reviewed to accomodate new Music struct and new miniaudio. - - text module reviewed to improve fonts generation and text management functions. - - Multiple new examples added and categorized examples table. - - GitHub Actions CI implemented for Windows, Linux and macOS. - -Detailed changes: -[build] ADDED: VS2017.ANGLE project, by @msmshazan -[build] ADDED: VS2017 project support for x64 platform configuration -[build] ADDED: Makefile for Android building on macOS, by @Yunoinsky -[build] ADDED: Makefile for Android building on Linux, by @pamarcos -[build] REMOVED: VS2015 project -[build] REVIEWED: VSCode project -[build] REVIEWED: Makefile build system -[build] REVIEWED: Android building, by @NimbusFox -[build] REVIEWED: Compilation with CLion IDE, by @Rover656 -[build] REVIEWED: Generation of web examples, by @pamarcos -[build] REVIEWED: Makefiles path to 'shell.html', by @niorad -[build] REVIEWED: VS2017 64bit compilation issues, by @spec-chum -[build] REVIEWED: Multiple fixes on projects building, by @ChrisDill, @JuDelCo, @electronstudio -[core] ADDED: Support touch/mouse indistinctly -[core] ADDED: FLAG_WINDOW_ALWAYS_RUN to avoid pause on minimize -[core] ADDED: Config flag SUPPORT_HALFBUSY_WAIT_LOOP -[core] ADDED: RPI mouse cursor point support on native mode -[core] ADDED: GetWorldToScreen2D()- Get screen space position for a 2d camera world space position, by @arvyy -[core] ADDED: GetScreenToWorld2D() - Get world space position for a 2d camera screen space position, by @arvyy -[core] ADDED: GetWorldToScreenEx() - Get size position for a 3d world space position -[core] ADDED: DirectoryExists() - Check if a directory path exists -[core] ADDED: GetPrevDirectoryPath() - Get previous directory path for a given path -[core] ADDED: CompressData() - Compress data (DEFLATE algorythm) -[core] ADDED: DecompressData() - Decompress data (DEFLATE algorythm) -[core] ADDED: GetWindowPosition() - Get window position XY on monitor -[core] ADDED: LoadFileData() - Load file data as byte array (read) -[core] ADDED: SaveFileData() - Save data to file from byte array (write) -[core] ADDED: LoadFileText() - Load text data from file (read), returns a '\0' terminated string -[core] ADDED: SaveFileText() - Save text data to file (write), string must be '\0' terminated -[core] REMOVED: Show raylib logo at initialization -[core] REVIEWED: GetFileName(), security checks -[core] REVIEWED: LoadStorageValue(), by @danimartin82 -[core] REVIEWED: SaveStorageValue(), by @danimartin82 -[core] REVIEWED: IsMouseButtonReleased(), when press/release events come too fast, by @oswjk -[core] REVIEWED: SetWindowMonitor(), by @DropsOfSerenity -[core] REVIEWED: IsFileExtension() to be case-insensitive -[core] REVIEWED: IsFileExtension() when checking no-extension files -[core] REVIEWED: Default font scale filter for HighDPI mode -[core] REVIEWED: Touch input scaling for PLATFORM_WEB -[core] REVIEWED: RPI input system, by @DarkElvenAngel -[core] REVIEWED: RPI input threads issues -[core] REVIEWED: OpenGL extensions loading and freeing -[core] REVIEWED: GetDirectoryPath() -[core] REVIEWED: Camera2D behavior, by @arvyy -[core] REVIEWED: OpenGL ES 2.0 extensions check -[rlgl] ADDED: Flags to allow frustrum culling near/far distance configuration at compile time -[rlgl] ADDED: Flags to sllow MAX_BATCH_BUFFERING config at compile time -[rlgl] ADDED: GetMatrixProjection(), by @chriscamacho -[rlgl] ADDED: rlUpdateMeshAt() - Update vertex or index data on GPU, at index, by @brankoku -[rlgl] REVIEWED: Vertex padding not zeroed for quads, by @kawa-yoiko -[rlgl] REVIEWED: Read texture data as RGBA from FBO on GLES 2.0 -[rlgl] REVIEWED: LoadShaderCode() for const correctness, by @heretique -[rlgl] REVIEWED: rlLoadTexture() -[rlgl] REVIEWED: rlReadTexturePixels() -[rlgl] REVIEWED: rlUpdateMesh() to supports updating indices, by @brankoku -[rlgl] REVIEWED: GenTextureCubemap(), renamed parameters for consistency -[rlgl] REVIEWED: HDR pixels loading -[raymath] ADDED: MatrixRotateXYZ(), by @chriscamacho -[raymath] RENAMED: Vector3Multiply() to Vector3Scale() -[camera] REVIEWED: Free camera pitch, by @chriscamacho -[camera] REVIEWED: Camera not working properly at z-align, by @Ushio -[shapes] ADDED: DrawTriangleStrip() - Draw a triangle strip defined by points -[shapes] ADDED: DrawEllipse() - Draw ellipse -[shapes] ADDED: DrawEllipseLines() - Draw ellipse outline -[shapes] ADDED: DrawPolyLines() - Draw a polygon outline of n sides -[shapes] REVIEWED: DrawPoly() shape rendering, by @AlexHCC -[textures] ADDED: LoadAnimatedGIF() - Load animated GIF file -[textures] ADDED: GetImageAlphaBorder() - Get image alpha border rectangle -[textures] ADDED: ImageFromImage() - Create an image from another image piece -[textures] ADDED: ImageClearBackground(), by @iamsouravgupta -[textures] ADDED: ImageDrawPixel(), by @iamsouravgupta -[textures] ADDED: ImageDrawCircle(), by @iamsouravgupta -[textures] ADDED: ImageDrawLineEx(), by @iamsouravgupta -[textures] ADDED: ImageDrawPixelV(), by @RobLoach -[textures] ADDED: ImageDrawCircleV(), by @RobLoach -[textures] ADDED: ImageDrawLineV(), by @RobLoach -[textures] ADDED: ImageDrawRectangleV(), by @RobLoach -[textures] ADDED: ImageDrawRectangleRec(), by @RobLoach -[textures] REVIEWED: ImageDrawPixel(), by @RobLoach -[textures] REVIEWED: ImageDrawLine(), by @RobLoach -[textures] REVIEWED: ImageDrawCircle(), by @RobLoach -[textures] REVIEWED: ImageDrawRectangle(), by @RobLoach -[textures] REVIEWED: ImageDraw(), now it supports color tint parameter -[textures] REVIEWED: ImageResizeCanvas() -[textures] REVIEWED: ImageCrop() with security checks -[textures] REVIEWED: ImageAlphaMask() -[textures] REVIEWED: ImageDrawRectangleLines() -[textures] REVIEWED: GetImageData() -[text] ADDED: TextCopy() - Copy one string to another, returns bytes copied -[text] ADDED: GetCodepoints() - Get all codepoints in a string -[text] ADDED: CodepointToUtf8() - Encode codepoint into utf8 text -[text] ADDED: DrawTextCodepoint() - Draw one character (codepoint) -[text] RENAMED: LoadDefaultFont() -> LoadFontDefault() -[text] RENAMED: TextCountCodepoints() -> GetCodepointsCount() -[text] REVIEWED: TextFormat(), to support caching, by @brankoku -[text] REVIEWED: LoadFontData(), generate empty image for space character -[text] REVIEWED: TextSplit() -[text] REVIEWED: TextToInteger() -[text] REVIEWED: GetNextCodepoint(), renamed parameters for clarity -[text] REVIEWED: GenImageFontAtlas(), improved atlas size computing -[text] REDESIGNED: struct Font, character rectangles have been moved out from CharInfo to Font -[text] REDESIGNED: struct CharInfo, now includes directly an Image of the glyph -[text] REDESIGNED: GenImageFontAtlas(), additional recs parameter added -[text] REDESIGNED: ImageTextEx(), to avoid font retrieval from GPU -[models] ADDED: Support rlPushMatrix() and rlPopMatrix() on mesh drawing -[models] ADDED: DrawPoint3D() - Draw a point in 3D space, actually a small line, by @ProfJski -[models] ADDED: Multi texture support for materials in GLTF format, by @Gamerfiend, @chriscamacho -[models] REVIEWED: LoadGLTF(), fixed memory leak, by @jubalh -[models] REVIEWED: LoadIQM(), support multiple animations loading, by @culacant -[models] REVIEWED: GetCollisionRayModel(), to avoid pointers -[models] REVIEWED: CheckCollisionRay*(), parameters renamed -[models] REVIEWED: UnloadMesh(), to avoid pointers -[models] REVIEWED: LoadModel(), memory initialization -[models] REVIEWED: UpdateModelAnimation(), added security checks -[models] REVIEWED: Multiple fixes on models loading, by @jubalh -[models] REVIEWED: Normals updated when using animated meshes, by @@las3rlars -[models] REVIEWED: Compilation when the SUPPORT_MESH_GENERATION not set, by @@Elkantor -[raudio] ADDED: Multi-channel audio playing, by @chriscamacho -[raudio] REMOVED: LoadWaveEx() -[raudio] RENAMED: IsAudioBufferProcessed() to IsAudioStreamProcessed() -[raudio] REVIEWED: Ensure .xm playback starts in the right place, by @illegalinstruction -[raudio] REVIEWED: Fix short non-looping sounds, by @jbosh -[raudio] REVIEWED: Modules playing time to full length -[raudio] REDESIGNED: Replaced Music pointer by struct -[raudio] REDESIGNED: Removed sampleLeft from Music struct -[examples] ADDED: core_scissor_test, by @ChrisDill -[examples] ADDED: core_2d_camera_platformer, by @arvyy -[examples] ADDED: textures_mouse_painting, by @ChrisDill -[examples] ADDED: models_waving_cubes, by @codecat -[examples] ADDED: models_solar_system, by @aldrinmartoq -[examples] ADDED: shaders_fog, by @chriscamacho -[examples] ADDED: shaders_texture_waves, by @Anata -[examples] ADDED: shaders_basic_lighting, by @chriscamacho -[examples] ADDED: shaders_simple_mask, by @chriscamacho -[examples] ADDED: audio_multichannel_sound, by @chriscamacho -[examples] ADDED: shaders_spotlight, by @chriscamacho -[examples] RENAMED: text_sprite_font > text_font_spritefont -[examples] RENAMED: text_ttf_loading > text_font_filters -[examples] RENAMED: text_bmfont_ttf > text_font_loading -[examples] REMOVED: models_obj_viewer -[examples] REMOVED: models_solar_system -[examples] REVIEWED: models_obj_loading > models_loading -[examples] REVIEWED: models_materials_pbr, shader issues -[examples] REVIEWED: core_window_letterbox, detailed explanation, by @jotac0 -[examples] REVIEWED: core_window_letterbox, virtual mouse, by @anatagawa -[games] ADDED: GGJ2020 game - RE-PAIR -[*] Misc fixes and tweaks, by @yaram, @oraoto, @zatherz, @piecedigital, @Shylie -[*] Update ALL supported projects (Notepad++, VS2017) -[*] Update ALL external libraries to latest versions (29.Jan.2020) -[*] Update ALL examples and games -[*] Update BINDINGS list - ------------------------------------------------ -Release: raylib 2.5 (May 2019) ------------------------------------------------ -KEY CHANGES: - - [core] Redesigned Gamepad mechanism, now common to all platforms and gamepads - - [core] HighDPI monitors support with automatic content scaling - - [rlgl] Complete module redesign to use one single internal buffer - - [rlgl] VR system redesign to allow custom device parameters and distortion shader - - [shapes] New drawing shapes available: CircleSector, Ring and RectangleRounded - - [text] New text management API (multiple functions) - - [text] Full Unicode support (utf8 text) - - [textures] Cubemap textures support - - [textures] Quad and N-Patch drawing - - [models] Skeletal model animation support - - [models] Support multiple meshes per model - - [models] Support glTF model loading - -Detailed changes: -[build] REVIEWED: Default raylib and examples Makefile -[build] REVIEWED: Notepad++ NppExec scripts -[build] REVIEWED: VS2015 and VS2017 projects -[build] REVIEWED: Android APK build pipeline -[core] Converted most #defined values as enum values -[core] Complete redesign of RPI input system to use evdev events -[core] ADDED: IsWindowResized() - Check if window has been resized -[core] ADDED: IsWindowHidden() - Check if window is currently hidden -[core] ADDED: UnhideWindow() - Show the window -[core] ADDED: HideWindow() - Hide the window -[core] ADDED: GetWindowHandle() - Get native window handle -[core] ADDED: GetMonitorCount() - Get number of connected monitors -[core] ADDED: GetMonitorWidth() - Get primary monitor width -[core] ADDED: GetMonitorHeight() - Get primary monitor height -[core] ADDED: GetMonitorPhysicalWidth() - Get primary monitor physical width in millimetres -[core] ADDED: GetMonitorPhysicalHeight() - Get primary monitor physical height in millimetres -[core] ADDED: GetMonitorName() - Get the human-readable, UTF-8 encoded name of the primary monitor -[core] ADDED: GetClipboardText() - Get clipboard text content -[core] ADDED: SetClipboardText() - Set clipboard text content -[core] ADDED: ColorFromHSV() - Returns a Color from HSV values -[core] ADDED: FileExists() - Check if file exists -[core] ADDED: GetFileNameWithoutExt() - Get filename string without extension (memory should be freed) -[core] ADDED: GetDirectoryFiles() - Get filenames in a directory path (memory should be freed) -[core] ADDED: ClearDirectoryFiles() - Clear directory files paths buffers (free memory) -[core] ADDED: OpenURL() - Open URL with default system browser (if available) -[core] ADDED: SetMouseOffset() - Set mouse offset -[core] ADDED: SetMouseScale() - Set mouse scaling -[core] REMOVED: ShowLogo() - Activate raylib logo at startup (can be done with flags) -[shapes] ADDED: DrawCircleSector() - Draw a piece of a circle -[shapes] ADDED: DrawCircleSectorLines() - Draw circle sector outline -[shapes] ADDED: DrawRing() - Draw ring -[shapes] ADDED: DrawRingLines() - Draw ring outline -[shapes] ADDED: DrawRectangleRounded() - Draw rectangle with rounded edges -[shapes] ADDED: DrawRectangleRoundedLines() - Draw rectangle with rounded edges outline -[shapes] ADDED: SetShapesTexture() - Define default texture used to draw shapes -[textures] REVIEWED: ExportImage() - Reorder function parameters -[textures] REVIEWED: ImageDrawRectangle() - Remove unneeded parameter -[textures] ADDED: ExportImageAsCode() - Export image as code file defining an array of bytes -[textures] ADDED: LoadTextureCubemap() - Load cubemap from image, multiple image cubemap layouts supported -[textures] ADDED: ImageExtractPalette() - Extract color palette from image to maximum size (memory should be freed) -[textures] ADDED: ImageDrawRectangleLines() - Draw rectangle lines within an image -[textures] ADDED: DrawTextureQuad() - Draw texture quad with tiling and offset parameters -[textures] ADDED: DrawTextureNPatch() - Draws a texture (or part of it) that stretches or shrinks nicely -[models] REVIEWED: LoadMesh() -> LoadMeshes() - Support multiple meshes loading -[models] REVIEWED: LoadMaterial() -> LoadMaterials() - Support multiple materials loading -[models] REVIEWED: ExportMesh() - Reorder parameters -[models] ADDED: DrawCubeWiresV() - Draw cube wires (Vector version) -[models] ADDED: GenMeshPoly() - Generate polygonal mesh -[models] ADDED: SetMaterialTexture() - Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...) -[models] ADDED: SetModelMeshMaterial() - Set material for a mesh -[models] ADDED: LoadModelAnimations() - Load model animations from file -[models] ADDED: UpdateModelAnimation() - Update model animation pose -[models] ADDED: UnloadModelAnimation() - Unload animation data -[models] ADDED: IsModelAnimationValid() - Check model animation skeleton match -[rlgl] Improved internal batching mechanism (multibuffering support, triangle texcoords...) -[rlgl] REVIEWED: rlPushMatrix()/rlPopMatrix() - Now works like OpenGL 1.1 -[rlgl] REVIEWED: SetShaderValue() - More generic, now requires uniform type -[rlgl] REMOVED: SetShaderValuei() - Can be acoomplished with new SetShaderValue() -[rlgl] ADDED: SetShaderValueV() - Set shader uniform value vector -[rlgl] ADDED: SetShaderValueTexture() - Set shader uniform value for texture -[rlgl] ADDED: BeginScissorMode() - Begin scissor mode (define screen area for following drawing) -[rlgl] ADDED: EndScissorMode() - End scissor mode -[rlgl] ADDED: SetVrConfiguration() - Set stereo rendering configuration parameters -[rlgl] REVIEWED: InitVrSimulator() - No input parameter required, use SetVrConfiguration() -[text] REVIEWED: LoadFontEx() - Reorder function parameters -[text] REVIEWED: LoadFontData() - Reorder function parameters -[text] REVIEWED: GenImageFontAtlas() - Reorder function parameters -[text] RENAMED: FormatText() -> TextFormat() -[text] RENAMED: SubText() -> TextSubtext() -[text] ADDED: LoadFontFromImage() - Load font from Image (XNA style) -[text] ADDED: DrawTextRec() - Draw text using font inside rectangle limits -[text] ADDED: DrawTextRecEx() - Draw text using font inside rectangle limits with support for text selection -[text] ADDED: TextIsEqual() - Check if two text string are equal -[text] ADDED: TextLength() - Get text length, checks for '\0' ending -[text] ADDED: TextReplace() - Replace text string (memory should be freed!) -[text] ADDED: TextInsert() - Insert text in a position (memory should be freed!) -[text] ADDED: TextJoin() - Join text strings with delimiter -[text] ADDED: TextSplit() - Split text into multiple strings -[text] ADDED: TextAppend() - Append text at specific position and move cursor! -[text] ADDED: TextFindIndex() - Find first text occurrence within a string -[text] ADDED: TextToUpper() - Get upper case version of provided string -[text] ADDED: TextToLower() - Get lower case version of provided string -[text] ADDED: TextToPascal() - Get Pascal case notation version of provided string -[text] ADDED: TextToInteger() - Get integer value from text (negative values not supported) -[raudio] ADDED: ExportWave() - Export wave data to file -[raudio] ADDED: ExportWaveAsCode() - Export wave sample data to code (.h) -[raudio] ADDED: IsAudioStreamPlaying() - Check if audio stream is playing -[raudio] ADDED: SetAudioStreamVolume() - Set volume for audio stream (1.0 is max level) -[raudio] ADDED: SetAudioStreamPitch() - Set pitch for audio stream (1.0 is base level) -[examples] Complete review of full examples collection, many additions -[examples] ADDED: core_custom_logging - Custom trace log system -[examples] ADDED: core_input_multitouch - Multitouch input example -[examples] ADDED: core_window_letterbox - Window adapted to screen -[examples] ADDED: core_loading_thread - Data loading in second thread -[examples] REVIEWED: core_input_gamepad - Adapted to new gamepad system -[examples] REVIEWED: core_vr_simulator - HMD device parameters and distortion shader should be provided -[examples] ADDED: core_window_scale_letterbox - Windows resizing and letterbox content -[examples] ADDED: shapes_rectangle_scaling_mouse - Scale a rectangle with mouse -[examples] ADDED: shapes_draw_circle_sector - Circle sector drawing -[examples] ADDED: shapes_draw_ring - Ring drawing -[examples] ADDED: shapes_draw_rectangle_rounded - Rounded rectangle drawing -[examples] ADDED: shapes_bouncing_ball - Ball bouncing in the screen -[examples] ADDED: shapes_collision_area - Collision detection and drawing -[examples] ADDED: shapes_following_eyes - Some maths on eyes and mouse -[examples] ADDED: shapes_easings_ball_anim - Ball animation -[examples] ADDED: shapes_easings_box_anim - Box animation -[examples] ADDED: shapes_easings_rectangle_array - Rectangles animation -[examples] REVIEWED: shapes_colors_palette - Reviewed color selection and text displaying -[examples] ADDED: textures_background_scrolling - Scrolling and parallaz background effect -[examples] ADDED: textures_image_npatch - Drawing N-Patch based boxes -[examples] ADDED: textures_sprite_button - Sprite button with sound -[examples] ADDED: textures_sprite_explosion - Sprite explosion with sound -[examples] ADDED: textures_bunnymark - Benchmarking test -[examples] ADDED: text_draw_inside_rectangle - Drawing text inside a delimited rectangle box -[examples] ADDED: text_unicode - Multiple languages text drawing -[examples] ADDED: text_rectangle_bound - Fit text inside a rectangle -[examples] REVIEWED: text_bmfont_ttf - Simplified example -[examples] ADDED: models_animation - Animated models loading and animation playing -[examples] ADDED: models_obj_viewer - Draw and drop models viewer -[examples] ADDED: models_rlgl_solar_system - Solar system simulation using rlgl functionality -[examples] ADDED: models_first_person_maze - 3D maze fps -[examples] ADDED: shaders_palette_switch - Switching color palette on shader -[examples] ADDED: shaders_raymarching - Raymarching shader -[examples] ADDED: shaders_texture_drawing - Texture drawing on GPU -[examples] ADDED: shaders_texture_waves - Texture waves on shader -[examples] ADDED: shaders_julia_set - Julia set fractals -[examples] ADDED: shaders_eratosthenes - Prime number visualization shader -[examples] REVIEWED: audio_raw_stream - Mostly rewritten -[games] ADDED: GGJ19 game - Cat vs Roomba -[*] Updated external libraries to latest version -[*] Multiple bugs corrected (check github issues) - ------------------------------------------------ -Release: raylib 2.0 (July 2018) ------------------------------------------------ -KEY CHANGES: - - Removed external dependencies (GLFW3 and OpenAL) - - Complete redesign of audio module to use miniaudio library - - Support AppVeyor and Travis CI (continuous integration) building - - Reviewed raymath.h for better consistency and performance (inlining) - - Refactor all #define SUPPORT_* into a single config.h - - Support TCC compiler (32bit and 64bit) - -Detailed changes: -[build] REMOVED: GitHub develop branch -[build] REMOVED: External dependencies GLFW and OpenAL -[build] ADDED: Android 64bit ARM support -[build] ADDED: FreeBSD, OpenBSD, NetBSD, Dragon Fly OS support -[build] ADDED: Universal Windows Platform (UWP) support -[build] ADDED: Wayland Linux desktop support -[build] ADDED: AppVeyor CI for automatic Windows builds -[build] ADDED: Travis CI for automatic Linux/macOS builds -[build] ADDED: rglfw (GLFW3 module) to avoid external dependency -[build] ADDED: VS2017 UWP project -[build] ADDED: Builder project template -[build] ADDED: Compiler memory sanitizer for better debug -[build] ADDED: CMake package target and CI auto-deploy tags -[build] ADDED: DEBUG library building support -[build] ADDED: Notepad++ NppExec scripts -[build] REVIEWED: VS2015 and VS2017 projects -[build] REVIEWED: Android APK build pipeline -[core] REVIEWED: Window creation hints to support transparent windows -[core] Unified InitWindow() between platforms -[core] Export Android main entry point -[core] RENAMED: Begin3dMode() to BeginMode3D() -[core] RENAMED: End3dMode() to EndMode3D() -[core] RENAMED: Begin2dMode() to BeginMode2D() -[core] RENAMED: End2dMode() to EndMode2D() -[core] RENAMED: struct Camera to Camera3D -[core] RENAMED: struct SpriteFont to Font -> plus all required functions! -[core] RENAMED: enum TextureFormat to PixelFormat -[core] REVIEWED: Rectangle params int to float -[core] REVIEWED: timing system for macOS -[core] REMOVED: ColorToFloat() -[core] ADDED: GetCurrentTime() on macOS -[core] ADDED: GetTime() -[core] ADDED: struct Vector4 -[core] ADDED: SetTraceLog() to define trace log messages type -[core] ADDED: GetFileName() to get filename from path string -[core] ADDED: ColorToHSV() -[core] ADDED: ColorNormalize() -[core] ADDED: SetWindowSize() to scale Windows in runtime -[core] ADDED: SetMouseScale() to scale mouse input -[core] ADDED: key definitions - KEY_GRAVE, KEY_SLASH, KEY_BACKSLASH -[core] RENAMED: GetHexValue() to ColorToInt() -[core] REVIEWED: Fade() -[core] REVIEWED: InitWindow() to avoid void pointer (safety) -[core] Support camera 3d orthographic projection mode -[shapes] ADDED: DrawRectangleLinesEx() -[textures] Improved pixel formats support (32bit channels) -[textures] Improved textures support for OpenGL 2.1 -[textures] REMOVED: DrawRectangleT() --> Added support to DrawRectangle() -[textures] ADDED: GetPixelDataSize(); pixel data size in bytes (image or texture) -[textures] ADDED: ImageAlphaClear() --> Clear alpha channel to desired color -[textures] ADDED: ImageAlphaCrop() --> Crop image depending on alpha value -[textures] ADDED: ImageAlphaPremultiply() --> Premultiply alpha channel -[textures] ADDED: ImageDrawRectangle() -[textures] ADDED: ImageMipmaps() -[textures] ADDED: GenImageColor() -[textures] ADDED: GetPixelDataSize() -[textures] ADDED: ImageRotateCW() -[textures] ADDED: ImageRotateCCW() -[textures] ADDED: ImageResizeCanvas() -[textures] ADDED: GetImageDataNormalized() -[textures] REVIEWED: ImageFormat() to use normalized data -[textures] REVIEWED: Manual mipmap generation -[textures] REVIEWED: LoadASTC() -[textures] REVIEWED: GenImagePerlinNoise() -[textures] REVIEWED: ImageTextEx() to support UTF8 basic characters -[textures] REVIEWED: GetTextureData() for RPI - requires some work -[textures] Added new example: text drawing on image -[text] Corrected issue with ttf font y-offset -[text] Support SDF font data generation -[text] ADDED: GenImageFontAtlas() -[text] ADDED: LoadFontData() to load data from TTF file -[text] REMOVED: LoadTTF() internal function -[text] REVIEWED: DrawTextEx() - avoid rendering SPACE character! -[text] RENAMED: GetDefaultFont() to GetFontDefault() -[rlgl] ADDED: rlCheckBufferLimit() -[rlgl] ADDED: LoadShaderCode() -[rlgl] ADDED: GetMatrixModelview() -[rlgl] ADDED: SetVrDistortionShader(Shader shader) -[rlgl] REVIEWED: rlLoadTexture() - added mipmaps support, improved compressed textures loading -[rlgl] REVIEWED: rlReadTexturePixels() -[models] Support 4 components mesh.tangent data -[models] Removed tangents generation from LoadOBJ() -[models] ADDED: MeshTangents() -[models] ADDED: MeshBinormals() -[models] ADDED: ExportMesh() -[models] ADDED: GetCollisionRayModel() -[models] RENAMED: CalculateBoundingBox() to MeshBoundingBox() -[models] REMOVED: GetCollisionRayMesh() - does not consider model transform -[models] REVIEWED: LoadMesh() - fallback to default cube mesh if loading fails -[audio] ADDED: Support for MP3 fileformat -[audio] ADDED: IsAudioStreamPlaying() -[audio] ADDED: SetAudioStreamVolume() -[audio] ADDED: SetAudioStreamPitch() -[utils] Corrected issue with SaveImageAs() -[utils] RENAMED: SaveImageAs() to ExportImage() -[utils] REMOVED: rres support - moved to external library (rres.h) -[shaders] REVIEWED: GLSL 120 shaders -[raymath] ADDED: Vector3RotateByQuaternion() -[raymath] REVIEWED: math usage to reduce temp variables -[raymath] REVIEWED: Avoid pointer-based parameters for API consistency -[physac] REVIEWED: physac.h timing system -[examples] Replaced dwarf model by brand new 3d assets: 3d medieval buildings -[examples] Assets cleaning and some replacements -[games] ADDED: GGJ18 game - transmission mission -[games] REVIEWED: Light my Ritual game - improved gameplay drawing -[*] Updated external libraries to latest version -[*] Multiple bugs corrected (check github issues) - ------------------------------------------------ -Release: raylib 1.8.0 (Oct 2017) ------------------------------------------------ -NOTE: - In this release, multiple parts of the library have been reviewed (again) for consistency and simplification. - It exposes more than 30 new functions in comparison with previous version and it improves overall programming experience. - -BIG CHANGES: - - New Image generation functions: Gradient, Checked, Noise, Cellular... - - New Mesh generation functions: Cube, Sphere, Cylinder, Torus, Knot... - - New Shaders and Materials systems to support PBR materials - - Custom Android APK build pipeline with simple Makefile - - Complete review of rlgl layer functionality - - Complete review of raymath functionality - -detailed changes: -[rlgl] RENAMED: rlglLoadTexture() to rlLoadTexture() -[rlgl] RENAMED: rlglLoadRenderTexture() to rlLoadRenderTexture() -[rlgl] RENAMED: rlglUpdateTexture() to rlUpdateTexture() -[rlgl] RENAMED: rlglGenerateMipmaps() to rlGenerateMipmaps() -[rlgl] RENAMED: rlglReadScreenPixels() to rlReadScreenPixels() -[rlgl] RENAMED: rlglReadTexturePixels() to rlReadTexturePixels() -[rlgl] RENAMED: rlglLoadMesh() to rlLoadMesh() -[rlgl] RENAMED: rlglUpdateMesh() to rlUpdateMesh() -[rlgl] RENAMED: rlglDrawMesh() to rlDrawMesh() -[rlgl] RENAMED: rlglUnloadMesh() to rlUnloadMesh() -[rlgl] RENAMED: rlglUnproject() to rlUnproject() -[rlgl] RENAMED: LoadCompressedTexture() to LoadTextureCompressed() -[rlgl] RENAMED: GetDefaultTexture() to GetTextureDefault() -[rlgl] RENAMED: LoadDefaultShader() to LoadShaderDefault() -[rlgl] RENAMED: LoadDefaultShaderLocations() to SetShaderDefaultLocations() -[rlgl] RENAMED: UnloadDefaultShader() to UnLoadShaderDefault() -[rlgl] ADDED: rlGenMapCubemap(), Generate cubemap texture map from HDR texture -[rlgl] ADDED: rlGenMapIrradiance(), Generate irradiance texture map -[rlgl] ADDED: rlGenMapPrefilter(), Generate prefilter texture map -[rlgl] ADDED: rlGenMapBRDF(), Generate BRDF texture map -[rlgl] ADDED: GetVrDeviceInfo(), Get VR device information for some standard devices -[rlgl] REVIEWED: InitVrSimulator(), to accept device parameters as input -[core] ADDED: SetWindowTitle(), Set title for window (only PLATFORM_DESKTOP) -[core] ADDED: GetExtension(), Get file extension -[shapes] REMOVED: DrawRectangleGradient(), replaced by DrawRectangleGradientV() and DrawRectangleGradientH() -[shapes] ADDED: DrawRectangleGradientV(), Draw a vertical-gradient-filled rectangle -[shapes] ADDED: DrawRectangleGradientH(), Draw a horizontal-gradient-filled rectangle -[shapes] ADDED: DrawRectangleGradientEx(), Draw a gradient-filled rectangle with custom vertex colors -[shapes] ADDED: DrawRectangleT(), Draw rectangle using text character -[textures] ADDED: SaveImageAs(), Save image as PNG file -[textures] ADDED: GenImageGradientV(), Generate image: vertical gradient -[textures] ADDED: GenImageGradientH(), Generate image: horizontal gradient -[textures] ADDED: GenImageGradientRadial(), Generate image: radial gradient -[textures] ADDED: GenImageChecked(), Generate image: checked -[textures] ADDED: GenImageWhiteNoise(), Generate image: white noise -[textures] ADDED: GenImagePerlinNoise(), Generate image: perlin noise -[textures] ADDED: GenImageCellular(), Generate image: cellular algorithm. Bigger tileSize means bigger cells -[textures] ADDED: GenTextureCubemap(), Generate cubemap texture from HDR texture -[textures] ADDED: GenTextureIrradiance(), Generate irradiance texture using cubemap data -[textures] ADDED: GenTexturePrefilter(), Generate prefilter texture using cubemap data -[textures] ADDED: GenTextureBRDF(), Generate BRDF texture using cubemap data -[models] REMOVED: LoadMeshEx(), Mesh struct variables can be directly accessed -[models] REMOVED: UpdateMesh(), very ineficient -[models] REMOVED: LoadHeightmap(), use GenMeshHeightmap() and LoadModelFromMesh() -[models] REMOVED: LoadCubicmap(), use GenMeshCubicmap() and LoadModelFromMesh() -[models] RENAMED: LoadDefaultMaterial() to LoadMaterialDefault() -[models] ADDED: GenMeshPlane(), Generate plane mesh (with subdivisions) -[models] ADDED: GenMeshCube(), Generate cuboid mesh -[models] ADDED: GenMeshSphere(), Generate sphere mesh (standard sphere) -[models] ADDED: GenMeshHemiSphere(), Generate half-sphere mesh (no bottom cap) -[models] ADDED: GenMeshCylinder(), Generate cylinder mesh -[models] ADDED: GenMeshTorus(), Generate torus mesh -[models] ADDED: GenMeshKnot(), Generate trefoil knot mesh -[models] ADDED: GenMeshHeightmap(), Generate heightmap mesh from image data -[models] ADDED: GenMeshCubicmap(), Generate cubes-based map mesh from image data -[raymath] REVIEWED: full Matrix functionality to align with GLM in usage -[raymath] RENAMED: Vector3 functions for consistency: Vector*() renamed to Vector3*() -[build] Integrate Android APK building into examples Makefile -[build] Integrate Android APK building into templates Makefiles -[build] Improved Visual Studio 2015 project, folders, references... -[templates] Reviewed the full pack to support Android building -[examples] Reviewed full collection to adapt to raylib changes -[examples] [textures] ADDED: textures_image_generation -[examples] [models] ADDED: models_mesh_generation -[examples] [models] ADDED: models_material_pbr -[examples] [models] ADDED: models_skybox -[examples] [models] ADDED: models_yaw_pitch_roll -[examples] [others] REVIEWED: rlgl_standalone -[examples] [others] REVIEWED: audio_standalone -[github] Moved raylib webpage to own repo: github.com/raysan5/raylib.com -[games] Reviewed game: Koala Seasons -[*] Updated STB libraries to latest version -[*] Multiple bugs corrected (check github issues) - ------------------------------------------------ -Release: raylib 1.7.0 (20 May 2017) ------------------------------------------------ -NOTE: - In this new raylib release, multiple parts of the library have been reviewed for consistency and simplification. - It exposes almost 300 functions, around 30 new functions in comparison with previous version and, again, - it sets a stepping stone towards raylib future. - -BIG changes: - - More than 30 new functions added to the library, check list below. - - Support of configuration flags on every raylib module, to customize library build. - - Improved build system for all supported platforms with a unique Makefile to compile sources. - - Complete review of examples and sample games, added new sample material. - - Support automatic GIF recording of current window, just pressing Ctrl+F12 - - Improved library consistency and organization in general. - -other changes: -[core] Added function: SetWindowIcon(), to setup icon by code -[core] Added function: SetWindowMonitor(), to set current display monitor -[core] Added function: SetWindowMinSize(), to set minimum resize size -[core] Added function: TakeScreenshot(), made public to API (also launched internally with F12) -[core] Added function: GetDirectoryPath(), get directory for a given fileName (with path) -[core] Added function: GetWorkingDirectory(), get current working directory -[core] Added function: ChangeDirectory(), change working directory -[core] Added function: TraceLog(), made public to API -[core] Improved timing system to avoid busy wait loop on frame sync: Wait() -[core] Added support for gamepad on HTML5 platform -[core] Support mouse lock, useful for camera system -[core] Review functions description comments -[rlgl] Removed function: GetStandardShader(), removed internal standard shader -[rlgl] Removed function: CreateLight(), removed internal lighting system -[rlgl] Removed function: DestroyLight(), removed internal lighting system -[rlgl] Removed function: InitVrDevice(), removed VR device render, using simulator -[rlgl] Removed function: CloseVrDevice(), removed VR device render, using simulator -[rlgl] Removed function: IsVrDeviceReady(), removed VR device render, using simulator -[rlgl] Removed function: IsVrSimulator(), removed VR device render, using simulator -[rlgl] Added function: InitVrSimulator(), init VR simulator for selected device -[rlgl] Added function: CloseVrSimulator(), close VR simulator for current device -[rlgl] Added function: IsVrSimulatorReady(), detect if VR device is ready -[rlgl] Added function: BeginVrDrawing(), begin VR simulator stereo rendering -[rlgl] Added function: EndVrDrawing(), end VR simulator stereo rendering -[rlgl] Renamed function: ReadTextFile() to LoadText() and exposed to API -[rlgl] Removed internal lighting system and standard shader, moved to example -[rlgl] Removed Oculus Rift support, moved to oculus_rift example -[rlgl] Removed VR device support and replaced by VR simulator -[shapes] Added function: DrawLineEx(), draw line with QUADS, supports custom line thick -[shapes] Added function: DrawLineBezier(), draw a line using cubic-bezier curves in-out -[shapes] Added function: DrawRectanglePro(), draw a color-filled rectangle with pro parameters -[textures] Removed function: LoadImageFromRES(), redesigning custom RRES fileformat -[textures] Removed function: LoadTextureFromRES(), redesigning custom RRES fileformat -[textures] Removed function: LoadTextureEx(), use instead Image -> LoadImagePro(), LoadImageEx() -[textures] Added function: LoadImagePro()), load image from raw data with parameters -[textures] Review TraceLog() message when image file not found -[text] Renamed function: LoadSpriteFontTTF() to LoadSpriteFontEx(), for consistency -[text] Removed rBMF fileformat support, replaced by .png -[text] Refactor SpriteFont struct (better for rres custom fileformat) -[text] Renamed some variables for consistency -[models] Added function: LoadMesh(), load mesh from file -[models] Added function: LoadMeshEx(), load mesh from vertex data -[models] Added function: UnloadMesh(), unload mesh from memory (RAM and/or VRAM) -[models] Added function: GetCollisionRayMesh(), get collision info between ray and mesh -[models] Added function: GetCollisionRayTriangle(), get collision info between ray and triangle -[models] Added function: GetCollisionRayGround(), get collision info between ray and ground plane -[models] Renamed function: LoadModelEx() to LoadModelFromMesh() -[models] Removed function: DrawLight(), removed internal lighting system -[models] Renamed function: LoadModelEx() to LoadModelFromMesh() for consistency -[models] Removed function: LoadStandardMaterial(), removed internal standard shader -[models] Removed function: LoadModelFromRES(), redesigning custom RRES fileformat -[models] Renamed multiple variables for consistency -[audio] Added function: SetMasterVolume(), define listener volume -[audio] Added function: ResumeSound(), resume a paused sound -[audio] Added function: SetMusicLoopCount(), set number of repeats for a music -[audio] Added function: LoadWaveEx(), load wave from raw audio data -[audio] Added function: WaveCrop(), crop wave audio data -[audio] Added function: WaveFormat(), format audio data -[audio] Removed function: LoadSoundFromRES(), redesigning custom RRES fileformat -[audio] Added support for 32bit audio samples -[audio] Preliminary support for multichannel, limited to mono and stereo -[audio] Make sure buffers are ready for update: UpdateMusicStream() -[utils] Replaced function: GetExtension() by IsFileExtension() and made public to API -[utils] Unified function: TraceLog() between Android and other platforms -[utils] Removed internal function: GetNextPOT(), simplified implementation -[raymath] Added function: QuaternionToEuler(), to work with Euler angles -[raymath] Added function: QuaternionFromEuler(), to work with Euler angles -[raymath] Added multiple Vector2 math functions -[build] Integrate Android source building into Makefile -[example] Added example: shapes_lines_bezier -[example] Added example: text_input_box -[github] Moved gh-pages branch to master/docs -[github] Moved rlua.h and Lua examples to own repo: raylib-lua -[games] Reviewed full games collection -[games] New game added to collection: Koala Seasons -[*] Reviewed and improved examples collection (new assets) -[*] Reorganized library functions, structs, enums -[*] Updated STB libraries to latest version - ------------------------------------------------ -Release: raylib 1.6.0 (20 November 2016) ------------------------------------------------ -NOTE: - This new raylib version commemorates raylib 3rd anniversary and represents another complete review of the library. - It includes some interesting new features and is a stepping stone towards raylib future. - -HUGE changes: -[rlua] Lua BINDING: Complete raylib Lua binding, ALL raylib functions ported to Lua plus the +60 code examples. -[audio] COMPLETE REDESIGN: Improved music support and also raw audio data processing and playing, +20 new functions added. -[physac] COMPLETE REWRITE: Improved performance, functionality and simplified usage, moved to own repository and added multiple examples! - -other changes: - -[core] Corrected issue on OSX with HighDPI display -[core] Added flag to allow resizable window -[core] Allow no default font loading -[core] Corrected old issue with mouse buttons on web -[core] Improved gamepad support, unified across platforms -[core] Gamepad id functionality: GetGamepadName(), IsGamepadName() -[core] Gamepad buttons/axis checking functionality: -[core] Reviewed Android key inputs system, unified with desktop -[rlgl] Redesigned lighting shader system -[rlgl] Updated standard shader for better performance -[rlgl] Support alpha on framebuffer: rlglLoadRenderTexture() -[rlgl] Reviewed UpdateVrTracking() to update camera -[rlgl] Added IsVrSimulator() to check for VR simulator -[shapes] Corrected issue on DrawPolyEx() -[textures] Simplified supported image formats support -[textures] Improved text drawing within an image: ImageDrawText() -[textures] Support image alpha mixing: ImageAlphaMask() -[textures] Support textures filtering: SetTextureFilter() -[textures] Support textures wrap modes: SetTextureWrap() -[text] Improved TTF spritefont generation: LoadSpriteFontTTF() -[text] Improved AngelCode fonts support (unordered chars) -[text] Added TraceLog info on image spritefont loading -[text] Improved text measurement: MeasureTextEx() -[models] Improved OBJ loading flexibility -[models] Reviewed functions: DrawLine3D(), DrawCircle3D() -[models] Removed function: ResolveCollisionCubicmap() -[camera] Redesigned camera system and ported to header-only -[camera] Removed function: UpdateCameraPlayer() -[gestures] Redesigned gestures module to header-only -[audio] Simplified Music loading and playing system -[audio] Added trace on audio device closing -[audio] Reviewed Wave struct, improved flexibility -[audio] Support sound data update: UpdateSound() -[audio] Added support for FLAC audio loading/streaming -[raygui] Removed raygui from raylib repo (moved to own repo) -[build] Added OpenAL static library -[build] Added Visual Studio 2015 projects -[build] Support shared/dynamic raylib compilation -[*] Updated LibOVR to SDK version 1.8 -[*] Updated games to latest raylib version -[*] Improved examples and added new ones -[*] Improved Android support - ------------------------------------------------ -Release: raylib 1.5.0 (18 July 2016) ------------------------------------------------ -NOTE: - Probably this new version is the biggest boost of the library ever, lots of parts of the library have been redesigned, - lots of bugs have been solved and some **AMAZING** new features have been added. - -HUGE changes: -[rlgl] OCULUS RIFT CV1: Added support for VR, not oly Oculus Rift CV1 but also stereo rendering simulator (multiplatform). -[rlgl] MATERIALS SYSTEM: Added support for Materials (.mtl) and multiple material properties: diffuse, specular, normal. -[rlgl] LIGHTING SYSTEM: Added support for up to 8 lights of 3 different types: Omni, Directional and Spot. -[physac] REDESIGNED: Improved performance and simplified usage, physic objects now are managed internally in a second thread! -[audio] CHIPTUNES: Added support for module audio music (.xm, .mod) loading and playing. Multiple mixing channels supported. - -other changes: - -[core] Review Android button inputs -[core] Support Android internal data storage -[core] Renamed WorldToScreen() to GetWorldToScreen() -[core] Removed function SetCustomCursor() -[core] Removed functions BeginDrawingEx(), BeginDrawingPro() -[core] Replaced functions InitDisplay() + InitGraphics() with: InitGraphicsDevice() -[core] Added support for field-of-view Y (fovy) on 3d Camera -[core] Added 2D camera mode functions: Begin2dMode() - End2dMode() -[core] Translate mouse inputs to Android touch/gestures internally -[core] Translate mouse inputs as touch inputs in HTML5 -[core] Improved function GetKeyPressed() to support multiple keys (including function keys) -[core] Improved gamepad support, specially for RaspberryPi (including multiple gamepads support) -[rlgl] Support stereo rendering simulation (duplicate draw calls by viewport, optimized) -[rlgl] Added distortion shader (embeded) to support custom VR simulator: shader_distortion.h -[rlgl] Added support for OpenGL 2.1 on desktop -[rlgl] Improved 2D vs 3D drawing system (lines, triangles, quads) -[rlgl] Improved DXT-ETC1 support on HTML5 -[rlgl] Review function: rlglUnproject() -[rlgl] Removed function: rlglInitGraphics(), integrated into rlglInit() -[rlgl] Updated Mesh and Shader structs -[rlgl] Simplified internal (default) dynamic buffers -[rlgl] Added support for indexed and dynamic mesh data -[rlgl] Set fixed vertex attribs location points -[rlgl] Improved mesh data loading support -[rlgl] Added standard shader (embeded) to support materials and lighting: shader_standard.h -[rlgl] Added light functions: CreateLight(), DestroyLight() -[rlgl] Added wire mode functions: rlDisableWireMode(), rlEnableWireMode() -[rlgl] Review function consistency, added: rlglLoadMesh(), rlglUpdateMesh(), rlglDrawMesh(), rlglUnloadMesh() -[rlgl] Replaced SetCustomShader() by: BeginShaderMode() - EndShaderMode() -[rlgl] Replaced SetBlendMode() by: BeginBlendMode() - EndBlendMode() -[rlgl] Added functions to customize internal matrices: SetMatrixProjection(), SetMatrixModelview() -[rlgl] Unified internal shaders to only one default shader -[rlgl] Added support for render to texture (RenderTexture2D): - LoadRenderTexture() - UnloadRenderTexture() - BeginTextureMode() - EndTextureMode() -[rlgl] Removed SetShaderMap*() functions -[rlgl] Redesigned default buffers usage functions: - LoadDefaultBuffers() - UnloadDefaultBuffers() - UpdateDefaultBuffers() - DrawDefaultBuffers() -[shapes] Corrected bug on GetCollisionRec() -[textures] Added support for Nearest-Neighbor image scaling -[textures] Added functions to draw text on image: ImageDrawText(), ImageDrawTextEx() -[text] Reorganized internal functions: Added LoadImageFont() -[text] Security check for unsupported BMFonts -[models] Split mesh creation from model loading on heightmap and cubicmap -[models] Updated BoundingBox collision detections -[models] Added color parameter to DrawBoundigBox() -[models] Removed function: DrawQuad() -[models] Removed function: SetModelTexture() -[models] Redesigned DrawPlane() to use RL_TRIANGLES -[models] Redesigned DrawRectangleV() to use RL_TRIANGLES -[models] Redesign to accomodate new materials system: LoadMaterial() -[models] Added material functions: LoadDefaultMaterial(), LoadStandardMaterial() -[models] Added MTL material loading support: LoadMTL() -[models] Added function: DrawLight() -[audio] Renamed SoundIsPlaying() to IsSoundPlaying() -[audio] Renamed MusicIsPlaying() to IsMusicPlaying() -[audio] Support multiple Music streams (indexed) -[audio] Support multiple mixing channels -[gestures] Improved and reviewed gestures system -[raymath] Added QuaternionInvert() -[raymath] Removed function: PrintMatrix() -[raygui] Ported to header-only library (https://github.com/raysan5/raygui) -[shaders] Added depth drawing shader (requires a depth texture) -[shaders] Reviewed included shaders and added comments -[OpenAL Soft] Updated to latest version (1.17.2) -[GLFW3] Updated to latest version (3.2) -[stb] Updated to latest headers versions -[GLAD] Converted to header only library and simplified to only used extensions -[*] Reorganize library folders: external libs moved to src/external folder -[*] Reorganize src folder for Android library -[*] Review external dependencies usage -[*] Improved Linux and OSX build systems -[*] Lots of tweaks and bugs corrected all around - ------------------------------------------------ -Release: raylib 1.4.0 (22 February 2016) ------------------------------------------------ -NOTE: - This version supposed another big improvement for raylib, including new modules and new features. - More than 30 new functions have been added to previous raylib version. - Around 8 new examples and +10 new game samples have been added. - -BIG changes: -[textures] IMAGE MANIPULATION: Functions to crop, resize, colorize, flip, dither and even draw image-to-image or text-to-image. -[text] SPRITEFONT SUPPORT: Added support for AngelCode fonts (.fnt) and TrueType fonts (.ttf). -[gestures] REDESIGN: Gestures system simplified and prepared to process generic touch events, including mouse events (multiplatform). -[physac] NEW MODULE: Basic 2D physics support, use colliders and rigidbodies; apply forces to physic objects. - -other changes: - -[rlgl] Removed GLEW library dependency, now using GLAD -[rlgl] Implemented alternative to glGetTexImage() on OpenGL ES -[rlgl] Using depth data on batch drawing -[rlgl] Reviewed glReadPixels() function -[core][rlgl] Reviewed raycast system, now 3D picking works -[core] Android: Reviewed Android App cycle, paused if inactive -[shaders] Implemented Blinn-Phong lighting shading model -[textures] Implemented Floyd-Steinberg dithering - ImageDither() -[text] Added line-break support to DrawText() -[text] Added TrueType Fonts support (using stb_truetype) -[models] Implement function: CalculateBoundingBox(Mesh mesh) -[models] Added functions to check Ray collisions -[models] Improve map resolution control on LoadHeightmap() -[camera] Corrected small-glitch on zoom-in with mouse-wheel -[gestures] Implemented SetGesturesEnabled() to enable only some gestures -[gestures] Implemented GetElapsedTime() on Windows system -[gestures] Support mouse gestures for desktop platforms -[raymath] Complete review of the module and converted to header-only -[easings] Added new module for easing animations -[stb] Updated to latest headers versions -[*] Lots of tweaks around - ------------------------------------------------ -Release: raylib 1.3.0 (01 September 2015) ------------------------------------------------ -NOTE: - This version supposed a big boost for raylib, new modules have been added with lots of features. - Most of the modules have been completely reviewed to accomodate to the new features. - Over 50 new functions have been added to previous raylib version. - Most of the examples have been redone and +10 new advanced examples have been added. - -BIG changes: -[rlgl] SHADERS: Support for model shaders and postprocessing shaders (multiple functions) -[textures] FORMATS: Support for multiple internal formats, including compressed formats -[camera] NEW MODULE: Set of cameras for 3d view: Free, Orbital, 1st person, 3rd person -[gestures] NEW MODULE: Gestures system for Android and HTML5 platforms -[raygui] NEW MODULE: Set of IMGUI elements for tools development (experimental) - -other changes: - -[rlgl] Added check for OpenGL supported extensions -[rlgl] Added function SetBlenMode() to select some predefined blending modes -[core] Added support for drop&drag of external files into running program -[core] Added functions ShowCursor(), HideCursor(), IsCursorHidden() -[core] Renamed function SetFlags() to SetConfigFlags() -[shapes] Simplified some functions to improve performance -[textures] Review of Image struct to support multiple data formats -[textures] Added function LoadImageEx() -[textures] Added function LoadImageRaw() -[textures] Added function LoadTextureEx() -[textures] Simplified function parameters LoadTextureFromImage() -[textures] Added function GetImageData() -[textures] Added function GetTextureData() -[textures] Renamed function ConvertToPOT() to ImageConvertToPOT() -[textures] Added function ImageConvertFormat() -[textures] Added function GenTextureMipmaps() -[text] Added support for Latin-1 Extended characters for default font -[text] Redesigned SpriteFont struct, replaced Character struct by Rectangle -[text] Removed function GetFontBaseSize(), use directly spriteFont.size -[models] Review of struct: Model (added shaders support) -[models] Added 3d collision functions (sphere vs sphere vs box vs box) -[models] Added function DrawCubeTexture() -[models] Added function DrawQuad() -[models] Added function DrawRay() -[models] Simplified function DrawPlane() -[models] Removed function DrawPlaneEx() -[models] Simplified function DrawGizmo() -[models] Removed function DrawGizmoEx() -[models] Added function LoadModelEx() -[models] Review of function LoadCubicMap() -[models] Added function ResolveCollisionCubicmap() -[audio] Decopupled from raylib, now this module can be used as standalone -[audio] Added function UpdateMusicStream() -[raymath] Complete review of the module -[stb] Updated to latest headers versions -[*] Lots of tweaks around - ------------------------------------------------ -Release: raylib 1.2.2 (31 December 2014) ------------------------------------------------ -[*] Added support for HTML5 compiling (emscripten, asm.js) -[core] Corrected bug on input handling (keyboard and mouse) -[textures] Renamed function CreateTexture() to LoadTextureFromImage() -[textures] Added function ConvertToPOT() -[rlgl] Added support for color tint on models on GL 3.3+ and ES2 -[rlgl] Added support for normals on models -[models] Corrected bug on DrawBillboard() -[models] Corrected bug on DrawHeightmap() -[models] Renamed LoadCubesmap() to LoadCubicmap() -[audio] Added function LoadSoundFromWave() -[makefile] Added support for Linux and OSX compiling -[stb] Updated to latest headers versions -[*] Lots of tweaks around - ---------------------------------------------------------------- -Update: raylib 1.2.1 (17 October 2014) (Small Fixes Update) ---------------------------------------------------------------- -[core] Added function SetupFlags() to preconfigure raylib Window -[core] Corrected bug on fullscreen mode -[rlgl] rlglDrawmodel() - Added rotation on Y axis -[text] MeasureTextEx() - Corrected bug on measures for default font - ------------------------------------------------ -Release: raylib 1.2 (16 September 2014) ------------------------------------------------ -NOTE: - This version supposed a complete redesign of the [core] module to support Android and Raspberry Pi. - Multiples modules have also been tweaked to accomodate to the new platforms, specially [rlgl] - -[core] Added multiple platforms support: Android and Raspberry Pi -[core] InitWindow() - Complete rewrite and split for Android -[core] InitDisplay() - Internal function added to calculate proper display size -[core] InitGraphics() - Internal function where OpenGL graphics are initialized -[core] Complete refactoring of input functions to accomodate to new platforms -[core] Mouse and Keyboard raw data reading functions added for Raspberry Pi -[core] GetTouchX(), GetTouchY() - Added for Android -[core] Added Android callbacks to process inputs and Android activity commands -[rlgl] Adjusted buffers depending on platform -[rlgl] Added security check in case deployed vertex excess buffer size -[rlgl] Adjusted indices type depending on GL version (int or short) -[rlgl] Fallback to VBOs only usage if VAOs not supported on ES2 -[rlgl] rlglLoadModel() stores vbo ids on new Model struct -[textures] Added support for PKM files (ETC1, ETC2 compression support) -[shapes] DrawRectangleV() - Modified, depending on OGL version uses TRIANGLES or QUADS -[text] LoadSpriteFont() - Modified to use LoadImage() -[models] Minor changes on models loading to accomodate to new Model struct -[audio] PauseMusicStream(), ResumeMusicStream() - Added -[audio] Reduced music buffer size to avoid stalls on Raspberry Pi -[src] Added makefile for Windows and RPI -[src] Added resources file (raylib icon and executable info) -[examples] Added makefile for Windows and RPI -[examples] Renamed and merged with test examples for coherence with module names -[templates] Added multiple templates to be use as a base-code for games - ------------------------------------------------ -Release: raylib 1.1.1 (22 July 2014) ------------------------------------------------ -[core] ShowLogo() - To enable raylib logo animation at startup -[core] Corrected bug with window resizing -[rlgl] Redefined colors arrays to use byte instead of float -[rlgl] Removed double buffer system (no performance improvement) -[rlgl] rlglDraw() - Reorganized buffers drawing order -[rlgl] Corrected bug on screen resizing -[shapes] DrawRectangle() - Use QUADS instead of TRIANGLES -[models] DrawSphereWires() - Corrected some issues -[models] LoadOBJ() - Redesigned to support multiple meshes -[models] LoadCubesMap() - Loading a map as cubes (by pixel color) -[textures] Added security check if file doesn't exist -[text] Corrected bug on SpriteFont loading -[examples] Corrected some 3d examples -[test] Added cubesmap loading test - ------------------------------------------------ -Release: raylib 1.1.0 (19 April 2014) ------------------------------------------------ -NOTE: - This version supposed a complete internal redesign of the library to support OpenGL 3.3+ and OpenGL ES 2.0. - New module [rlgl] has been added to 'translate' immediate mode style functions (i.e. rlVertex3f()) to GL 1.1, 3.3+ or ES2. - Another new module [raymath] has also been added with lot of useful 3D math vector-matrix-quaternion functions. - -[rlgl] New module, abstracts OpenGL rendering (multiple versions support) -[raymath] New module, useful 3D math vector-matrix-quaternion functions -[core] Adapt all OpenGL code (initialization, drawing) to use [rlgl] -[shapes] Rewrite all shapes drawing functions to use [rlgl] -[textures] Adapt texture GPU loading to use [rlgl] -[textures] Added support for DDS images (compressed and uncompressed) -[textures] CreateTexture() - Redesigned to add mipmap automatic generation -[textures] DrawTexturePro() - Redesigned and corrected bugs -[models] Rewrite all 3d-shapes drawing functions to use [rlgl] -[models] Adapt model loading and drawing to use [rlgl] -[models] Model struct updated to include texture id -[models] SetModelTexture() - Added, link a texture to a model -[models] DrawModelEx() - Redesigned with extended parameters -[audio] Added music streaming support (OGG files) -[audio] Added support for OGG files as Sound -[audio] PlayMusicStream() - Added, open a new music stream and play it -[audio] StopMusicStream() - Added, stop music stream playing and close stream -[audio] PauseMusicStream() - Added, pause music stream playing -[audio] MusicIsPlaying() - Added, to check if music is playing -[audio] SetMusicVolume() - Added, set volume for music -[audio] GetMusicTimeLength() - Added, get current music time length (in seconds) -[audio] GetMusicTimePlayed() - Added, get current music time played (in seconds) -[utils] Added log tracing functionality - TraceLog(), TraceLogOpen(), TraceLogClose() -[*] Log tracing messages all around the code - ------------------------------------------------ -Release: raylib 1.0.6 (16 March 2014) ------------------------------------------------ -[core] Removed unused lighting-system code -[core] Removed SetPerspective() function, calculated directly -[core] Unload and reload default font on fullscreen toggle -[core] Corrected bug gamepad buttons checking if no gamepad available -[texture] DrawTextureV() - Added, to draw using Vector2 for position -[texture] LoadTexture() - Redesigned, now uses LoadImage() + CreateTexture() -[text] FormatText() - Corrected memory leak bug -[models] Added Matrix struct and related functions -[models] DrawBillboard() - Reviewed, now it works! -[models] DrawBillboardRec() - Reviewed, now it works! -[tests] Added folder with multiple tests for new functions - ------------------------------------------------ -Update: raylib 1.0.5 (28 January 2014) ------------------------------------------------ -[audio] LoadSound() - Corrected a bug, WAV file was not closed! -[core] GetMouseWheelMove() - Added, check mouse wheel Y movement -[texture] CreateTexture2D() renamed to CreateTexture() -[models] LoadHeightmap() - Added, Heightmap can be loaded as a Model -[tool] rREM updated, now supports (partially) drag and drop of files - ------------------------------------------------ -Release: raylib 1.0.4 (23 January 2014) ------------------------------------------------ -[tool] Published a first alpha version of rREM tool (raylib Resource Embedder) -[core] GetRandomValue() - Bug corrected, now works right -[core] Fade() - Added, fades a color to an alpha percentadge -[core] WriteBitmap() - Moved to new module: utils.c, not used anymore -[core] TakeScreenshot() - Now uses WritePNG() (utils.c) -[utils] New module created with utility functions -[utils] WritePNG() - Write a PNG file (used by TakeScreenshot() on core) -[utils] DecompressData() - Added, used for rRES resource data decompresion -[textures] LoadImageFromRES() - Added, load an image from a rRES resource file -[textures] LoadTextureFromRES() - Added, load a texture from a rRES resource file -[audio] LoadSoundFromRES() - Added, load a sound from a rRES resource file -[audio] IsPlaying() - Added, check if a sound is currently playing -[audio] SetVolume() - Added, set the volume for a sound -[audio] SetPitch() - Added, set the pitch for a sound -[examples] ex06a_color_select completed -[examples] ex06b_logo_anim completed -[examples] ex06c_font select completed - ------------------------------------------------ -Release: raylib 1.0.3 (19 December 2013) ------------------------------------------------ -[fonts] Added 8 rBMF free fonts to be used on projects! -[text] LoadSpriteFont() - Now supports rBMF file loading (raylib Bitmap Font) -[examples] ex05a_sprite_fonts completed -[examples] ex05b_rbmf_fonts completed -[core] InitWindowEx() - InitWindow with extended parameters, resizing option and custom cursor! -[core] GetRandomValue() - Added, returns a random value within a range (int) -[core] SetExitKey() - Added, sets a key to exit program (default is ESC) -[core] Custom cursor not drawn when mouse out of screen -[shapes] CheckCollisionPointRec() - Added, check collision between point and rectangle -[shapes] CheckCollisionPointCircle() - Added, check collision between point and circle -[shapes] CheckCollisionPointTriangle() - Added, check collision between point and triangle -[shapes] DrawPoly() - Added, draw regular polygons of n sides, rotation can be defined! - ------------------------------------------------ -Release: raylib 1.0.2 (1 December 2013) ------------------------------------------------ -[text] GetDefaultFont() - Added, get default SpriteFont to be used on DrawTextEx() -[shapes] CheckCollisionRecs() - Added, check collision between rectangles -[shapes] CheckCollisionCircles() - Added, check collision between circles -[shapes] CheckCollisionCircleRec() - Added, check collision circle-rectangle -[shapes] GetCollisionRec() - Added, get collision rectangle -[textures] CreateTexture2D() - Added, create Texture2D from Image data -[audio] Fixed WAV loading function, now audio works! - ------------------------------------------------ -Update: raylib 1.0.1 (28 November 2013) ------------------------------------------------ -[text] DrawText() - Removed spacing parameter -[text] MeasureText() - Removed spacing parameter -[text] DrawFps() - Renamed to DrawFPS() for coherence with similar function -[core] IsKeyPressed() - Change functionality, check if key pressed once -[core] IsKeyDown() - Added, check if key is being pressed -[core] IsKeyReleased() - Change functionality, check if key released once -[core] IsKeyUp() - Added, check if key is being NOT pressed -[core] IsMouseButtonDown() - Added, check if mouse button is being pressed -[core] IsMouseButtonPressed() - Change functionality, check if mouse button pressed once -[core] IsMouseButtonUp() - Added, check if mouse button is NOT being pressed -[core] IsMouseButtonReleased() - Change functionality, check if mouse button released once -[textures] DrawTexturePro() - Added, texture drawing with 'pro' parameters -[examples] Function changes applied to ALL examples - ------------------------------------------------ -Release: raylib 1.0.0 (18 November 2013) ------------------------------------------------ -* Initial version -* 6 Modules provided: - - core: basic window/context creation functions, input management, timing functions - - shapes: basic shapes drawing functions - - textures: image data loading and conversion to OpenGL textures - - text: text drawing, sprite fonts loading, default font loading - - models: basic 3d shapes drawing, OBJ models loading and drawing - - audio: audio device initialization, WAV files loading and playing diff --git a/examples/raylib/raylib-5.5_linux_amd64/LICENSE b/examples/raylib/raylib-5.5_linux_amd64/LICENSE deleted file mode 100644 index d1bfe3b..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) - -This software is provided "as-is", without any express or implied warranty. In no event -will the authors be held liable for any damages arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, including commercial -applications, and to alter it and redistribute it freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not claim that you - wrote the original software. If you use this software in a product, an acknowledgment - in the product documentation would be appreciated but is not required. - - 2. Altered source versions must be plainly marked as such, and must not be misrepresented - as being the original software. - - 3. This notice may not be removed or altered from any source distribution. diff --git a/examples/raylib/raylib-5.5_linux_amd64/README.md b/examples/raylib/raylib-5.5_linux_amd64/README.md deleted file mode 100644 index 29173d6..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/README.md +++ /dev/null @@ -1,150 +0,0 @@ - - -**raylib is a simple and easy-to-use library to enjoy videogames programming.** - -raylib is highly inspired by Borland BGI graphics lib and by XNA framework and it's especially well suited for prototyping, tooling, graphical applications, embedded systems and education. - -*NOTE for ADVENTURERS: raylib is a programming library to enjoy videogames programming; no fancy interface, no visual helpers, no debug button... just coding in the most pure spartan-programmers way.* - -Ready to learn? Jump to [code examples!](https://www.raylib.com/examples.html) - ---- - -
- -[![GitHub Releases Downloads](https://img.shields.io/github/downloads/raysan5/raylib/total)](https://github.com/raysan5/raylib/releases) -[![GitHub Stars](https://img.shields.io/github/stars/raysan5/raylib?style=flat&label=stars)](https://github.com/raysan5/raylib/stargazers) -[![GitHub commits since tagged version](https://img.shields.io/github/commits-since/raysan5/raylib/5.0)](https://github.com/raysan5/raylib/commits/master) -[![GitHub Sponsors](https://img.shields.io/github/sponsors/raysan5?label=sponsors)](https://github.com/sponsors/raysan5) -[![Packaging Status](https://repology.org/badge/tiny-repos/raylib.svg)](https://repology.org/project/raylib/versions) -[![License](https://img.shields.io/badge/license-zlib%2Flibpng-blue.svg)](LICENSE) - -[![Discord Members](https://img.shields.io/discord/426912293134270465.svg?label=Discord&logo=discord)](https://discord.gg/raylib) -[![Reddit Static Badge](https://img.shields.io/badge/-r%2Fraylib-red?style=flat&logo=reddit&label=reddit)](https://www.reddit.com/r/raylib/) -[![Youtube Subscribers](https://img.shields.io/youtube/channel/subscribers/UC8WIBkhYb5sBNqXO1mZ7WSQ?style=flat&label=Youtube&logo=youtube)](https://www.youtube.com/c/raylib) -[![Twitch Status](https://img.shields.io/twitch/status/raysan5?style=flat&label=Twitch&logo=twitch)](https://www.twitch.tv/raysan5) - -[![Windows](https://github.com/raysan5/raylib/workflows/Windows/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AWindows) -[![Linux](https://github.com/raysan5/raylib/workflows/Linux/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3ALinux) -[![macOS](https://github.com/raysan5/raylib/workflows/macOS/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AmacOS) -[![WebAssembly](https://github.com/raysan5/raylib/workflows/WebAssembly/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AWebAssembly) - -[![CMakeBuilds](https://github.com/raysan5/raylib/workflows/CMakeBuilds/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3ACMakeBuilds) -[![Windows Examples](https://github.com/raysan5/raylib/actions/workflows/windows_examples.yml/badge.svg)](https://github.com/raysan5/raylib/actions/workflows/windows_examples.yml) -[![Linux Examples](https://github.com/raysan5/raylib/actions/workflows/linux_examples.yml/badge.svg)](https://github.com/raysan5/raylib/actions/workflows/linux_examples.yml) - -features --------- - - **NO external dependencies**, all required libraries are [bundled into raylib](https://github.com/raysan5/raylib/tree/master/src/external) - - Multiple platforms supported: **Windows, Linux, MacOS, RPI, Android, HTML5... and more!** - - Written in plain C code (C99) using PascalCase/camelCase notation - - Hardware accelerated with OpenGL (**1.1, 2.1, 3.3, 4.3, ES 2.0, ES 3.0**) - - **Unique OpenGL abstraction layer** (usable as standalone module): [rlgl](https://github.com/raysan5/raylib/blob/master/src/rlgl.h) - - Multiple **Fonts** formats supported (TTF, OTF, FNT, BDF, sprite fonts) - - Multiple texture formats supported, including **compressed formats** (DXT, ETC, ASTC) - - **Full 3D support**, including 3D Shapes, Models, Billboards, Heightmaps and more! - - Flexible Materials system, supporting classic maps and **PBR maps** - - **Animated 3D models** supported (skeletal bones animation) (IQM, M3D, glTF) - - Shaders support, including model shaders and **postprocessing** shaders - - **Powerful math module** for Vector, Matrix and Quaternion operations: [raymath](https://github.com/raysan5/raylib/blob/master/src/raymath.h) - - Audio loading and playing with streaming support (WAV, QOA, OGG, MP3, FLAC, XM, MOD) - - **VR stereo rendering** support with configurable HMD device parameters - - Huge examples collection with [+140 code examples](https://github.com/raysan5/raylib/tree/master/examples)! - - Bindings to [+70 programming languages](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)! - - **Free and open source** - -basic example --------------- -This is a basic raylib example, it creates a window and draws the text `"Congrats! You created your first window!"` in the middle of the screen. Check this example [running live on web here](https://www.raylib.com/examples/core/loader.html?name=core_basic_window). -```c -#include "raylib.h" - -int main(void) -{ - InitWindow(800, 450, "raylib [core] example - basic window"); - - while (!WindowShouldClose()) - { - BeginDrawing(); - ClearBackground(RAYWHITE); - DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); - EndDrawing(); - } - - CloseWindow(); - - return 0; -} -``` - -build and installation ----------------------- - -raylib binary releases for Windows, Linux, macOS, Android and HTML5 are available at the [Github Releases page](https://github.com/raysan5/raylib/releases). - -raylib is also available via multiple package managers on multiple OS distributions. - -#### Installing and building raylib on multiple platforms - -[raylib Wiki](https://github.com/raysan5/raylib/wiki#development-platforms) contains detailed instructions on building and usage on multiple platforms. - - - [Working on Windows](https://github.com/raysan5/raylib/wiki/Working-on-Windows) - - [Working on macOS](https://github.com/raysan5/raylib/wiki/Working-on-macOS) - - [Working on GNU Linux](https://github.com/raysan5/raylib/wiki/Working-on-GNU-Linux) - - [Working on Chrome OS](https://github.com/raysan5/raylib/wiki/Working-on-Chrome-OS) - - [Working on FreeBSD](https://github.com/raysan5/raylib/wiki/Working-on-FreeBSD) - - [Working on Raspberry Pi](https://github.com/raysan5/raylib/wiki/Working-on-Raspberry-Pi) - - [Working for Android](https://github.com/raysan5/raylib/wiki/Working-for-Android) - - [Working for Web (HTML5)](https://github.com/raysan5/raylib/wiki/Working-for-Web-(HTML5)) - - [Working anywhere with CMake](https://github.com/raysan5/raylib/wiki/Working-with-CMake) - -*Note that the Wiki is open for edit, if you find some issues while building raylib for your target platform, feel free to edit the Wiki or open an issue related to it.* - -#### Setup raylib with multiple IDEs - -raylib has been developed on Windows platform using [Notepad++](https://notepad-plus-plus.org/) and [MinGW GCC](https://www.mingw-w64.org/) compiler but it can be used with other IDEs on multiple platforms. - -[Projects directory](https://github.com/raysan5/raylib/tree/master/projects) contains several ready-to-use **project templates** to build raylib and code examples with multiple IDEs. - -*Note that there are lots of IDEs supported, some of the provided templates could require some review, so please, if you find some issue with a template or you think they could be improved, feel free to send a PR or open a related issue.* - -learning and docs ------------------- - -raylib is designed to be learned using [the examples](https://github.com/raysan5/raylib/tree/master/examples) as the main reference. There is no standard API documentation but there is a [**cheatsheet**](https://www.raylib.com/cheatsheet/cheatsheet.html) containing all the functions available on the library a short description of each one of them, input parameters and result value names should be intuitive enough to understand how each function works. - -Some additional documentation about raylib design can be found in [raylib GitHub Wiki](https://github.com/raysan5/raylib/wiki). Here are the relevant links: - - - [raylib cheatsheet](https://www.raylib.com/cheatsheet/cheatsheet.html) - - [raylib architecture](https://github.com/raysan5/raylib/wiki/raylib-architecture) - - [raylib library design](https://github.com/raysan5/raylib/wiki) - - [raylib examples collection](https://github.com/raysan5/raylib/tree/master/examples) - - [raylib games collection](https://github.com/raysan5/raylib-games) - - -contact and networks ---------------------- - -raylib is present in several networks and raylib community is growing everyday. If you are using raylib and enjoying it, feel free to join us in any of these networks. The most active network is our [Discord server](https://discord.gg/raylib)! :) - - - Webpage: [https://www.raylib.com](https://www.raylib.com) - - Discord: [https://discord.gg/raylib](https://discord.gg/raylib) - - Twitter: [https://www.twitter.com/raysan5](https://www.twitter.com/raysan5) - - Twitch: [https://www.twitch.tv/raysan5](https://www.twitch.tv/raysan5) - - Reddit: [https://www.reddit.com/r/raylib](https://www.reddit.com/r/raylib) - - Patreon: [https://www.patreon.com/raylib](https://www.patreon.com/raylib) - - YouTube: [https://www.youtube.com/channel/raylib](https://www.youtube.com/c/raylib) - -contributors ------------- - - - - - -license -------- - -raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, BSD-like license that allows static linking with closed source software. Check [LICENSE](LICENSE) for further details. - -raylib uses internally some libraries for window/graphics/inputs management and also to support different file formats loading, all those libraries are embedded with and are available in [src/external](https://github.com/raysan5/raylib/tree/master/src/external) directory. Check [raylib dependencies LICENSES](https://github.com/raysan5/raylib/wiki/raylib-dependencies) on [raylib Wiki](https://github.com/raysan5/raylib/wiki) for details. diff --git a/examples/raylib/raylib-5.5_linux_amd64/include/raylib.h b/examples/raylib/raylib-5.5_linux_amd64/include/raylib.h deleted file mode 100644 index a26b8ce..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/include/raylib.h +++ /dev/null @@ -1,1708 +0,0 @@ -/********************************************************************************************** -* -* raylib v5.5 - A simple and easy-to-use library to enjoy videogames programming (www.raylib.com) -* -* FEATURES: -* - NO external dependencies, all required libraries included with raylib -* - Multiplatform: Windows, Linux, FreeBSD, OpenBSD, NetBSD, DragonFly, -* MacOS, Haiku, Android, Raspberry Pi, DRM native, HTML5. -* - Written in plain C code (C99) in PascalCase/camelCase notation -* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3, 4.3, ES2, ES3 - choose at compile) -* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* - Multiple Fonts formats supported (TTF, OTF, FNT, BDF, Sprite fonts) -* - Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) -* - Full 3d support for 3d Shapes, Models, Billboards, Heightmaps and more! -* - Flexible Materials system, supporting classic maps and PBR maps -* - Animated 3D models supported (skeletal bones animation) (IQM, M3D, GLTF) -* - Shaders support, including Model shaders and Postprocessing shaders -* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, QOA, XM, MOD) -* - VR stereo rendering with configurable HMD device parameters -* - Bindings to multiple programming languages available! -* -* NOTES: -* - One default Font is loaded on InitWindow()->LoadFontDefault() [core, text] -* - One default Texture2D is loaded on rlglInit(), 1x1 white pixel R8G8B8A8 [rlgl] (OpenGL 3.3 or ES2) -* - One default Shader is loaded on rlglInit()->rlLoadShaderDefault() [rlgl] (OpenGL 3.3 or ES2) -* - One default RenderBatch is loaded on rlglInit()->rlLoadRenderBatch() [rlgl] (OpenGL 3.3 or ES2) -* -* DEPENDENCIES (included): -* [rcore][GLFW] rglfw (Camilla Löwy - github.com/glfw/glfw) for window/context management and input -* [rcore][RGFW] rgfw (ColleagueRiley - github.com/ColleagueRiley/RGFW) for window/context management and input -* [rlgl] glad/glad_gles2 (David Herberth - github.com/Dav1dde/glad) for OpenGL 3.3 extensions loading -* [raudio] miniaudio (David Reid - github.com/mackron/miniaudio) for audio device/context management -* -* OPTIONAL DEPENDENCIES (included): -* [rcore] msf_gif (Miles Fogle) for GIF recording -* [rcore] sinfl (Micha Mettke) for DEFLATE decompression algorithm -* [rcore] sdefl (Micha Mettke) for DEFLATE compression algorithm -* [rcore] rprand (Ramon Snatamaria) for pseudo-random numbers generation -* [rtextures] qoi (Dominic Szablewski - https://phoboslab.org) for QOI image manage -* [rtextures] stb_image (Sean Barret) for images loading (BMP, TGA, PNG, JPEG, HDR...) -* [rtextures] stb_image_write (Sean Barret) for image writing (BMP, TGA, PNG, JPG) -* [rtextures] stb_image_resize2 (Sean Barret) for image resizing algorithms -* [rtextures] stb_perlin (Sean Barret) for Perlin Noise image generation -* [rtext] stb_truetype (Sean Barret) for ttf fonts loading -* [rtext] stb_rect_pack (Sean Barret) for rectangles packing -* [rmodels] par_shapes (Philip Rideout) for parametric 3d shapes generation -* [rmodels] tinyobj_loader_c (Syoyo Fujita) for models loading (OBJ, MTL) -* [rmodels] cgltf (Johannes Kuhlmann) for models loading (glTF) -* [rmodels] m3d (bzt) for models loading (M3D, https://bztsrc.gitlab.io/model3d) -* [rmodels] vox_loader (Johann Nadalutti) for models loading (VOX) -* [raudio] dr_wav (David Reid) for WAV audio file loading -* [raudio] dr_flac (David Reid) for FLAC audio file loading -* [raudio] dr_mp3 (David Reid) for MP3 audio file loading -* [raudio] stb_vorbis (Sean Barret) for OGG audio loading -* [raudio] jar_xm (Joshua Reisenauer) for XM audio module loading -* [raudio] jar_mod (Joshua Reisenauer) for MOD audio module loading -* [raudio] qoa (Dominic Szablewski - https://phoboslab.org) for QOA audio manage -* -* -* LICENSE: zlib/libpng -* -* raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, -* BSD-like license that allows static linking with closed source software: -* -* Copyright (c) 2013-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYLIB_H -#define RAYLIB_H - -#include // Required for: va_list - Only used by TraceLogCallback - -#define RAYLIB_VERSION_MAJOR 5 -#define RAYLIB_VERSION_MINOR 5 -#define RAYLIB_VERSION_PATCH 0 -#define RAYLIB_VERSION "5.5" - -// Function specifiers in case library is build/used as a shared library -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -// NOTE: visibility("default") attribute makes symbols "visible" when compiled with -fvisibility=hidden -#if defined(_WIN32) - #if defined(__TINYC__) - #define __declspec(x) __attribute__((x)) - #endif - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) - #elif defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) - #endif -#else - #if defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __attribute__((visibility("default"))) // We are building as a Unix shared library (.so/.dylib) - #endif -#endif - -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -//---------------------------------------------------------------------------------- -// Some basic Defines -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Allow custom memory allocators -// NOTE: Require recompiling raylib sources -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(ptr,sz) realloc(ptr,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(ptr) free(ptr) -#endif - -// NOTE: MSVC C++ compiler does not support compound literals (C99 feature) -// Plain structures in C++ (without constructors) can be initialized with { } -// This is called aggregate initialization (C++11 feature) -#if defined(__cplusplus) - #define CLITERAL(type) type -#else - #define CLITERAL(type) (type) -#endif - -// Some compilers (mostly macos clang) default to C++98, -// where aggregate initialization can't be used -// So, give a more clear error stating how to fix this -#if !defined(_MSC_VER) && (defined(__cplusplus) && __cplusplus < 201103L) - #error "C++11 or later is required. Add -std=c++11" -#endif - -// NOTE: We set some defines with some data types declared by raylib -// Other modules (raymath, rlgl) also require some of those types, so, -// to be able to use those other modules as standalone (not depending on raylib) -// this defines are very useful for internal check and avoid type (re)definitions -#define RL_COLOR_TYPE -#define RL_RECTANGLE_TYPE -#define RL_VECTOR2_TYPE -#define RL_VECTOR3_TYPE -#define RL_VECTOR4_TYPE -#define RL_QUATERNION_TYPE -#define RL_MATRIX_TYPE - -// Some Basic Colors -// NOTE: Custom raylib color palette for amazing visuals on WHITE background -#define LIGHTGRAY CLITERAL(Color){ 200, 200, 200, 255 } // Light Gray -#define GRAY CLITERAL(Color){ 130, 130, 130, 255 } // Gray -#define DARKGRAY CLITERAL(Color){ 80, 80, 80, 255 } // Dark Gray -#define YELLOW CLITERAL(Color){ 253, 249, 0, 255 } // Yellow -#define GOLD CLITERAL(Color){ 255, 203, 0, 255 } // Gold -#define ORANGE CLITERAL(Color){ 255, 161, 0, 255 } // Orange -#define PINK CLITERAL(Color){ 255, 109, 194, 255 } // Pink -#define RED CLITERAL(Color){ 230, 41, 55, 255 } // Red -#define MAROON CLITERAL(Color){ 190, 33, 55, 255 } // Maroon -#define GREEN CLITERAL(Color){ 0, 228, 48, 255 } // Green -#define LIME CLITERAL(Color){ 0, 158, 47, 255 } // Lime -#define DARKGREEN CLITERAL(Color){ 0, 117, 44, 255 } // Dark Green -#define SKYBLUE CLITERAL(Color){ 102, 191, 255, 255 } // Sky Blue -#define BLUE CLITERAL(Color){ 0, 121, 241, 255 } // Blue -#define DARKBLUE CLITERAL(Color){ 0, 82, 172, 255 } // Dark Blue -#define PURPLE CLITERAL(Color){ 200, 122, 255, 255 } // Purple -#define VIOLET CLITERAL(Color){ 135, 60, 190, 255 } // Violet -#define DARKPURPLE CLITERAL(Color){ 112, 31, 126, 255 } // Dark Purple -#define BEIGE CLITERAL(Color){ 211, 176, 131, 255 } // Beige -#define BROWN CLITERAL(Color){ 127, 106, 79, 255 } // Brown -#define DARKBROWN CLITERAL(Color){ 76, 63, 47, 255 } // Dark Brown - -#define WHITE CLITERAL(Color){ 255, 255, 255, 255 } // White -#define BLACK CLITERAL(Color){ 0, 0, 0, 255 } // Black -#define BLANK CLITERAL(Color){ 0, 0, 0, 0 } // Blank (Transparent) -#define MAGENTA CLITERAL(Color){ 255, 0, 255, 255 } // Magenta -#define RAYWHITE CLITERAL(Color){ 245, 245, 245, 255 } // My own White (raylib logo) - -//---------------------------------------------------------------------------------- -// Structures Definition -//---------------------------------------------------------------------------------- -// Boolean type -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) - typedef enum bool { false = 0, true = !false } bool; - #define RL_BOOL_TYPE -#endif - -// Vector2, 2 components -typedef struct Vector2 { - float x; // Vector x component - float y; // Vector y component -} Vector2; - -// Vector3, 3 components -typedef struct Vector3 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component -} Vector3; - -// Vector4, 4 components -typedef struct Vector4 { - float x; // Vector x component - float y; // Vector y component - float z; // Vector z component - float w; // Vector w component -} Vector4; - -// Quaternion, 4 components (Vector4 alias) -typedef Vector4 Quaternion; - -// Matrix, 4x4 components, column major, OpenGL style, right-handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; - -// Color, 4 components, R8G8B8A8 (32bit) -typedef struct Color { - unsigned char r; // Color red value - unsigned char g; // Color green value - unsigned char b; // Color blue value - unsigned char a; // Color alpha value -} Color; - -// Rectangle, 4 components -typedef struct Rectangle { - float x; // Rectangle top-left corner position x - float y; // Rectangle top-left corner position y - float width; // Rectangle width - float height; // Rectangle height -} Rectangle; - -// Image, pixel data stored in CPU memory (RAM) -typedef struct Image { - void *data; // Image raw data - int width; // Image base width - int height; // Image base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Image; - -// Texture, tex data stored in GPU memory (VRAM) -typedef struct Texture { - unsigned int id; // OpenGL texture id - int width; // Texture base width - int height; // Texture base height - int mipmaps; // Mipmap levels, 1 by default - int format; // Data format (PixelFormat type) -} Texture; - -// Texture2D, same as Texture -typedef Texture Texture2D; - -// TextureCubemap, same as Texture -typedef Texture TextureCubemap; - -// RenderTexture, fbo for texture rendering -typedef struct RenderTexture { - unsigned int id; // OpenGL framebuffer object id - Texture texture; // Color buffer attachment texture - Texture depth; // Depth buffer attachment texture -} RenderTexture; - -// RenderTexture2D, same as RenderTexture -typedef RenderTexture RenderTexture2D; - -// NPatchInfo, n-patch layout info -typedef struct NPatchInfo { - Rectangle source; // Texture source rectangle - int left; // Left border offset - int top; // Top border offset - int right; // Right border offset - int bottom; // Bottom border offset - int layout; // Layout of the n-patch: 3x3, 1x3 or 3x1 -} NPatchInfo; - -// GlyphInfo, font characters glyphs info -typedef struct GlyphInfo { - int value; // Character value (Unicode) - int offsetX; // Character offset X when drawing - int offsetY; // Character offset Y when drawing - int advanceX; // Character advance position X - Image image; // Character image data -} GlyphInfo; - -// Font, font texture and GlyphInfo array data -typedef struct Font { - int baseSize; // Base size (default chars height) - int glyphCount; // Number of glyph characters - int glyphPadding; // Padding around the glyph characters - Texture2D texture; // Texture atlas containing the glyphs - Rectangle *recs; // Rectangles in texture for the glyphs - GlyphInfo *glyphs; // Glyphs info data -} Font; - -// Camera, defines position/orientation in 3d space -typedef struct Camera3D { - Vector3 position; // Camera position - Vector3 target; // Camera target it looks-at - Vector3 up; // Camera up vector (rotation over its axis) - float fovy; // Camera field-of-view aperture in Y (degrees) in perspective, used as near plane width in orthographic - int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC -} Camera3D; - -typedef Camera3D Camera; // Camera type fallback, defaults to Camera3D - -// Camera2D, defines position/orientation in 2d space -typedef struct Camera2D { - Vector2 offset; // Camera offset (displacement from target) - Vector2 target; // Camera target (rotation and zoom origin) - float rotation; // Camera rotation in degrees - float zoom; // Camera zoom (scaling), should be 1.0f by default -} Camera2D; - -// Mesh, vertex data and vao/vbo -typedef struct Mesh { - int vertexCount; // Number of vertices stored in arrays - int triangleCount; // Number of triangles stored (indexed or not) - - // Vertex attributes data - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *texcoords2; // Vertex texture second coordinates (UV - 2 components per vertex) (shader-location = 5) - float *normals; // Vertex normals (XYZ - 3 components per vertex) (shader-location = 2) - float *tangents; // Vertex tangents (XYZW - 4 components per vertex) (shader-location = 4) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) - - // Animation vertex data - float *animVertices; // Animated vertex positions (after bones transformations) - float *animNormals; // Animated normals (after bones transformations) - unsigned char *boneIds; // Vertex bone ids, max 255 bone ids, up to 4 bones influence by vertex (skinning) (shader-location = 6) - float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) (shader-location = 7) - Matrix *boneMatrices; // Bones animated transformation matrices - int boneCount; // Number of bones - - // OpenGL identifiers - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int *vboId; // OpenGL Vertex Buffer Objects id (default vertex data) -} Mesh; - -// Shader -typedef struct Shader { - unsigned int id; // Shader program id - int *locs; // Shader locations array (RL_MAX_SHADER_LOCATIONS) -} Shader; - -// MaterialMap -typedef struct MaterialMap { - Texture2D texture; // Material map texture - Color color; // Material map color - float value; // Material map value -} MaterialMap; - -// Material, includes shader and maps -typedef struct Material { - Shader shader; // Material shader - MaterialMap *maps; // Material maps array (MAX_MATERIAL_MAPS) - float params[4]; // Material generic parameters (if required) -} Material; - -// Transform, vertex transformation data -typedef struct Transform { - Vector3 translation; // Translation - Quaternion rotation; // Rotation - Vector3 scale; // Scale -} Transform; - -// Bone, skeletal animation bone -typedef struct BoneInfo { - char name[32]; // Bone name - int parent; // Bone parent -} BoneInfo; - -// Model, meshes, materials and animation data -typedef struct Model { - Matrix transform; // Local transform matrix - - int meshCount; // Number of meshes - int materialCount; // Number of materials - Mesh *meshes; // Meshes array - Material *materials; // Materials array - int *meshMaterial; // Mesh material number - - // Animation data - int boneCount; // Number of bones - BoneInfo *bones; // Bones information (skeleton) - Transform *bindPose; // Bones base transformation (pose) -} Model; - -// ModelAnimation -typedef struct ModelAnimation { - int boneCount; // Number of bones - int frameCount; // Number of animation frames - BoneInfo *bones; // Bones information (skeleton) - Transform **framePoses; // Poses array by frame - char name[32]; // Animation name -} ModelAnimation; - -// Ray, ray for raycasting -typedef struct Ray { - Vector3 position; // Ray position (origin) - Vector3 direction; // Ray direction (normalized) -} Ray; - -// RayCollision, ray hit information -typedef struct RayCollision { - bool hit; // Did the ray hit something? - float distance; // Distance to the nearest hit - Vector3 point; // Point of the nearest hit - Vector3 normal; // Surface normal of hit -} RayCollision; - -// BoundingBox -typedef struct BoundingBox { - Vector3 min; // Minimum vertex box-corner - Vector3 max; // Maximum vertex box-corner -} BoundingBox; - -// Wave, audio wave data -typedef struct Wave { - unsigned int frameCount; // Total number of frames (considering channels) - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) - void *data; // Buffer data pointer -} Wave; - -// Opaque structs declaration -// NOTE: Actual structs are defined internally in raudio module -typedef struct rAudioBuffer rAudioBuffer; -typedef struct rAudioProcessor rAudioProcessor; - -// AudioStream, custom audio stream -typedef struct AudioStream { - rAudioBuffer *buffer; // Pointer to internal data used by the audio system - rAudioProcessor *processor; // Pointer to internal data processor, useful for audio effects - - unsigned int sampleRate; // Frequency (samples per second) - unsigned int sampleSize; // Bit depth (bits per sample): 8, 16, 32 (24 not supported) - unsigned int channels; // Number of channels (1-mono, 2-stereo, ...) -} AudioStream; - -// Sound -typedef struct Sound { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) -} Sound; - -// Music, audio stream, anything longer than ~10 seconds should be streamed -typedef struct Music { - AudioStream stream; // Audio stream - unsigned int frameCount; // Total number of frames (considering channels) - bool looping; // Music looping enable - - int ctxType; // Type of music context (audio filetype) - void *ctxData; // Audio context data, depends on type -} Music; - -// VrDeviceInfo, Head-Mounted-Display device parameters -typedef struct VrDeviceInfo { - int hResolution; // Horizontal resolution in pixels - int vResolution; // Vertical resolution in pixels - float hScreenSize; // Horizontal size in meters - float vScreenSize; // Vertical size in meters - float eyeToScreenDistance; // Distance between eye and display in meters - float lensSeparationDistance; // Lens separation distance in meters - float interpupillaryDistance; // IPD (distance between pupils) in meters - float lensDistortionValues[4]; // Lens distortion constant parameters - float chromaAbCorrection[4]; // Chromatic aberration correction parameters -} VrDeviceInfo; - -// VrStereoConfig, VR stereo rendering configuration for simulator -typedef struct VrStereoConfig { - Matrix projection[2]; // VR projection matrices (per eye) - Matrix viewOffset[2]; // VR view offset matrices (per eye) - float leftLensCenter[2]; // VR left lens center - float rightLensCenter[2]; // VR right lens center - float leftScreenCenter[2]; // VR left screen center - float rightScreenCenter[2]; // VR right screen center - float scale[2]; // VR distortion scale - float scaleIn[2]; // VR distortion scale in -} VrStereoConfig; - -// File path list -typedef struct FilePathList { - unsigned int capacity; // Filepaths max entries - unsigned int count; // Filepaths entries count - char **paths; // Filepaths entries -} FilePathList; - -// Automation event -typedef struct AutomationEvent { - unsigned int frame; // Event frame - unsigned int type; // Event type (AutomationEventType) - int params[4]; // Event parameters (if required) -} AutomationEvent; - -// Automation event list -typedef struct AutomationEventList { - unsigned int capacity; // Events max entries (MAX_AUTOMATION_EVENTS) - unsigned int count; // Events entries count - AutomationEvent *events; // Events entries -} AutomationEventList; - -//---------------------------------------------------------------------------------- -// Enumerators Definition -//---------------------------------------------------------------------------------- -// System/Window config flags -// NOTE: Every bit registers one state (use it with bit masks) -// By default all flags are set to 0 -typedef enum { - FLAG_VSYNC_HINT = 0x00000040, // Set to try enabling V-Sync on GPU - FLAG_FULLSCREEN_MODE = 0x00000002, // Set to run program in fullscreen - FLAG_WINDOW_RESIZABLE = 0x00000004, // Set to allow resizable window - FLAG_WINDOW_UNDECORATED = 0x00000008, // Set to disable window decoration (frame and buttons) - FLAG_WINDOW_HIDDEN = 0x00000080, // Set to hide window - FLAG_WINDOW_MINIMIZED = 0x00000200, // Set to minimize window (iconify) - FLAG_WINDOW_MAXIMIZED = 0x00000400, // Set to maximize window (expanded to monitor) - FLAG_WINDOW_UNFOCUSED = 0x00000800, // Set to window non focused - FLAG_WINDOW_TOPMOST = 0x00001000, // Set to window always on top - FLAG_WINDOW_ALWAYS_RUN = 0x00000100, // Set to allow windows running while minimized - FLAG_WINDOW_TRANSPARENT = 0x00000010, // Set to allow transparent framebuffer - FLAG_WINDOW_HIGHDPI = 0x00002000, // Set to support HighDPI - FLAG_WINDOW_MOUSE_PASSTHROUGH = 0x00004000, // Set to support mouse passthrough, only supported when FLAG_WINDOW_UNDECORATED - FLAG_BORDERLESS_WINDOWED_MODE = 0x00008000, // Set to run program in borderless windowed mode - FLAG_MSAA_4X_HINT = 0x00000020, // Set to try enabling MSAA 4X - FLAG_INTERLACED_HINT = 0x00010000 // Set to try enabling interlaced video format (for V3D) -} ConfigFlags; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - LOG_ALL = 0, // Display all logs - LOG_TRACE, // Trace logging, intended for internal use only - LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - LOG_INFO, // Info logging, used for program execution info - LOG_WARNING, // Warning logging, used on recoverable failures - LOG_ERROR, // Error logging, used on unrecoverable failures - LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - LOG_NONE // Disable logging -} TraceLogLevel; - -// Keyboard keys (US keyboard layout) -// NOTE: Use GetKeyPressed() to allow redefining -// required keys for alternative layouts -typedef enum { - KEY_NULL = 0, // Key: NULL, used for no key pressed - // Alphanumeric keys - KEY_APOSTROPHE = 39, // Key: ' - KEY_COMMA = 44, // Key: , - KEY_MINUS = 45, // Key: - - KEY_PERIOD = 46, // Key: . - KEY_SLASH = 47, // Key: / - KEY_ZERO = 48, // Key: 0 - KEY_ONE = 49, // Key: 1 - KEY_TWO = 50, // Key: 2 - KEY_THREE = 51, // Key: 3 - KEY_FOUR = 52, // Key: 4 - KEY_FIVE = 53, // Key: 5 - KEY_SIX = 54, // Key: 6 - KEY_SEVEN = 55, // Key: 7 - KEY_EIGHT = 56, // Key: 8 - KEY_NINE = 57, // Key: 9 - KEY_SEMICOLON = 59, // Key: ; - KEY_EQUAL = 61, // Key: = - KEY_A = 65, // Key: A | a - KEY_B = 66, // Key: B | b - KEY_C = 67, // Key: C | c - KEY_D = 68, // Key: D | d - KEY_E = 69, // Key: E | e - KEY_F = 70, // Key: F | f - KEY_G = 71, // Key: G | g - KEY_H = 72, // Key: H | h - KEY_I = 73, // Key: I | i - KEY_J = 74, // Key: J | j - KEY_K = 75, // Key: K | k - KEY_L = 76, // Key: L | l - KEY_M = 77, // Key: M | m - KEY_N = 78, // Key: N | n - KEY_O = 79, // Key: O | o - KEY_P = 80, // Key: P | p - KEY_Q = 81, // Key: Q | q - KEY_R = 82, // Key: R | r - KEY_S = 83, // Key: S | s - KEY_T = 84, // Key: T | t - KEY_U = 85, // Key: U | u - KEY_V = 86, // Key: V | v - KEY_W = 87, // Key: W | w - KEY_X = 88, // Key: X | x - KEY_Y = 89, // Key: Y | y - KEY_Z = 90, // Key: Z | z - KEY_LEFT_BRACKET = 91, // Key: [ - KEY_BACKSLASH = 92, // Key: '\' - KEY_RIGHT_BRACKET = 93, // Key: ] - KEY_GRAVE = 96, // Key: ` - // Function keys - KEY_SPACE = 32, // Key: Space - KEY_ESCAPE = 256, // Key: Esc - KEY_ENTER = 257, // Key: Enter - KEY_TAB = 258, // Key: Tab - KEY_BACKSPACE = 259, // Key: Backspace - KEY_INSERT = 260, // Key: Ins - KEY_DELETE = 261, // Key: Del - KEY_RIGHT = 262, // Key: Cursor right - KEY_LEFT = 263, // Key: Cursor left - KEY_DOWN = 264, // Key: Cursor down - KEY_UP = 265, // Key: Cursor up - KEY_PAGE_UP = 266, // Key: Page up - KEY_PAGE_DOWN = 267, // Key: Page down - KEY_HOME = 268, // Key: Home - KEY_END = 269, // Key: End - KEY_CAPS_LOCK = 280, // Key: Caps lock - KEY_SCROLL_LOCK = 281, // Key: Scroll down - KEY_NUM_LOCK = 282, // Key: Num lock - KEY_PRINT_SCREEN = 283, // Key: Print screen - KEY_PAUSE = 284, // Key: Pause - KEY_F1 = 290, // Key: F1 - KEY_F2 = 291, // Key: F2 - KEY_F3 = 292, // Key: F3 - KEY_F4 = 293, // Key: F4 - KEY_F5 = 294, // Key: F5 - KEY_F6 = 295, // Key: F6 - KEY_F7 = 296, // Key: F7 - KEY_F8 = 297, // Key: F8 - KEY_F9 = 298, // Key: F9 - KEY_F10 = 299, // Key: F10 - KEY_F11 = 300, // Key: F11 - KEY_F12 = 301, // Key: F12 - KEY_LEFT_SHIFT = 340, // Key: Shift left - KEY_LEFT_CONTROL = 341, // Key: Control left - KEY_LEFT_ALT = 342, // Key: Alt left - KEY_LEFT_SUPER = 343, // Key: Super left - KEY_RIGHT_SHIFT = 344, // Key: Shift right - KEY_RIGHT_CONTROL = 345, // Key: Control right - KEY_RIGHT_ALT = 346, // Key: Alt right - KEY_RIGHT_SUPER = 347, // Key: Super right - KEY_KB_MENU = 348, // Key: KB menu - // Keypad keys - KEY_KP_0 = 320, // Key: Keypad 0 - KEY_KP_1 = 321, // Key: Keypad 1 - KEY_KP_2 = 322, // Key: Keypad 2 - KEY_KP_3 = 323, // Key: Keypad 3 - KEY_KP_4 = 324, // Key: Keypad 4 - KEY_KP_5 = 325, // Key: Keypad 5 - KEY_KP_6 = 326, // Key: Keypad 6 - KEY_KP_7 = 327, // Key: Keypad 7 - KEY_KP_8 = 328, // Key: Keypad 8 - KEY_KP_9 = 329, // Key: Keypad 9 - KEY_KP_DECIMAL = 330, // Key: Keypad . - KEY_KP_DIVIDE = 331, // Key: Keypad / - KEY_KP_MULTIPLY = 332, // Key: Keypad * - KEY_KP_SUBTRACT = 333, // Key: Keypad - - KEY_KP_ADD = 334, // Key: Keypad + - KEY_KP_ENTER = 335, // Key: Keypad Enter - KEY_KP_EQUAL = 336, // Key: Keypad = - // Android key buttons - KEY_BACK = 4, // Key: Android back button - KEY_MENU = 5, // Key: Android menu button - KEY_VOLUME_UP = 24, // Key: Android volume up button - KEY_VOLUME_DOWN = 25 // Key: Android volume down button -} KeyboardKey; - -// Add backwards compatibility support for deprecated names -#define MOUSE_LEFT_BUTTON MOUSE_BUTTON_LEFT -#define MOUSE_RIGHT_BUTTON MOUSE_BUTTON_RIGHT -#define MOUSE_MIDDLE_BUTTON MOUSE_BUTTON_MIDDLE - -// Mouse buttons -typedef enum { - MOUSE_BUTTON_LEFT = 0, // Mouse button left - MOUSE_BUTTON_RIGHT = 1, // Mouse button right - MOUSE_BUTTON_MIDDLE = 2, // Mouse button middle (pressed wheel) - MOUSE_BUTTON_SIDE = 3, // Mouse button side (advanced mouse device) - MOUSE_BUTTON_EXTRA = 4, // Mouse button extra (advanced mouse device) - MOUSE_BUTTON_FORWARD = 5, // Mouse button forward (advanced mouse device) - MOUSE_BUTTON_BACK = 6, // Mouse button back (advanced mouse device) -} MouseButton; - -// Mouse cursor -typedef enum { - MOUSE_CURSOR_DEFAULT = 0, // Default pointer shape - MOUSE_CURSOR_ARROW = 1, // Arrow shape - MOUSE_CURSOR_IBEAM = 2, // Text writing cursor shape - MOUSE_CURSOR_CROSSHAIR = 3, // Cross shape - MOUSE_CURSOR_POINTING_HAND = 4, // Pointing hand cursor - MOUSE_CURSOR_RESIZE_EW = 5, // Horizontal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NS = 6, // Vertical resize/move arrow shape - MOUSE_CURSOR_RESIZE_NWSE = 7, // Top-left to bottom-right diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_NESW = 8, // The top-right to bottom-left diagonal resize/move arrow shape - MOUSE_CURSOR_RESIZE_ALL = 9, // The omnidirectional resize/move cursor shape - MOUSE_CURSOR_NOT_ALLOWED = 10 // The operation-not-allowed shape -} MouseCursor; - -// Gamepad buttons -typedef enum { - GAMEPAD_BUTTON_UNKNOWN = 0, // Unknown button, just for error checking - GAMEPAD_BUTTON_LEFT_FACE_UP, // Gamepad left DPAD up button - GAMEPAD_BUTTON_LEFT_FACE_RIGHT, // Gamepad left DPAD right button - GAMEPAD_BUTTON_LEFT_FACE_DOWN, // Gamepad left DPAD down button - GAMEPAD_BUTTON_LEFT_FACE_LEFT, // Gamepad left DPAD left button - GAMEPAD_BUTTON_RIGHT_FACE_UP, // Gamepad right button up (i.e. PS3: Triangle, Xbox: Y) - GAMEPAD_BUTTON_RIGHT_FACE_RIGHT, // Gamepad right button right (i.e. PS3: Circle, Xbox: B) - GAMEPAD_BUTTON_RIGHT_FACE_DOWN, // Gamepad right button down (i.e. PS3: Cross, Xbox: A) - GAMEPAD_BUTTON_RIGHT_FACE_LEFT, // Gamepad right button left (i.e. PS3: Square, Xbox: X) - GAMEPAD_BUTTON_LEFT_TRIGGER_1, // Gamepad top/back trigger left (first), it could be a trailing button - GAMEPAD_BUTTON_LEFT_TRIGGER_2, // Gamepad top/back trigger left (second), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_1, // Gamepad top/back trigger right (first), it could be a trailing button - GAMEPAD_BUTTON_RIGHT_TRIGGER_2, // Gamepad top/back trigger right (second), it could be a trailing button - GAMEPAD_BUTTON_MIDDLE_LEFT, // Gamepad center buttons, left one (i.e. PS3: Select) - GAMEPAD_BUTTON_MIDDLE, // Gamepad center buttons, middle one (i.e. PS3: PS, Xbox: XBOX) - GAMEPAD_BUTTON_MIDDLE_RIGHT, // Gamepad center buttons, right one (i.e. PS3: Start) - GAMEPAD_BUTTON_LEFT_THUMB, // Gamepad joystick pressed button left - GAMEPAD_BUTTON_RIGHT_THUMB // Gamepad joystick pressed button right -} GamepadButton; - -// Gamepad axis -typedef enum { - GAMEPAD_AXIS_LEFT_X = 0, // Gamepad left stick X axis - GAMEPAD_AXIS_LEFT_Y = 1, // Gamepad left stick Y axis - GAMEPAD_AXIS_RIGHT_X = 2, // Gamepad right stick X axis - GAMEPAD_AXIS_RIGHT_Y = 3, // Gamepad right stick Y axis - GAMEPAD_AXIS_LEFT_TRIGGER = 4, // Gamepad back trigger left, pressure level: [1..-1] - GAMEPAD_AXIS_RIGHT_TRIGGER = 5 // Gamepad back trigger right, pressure level: [1..-1] -} GamepadAxis; - -// Material map index -typedef enum { - MATERIAL_MAP_ALBEDO = 0, // Albedo material (same as: MATERIAL_MAP_DIFFUSE) - MATERIAL_MAP_METALNESS, // Metalness material (same as: MATERIAL_MAP_SPECULAR) - MATERIAL_MAP_NORMAL, // Normal material - MATERIAL_MAP_ROUGHNESS, // Roughness material - MATERIAL_MAP_OCCLUSION, // Ambient occlusion material - MATERIAL_MAP_EMISSION, // Emission material - MATERIAL_MAP_HEIGHT, // Heightmap material - MATERIAL_MAP_CUBEMAP, // Cubemap material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_IRRADIANCE, // Irradiance material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_PREFILTER, // Prefilter material (NOTE: Uses GL_TEXTURE_CUBE_MAP) - MATERIAL_MAP_BRDF // Brdf material -} MaterialMapIndex; - -#define MATERIAL_MAP_DIFFUSE MATERIAL_MAP_ALBEDO -#define MATERIAL_MAP_SPECULAR MATERIAL_MAP_METALNESS - -// Shader location index -typedef enum { - SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: SHADER_LOC_MAP_DIFFUSE) - SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: SHADER_LOC_MAP_SPECULAR) - SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - SHADER_LOC_MAP_BRDF, // Shader location: sampler2d texture: brdf - SHADER_LOC_VERTEX_BONEIDS, // Shader location: vertex attribute: boneIds - SHADER_LOC_VERTEX_BONEWEIGHTS, // Shader location: vertex attribute: boneWeights - SHADER_LOC_BONE_MATRICES // Shader location: array of matrices uniform: boneMatrices -} ShaderLocationIndex; - -#define SHADER_LOC_MAP_DIFFUSE SHADER_LOC_MAP_ALBEDO -#define SHADER_LOC_MAP_SPECULAR SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - SHADER_UNIFORM_INT, // Shader uniform type: int - SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} ShaderUniformDataType; - -// Shader attribute data types -typedef enum { - SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} ShaderAttributeDataType; - -// Pixel formats -// NOTE: Support depends on OpenGL version and platform -typedef enum { - PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} PixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - TEXTURE_FILTER_BILINEAR, // Linear filtering - TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} TextureFilter; - -// Texture parameters: wrap mode -typedef enum { - TEXTURE_WRAP_REPEAT = 0, // Repeats texture in tiled mode - TEXTURE_WRAP_CLAMP, // Clamps texture to edge pixel in tiled mode - TEXTURE_WRAP_MIRROR_REPEAT, // Mirrors and repeats the texture in tiled mode - TEXTURE_WRAP_MIRROR_CLAMP // Mirrors and clamps to border the texture in tiled mode -} TextureWrap; - -// Cubemap layouts -typedef enum { - CUBEMAP_LAYOUT_AUTO_DETECT = 0, // Automatically detect layout type - CUBEMAP_LAYOUT_LINE_VERTICAL, // Layout is defined by a vertical line with faces - CUBEMAP_LAYOUT_LINE_HORIZONTAL, // Layout is defined by a horizontal line with faces - CUBEMAP_LAYOUT_CROSS_THREE_BY_FOUR, // Layout is defined by a 3x4 cross with cubemap faces - CUBEMAP_LAYOUT_CROSS_FOUR_BY_THREE // Layout is defined by a 4x3 cross with cubemap faces -} CubemapLayout; - -// Font type, defines generation method -typedef enum { - FONT_DEFAULT = 0, // Default font generation, anti-aliased - FONT_BITMAP, // Bitmap font generation, no anti-aliasing - FONT_SDF // SDF font generation, requires external shader -} FontType; - -// Color blending modes (pre-defined) -typedef enum { - BLEND_ALPHA = 0, // Blend textures considering alpha (default) - BLEND_ADDITIVE, // Blend textures adding colors - BLEND_MULTIPLIED, // Blend textures multiplying colors - BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - BLEND_CUSTOM_SEPARATE // Blend textures using custom rgb/alpha separate src/dst factors (use rlSetBlendFactorsSeparate()) -} BlendMode; - -// Gesture -// NOTE: Provided as bit-wise flags to enable only desired gestures -typedef enum { - GESTURE_NONE = 0, // No gesture - GESTURE_TAP = 1, // Tap gesture - GESTURE_DOUBLETAP = 2, // Double tap gesture - GESTURE_HOLD = 4, // Hold gesture - GESTURE_DRAG = 8, // Drag gesture - GESTURE_SWIPE_RIGHT = 16, // Swipe right gesture - GESTURE_SWIPE_LEFT = 32, // Swipe left gesture - GESTURE_SWIPE_UP = 64, // Swipe up gesture - GESTURE_SWIPE_DOWN = 128, // Swipe down gesture - GESTURE_PINCH_IN = 256, // Pinch in gesture - GESTURE_PINCH_OUT = 512 // Pinch out gesture -} Gesture; - -// Camera system modes -typedef enum { - CAMERA_CUSTOM = 0, // Camera custom, controlled by user (UpdateCamera() does nothing) - CAMERA_FREE, // Camera free mode - CAMERA_ORBITAL, // Camera orbital, around target, zoom supported - CAMERA_FIRST_PERSON, // Camera first person - CAMERA_THIRD_PERSON // Camera third person -} CameraMode; - -// Camera projection -typedef enum { - CAMERA_PERSPECTIVE = 0, // Perspective projection - CAMERA_ORTHOGRAPHIC // Orthographic projection -} CameraProjection; - -// N-patch layout -typedef enum { - NPATCH_NINE_PATCH = 0, // Npatch layout: 3x3 tiles - NPATCH_THREE_PATCH_VERTICAL, // Npatch layout: 1x3 tiles - NPATCH_THREE_PATCH_HORIZONTAL // Npatch layout: 3x1 tiles -} NPatchLayout; - -// Callbacks to hook some internal functions -// WARNING: These callbacks are intended for advanced users -typedef void (*TraceLogCallback)(int logLevel, const char *text, va_list args); // Logging: Redirect trace log messages -typedef unsigned char *(*LoadFileDataCallback)(const char *fileName, int *dataSize); // FileIO: Load binary data -typedef bool (*SaveFileDataCallback)(const char *fileName, void *data, int dataSize); // FileIO: Save binary data -typedef char *(*LoadFileTextCallback)(const char *fileName); // FileIO: Load text data -typedef bool (*SaveFileTextCallback)(const char *fileName, char *text); // FileIO: Save text data - -//------------------------------------------------------------------------------------ -// Global Variables Definition -//------------------------------------------------------------------------------------ -// It's lonely here... - -//------------------------------------------------------------------------------------ -// Window and Graphics Device Functions (Module: core) -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -// Window-related functions -RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context -RLAPI void CloseWindow(void); // Close window and unload OpenGL context -RLAPI bool WindowShouldClose(void); // Check if application should close (KEY_ESCAPE pressed or windows close icon clicked) -RLAPI bool IsWindowReady(void); // Check if window has been initialized successfully -RLAPI bool IsWindowFullscreen(void); // Check if window is currently fullscreen -RLAPI bool IsWindowHidden(void); // Check if window is currently hidden -RLAPI bool IsWindowMinimized(void); // Check if window is currently minimized -RLAPI bool IsWindowMaximized(void); // Check if window is currently maximized -RLAPI bool IsWindowFocused(void); // Check if window is currently focused -RLAPI bool IsWindowResized(void); // Check if window has been resized last frame -RLAPI bool IsWindowState(unsigned int flag); // Check if one specific window flag is enabled -RLAPI void SetWindowState(unsigned int flags); // Set window configuration state using flags -RLAPI void ClearWindowState(unsigned int flags); // Clear window configuration state flags -RLAPI void ToggleFullscreen(void); // Toggle window state: fullscreen/windowed, resizes monitor to match window resolution -RLAPI void ToggleBorderlessWindowed(void); // Toggle window state: borderless windowed, resizes window to match monitor resolution -RLAPI void MaximizeWindow(void); // Set window state: maximized, if resizable -RLAPI void MinimizeWindow(void); // Set window state: minimized, if resizable -RLAPI void RestoreWindow(void); // Set window state: not minimized/maximized -RLAPI void SetWindowIcon(Image image); // Set icon for window (single image, RGBA 32bit) -RLAPI void SetWindowIcons(Image *images, int count); // Set icon for window (multiple images, RGBA 32bit) -RLAPI void SetWindowTitle(const char *title); // Set title for window -RLAPI void SetWindowPosition(int x, int y); // Set window position on screen -RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window -RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowMaxSize(int width, int height); // Set window maximum dimensions (for FLAG_WINDOW_RESIZABLE) -RLAPI void SetWindowSize(int width, int height); // Set window dimensions -RLAPI void SetWindowOpacity(float opacity); // Set window opacity [0.0f..1.0f] -RLAPI void SetWindowFocused(void); // Set window focused -RLAPI void *GetWindowHandle(void); // Get native window handle -RLAPI int GetScreenWidth(void); // Get current screen width -RLAPI int GetScreenHeight(void); // Get current screen height -RLAPI int GetRenderWidth(void); // Get current render width (it considers HiDPI) -RLAPI int GetRenderHeight(void); // Get current render height (it considers HiDPI) -RLAPI int GetMonitorCount(void); // Get number of connected monitors -RLAPI int GetCurrentMonitor(void); // Get current monitor where window is placed -RLAPI Vector2 GetMonitorPosition(int monitor); // Get specified monitor position -RLAPI int GetMonitorWidth(int monitor); // Get specified monitor width (current video mode used by monitor) -RLAPI int GetMonitorHeight(int monitor); // Get specified monitor height (current video mode used by monitor) -RLAPI int GetMonitorPhysicalWidth(int monitor); // Get specified monitor physical width in millimetres -RLAPI int GetMonitorPhysicalHeight(int monitor); // Get specified monitor physical height in millimetres -RLAPI int GetMonitorRefreshRate(int monitor); // Get specified monitor refresh rate -RLAPI Vector2 GetWindowPosition(void); // Get window position XY on monitor -RLAPI Vector2 GetWindowScaleDPI(void); // Get window scale DPI factor -RLAPI const char *GetMonitorName(int monitor); // Get the human-readable, UTF-8 encoded name of the specified monitor -RLAPI void SetClipboardText(const char *text); // Set clipboard text content -RLAPI const char *GetClipboardText(void); // Get clipboard text content -RLAPI Image GetClipboardImage(void); // Get clipboard image content -RLAPI void EnableEventWaiting(void); // Enable waiting for events on EndDrawing(), no automatic event polling -RLAPI void DisableEventWaiting(void); // Disable waiting for events on EndDrawing(), automatic events polling - -// Cursor-related functions -RLAPI void ShowCursor(void); // Shows cursor -RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Check if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) -RLAPI void DisableCursor(void); // Disables cursor (lock cursor) -RLAPI bool IsCursorOnScreen(void); // Check if cursor is on the screen - -// Drawing-related functions -RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) -RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void BeginMode2D(Camera2D camera); // Begin 2D mode with custom camera (2D) -RLAPI void EndMode2D(void); // Ends 2D mode with custom camera -RLAPI void BeginMode3D(Camera3D camera); // Begin 3D mode with custom camera (3D) -RLAPI void EndMode3D(void); // Ends 3D mode and returns to default 2D orthographic mode -RLAPI void BeginTextureMode(RenderTexture2D target); // Begin drawing to render texture -RLAPI void EndTextureMode(void); // Ends drawing to render texture -RLAPI void BeginShaderMode(Shader shader); // Begin custom shader drawing -RLAPI void EndShaderMode(void); // End custom shader drawing (use default shader) -RLAPI void BeginBlendMode(int mode); // Begin blending mode (alpha, additive, multiplied, subtract, custom) -RLAPI void EndBlendMode(void); // End blending mode (reset to default: alpha blending) -RLAPI void BeginScissorMode(int x, int y, int width, int height); // Begin scissor mode (define screen area for following drawing) -RLAPI void EndScissorMode(void); // End scissor mode -RLAPI void BeginVrStereoMode(VrStereoConfig config); // Begin stereo rendering (requires VR simulator) -RLAPI void EndVrStereoMode(void); // End stereo rendering (requires VR simulator) - -// VR stereo config functions for VR simulator -RLAPI VrStereoConfig LoadVrStereoConfig(VrDeviceInfo device); // Load VR stereo config for VR simulator device parameters -RLAPI void UnloadVrStereoConfig(VrStereoConfig config); // Unload VR stereo config - -// Shader management functions -// NOTE: Shader functionality is not available on OpenGL 1.1 -RLAPI Shader LoadShader(const char *vsFileName, const char *fsFileName); // Load shader from files and bind default locations -RLAPI Shader LoadShaderFromMemory(const char *vsCode, const char *fsCode); // Load shader from code strings and bind default locations -RLAPI bool IsShaderValid(Shader shader); // Check if a shader is valid (loaded on GPU) -RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location -RLAPI int GetShaderLocationAttrib(Shader shader, const char *attribName); // Get shader attribute location -RLAPI void SetShaderValue(Shader shader, int locIndex, const void *value, int uniformType); // Set shader uniform value -RLAPI void SetShaderValueV(Shader shader, int locIndex, const void *value, int uniformType, int count); // Set shader uniform value vector -RLAPI void SetShaderValueMatrix(Shader shader, int locIndex, Matrix mat); // Set shader uniform value (matrix 4x4) -RLAPI void SetShaderValueTexture(Shader shader, int locIndex, Texture2D texture); // Set shader uniform value for texture (sampler2d) -RLAPI void UnloadShader(Shader shader); // Unload shader from GPU memory (VRAM) - -// Screen-space-related functions -#define GetMouseRay GetScreenToWorldRay // Compatibility hack for previous raylib versions -RLAPI Ray GetScreenToWorldRay(Vector2 position, Camera camera); // Get a ray trace from screen position (i.e mouse) -RLAPI Ray GetScreenToWorldRayEx(Vector2 position, Camera camera, int width, int height); // Get a ray trace from screen position (i.e mouse) in a viewport -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Get the screen space position for a 3d world space position -RLAPI Vector2 GetWorldToScreenEx(Vector3 position, Camera camera, int width, int height); // Get size position for a 3d world space position -RLAPI Vector2 GetWorldToScreen2D(Vector2 position, Camera2D camera); // Get the screen space position for a 2d camera world space position -RLAPI Vector2 GetScreenToWorld2D(Vector2 position, Camera2D camera); // Get the world space position for a 2d camera screen space position -RLAPI Matrix GetCameraMatrix(Camera camera); // Get camera transform matrix (view matrix) -RLAPI Matrix GetCameraMatrix2D(Camera2D camera); // Get camera 2d transform matrix - -// Timing-related functions -RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) -RLAPI float GetFrameTime(void); // Get time in seconds for last frame drawn (delta time) -RLAPI double GetTime(void); // Get elapsed time in seconds since InitWindow() -RLAPI int GetFPS(void); // Get current FPS - -// Custom frame control functions -// NOTE: Those functions are intended for advanced users that want full control over the frame processing -// By default EndDrawing() does this job: draws everything + SwapScreenBuffer() + manage frame timing + PollInputEvents() -// To avoid that behaviour and control frame processes manually, enable in config.h: SUPPORT_CUSTOM_FRAME_CONTROL -RLAPI void SwapScreenBuffer(void); // Swap back buffer with front buffer (screen drawing) -RLAPI void PollInputEvents(void); // Register all input events -RLAPI void WaitTime(double seconds); // Wait for some time (halt program execution) - -// Random values generation functions -RLAPI void SetRandomSeed(unsigned int seed); // Set the seed for the random number generator -RLAPI int GetRandomValue(int min, int max); // Get a random value between min and max (both included) -RLAPI int *LoadRandomSequence(unsigned int count, int min, int max); // Load random values sequence, no values repeated -RLAPI void UnloadRandomSequence(int *sequence); // Unload random values sequence - -// Misc. functions -RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (filename extension defines format) -RLAPI void SetConfigFlags(unsigned int flags); // Setup init configuration flags (view FLAGS) -RLAPI void OpenURL(const char *url); // Open URL with default system browser (if available) - -// NOTE: Following functions implemented in module [utils] -//------------------------------------------------------------------ -RLAPI void TraceLog(int logLevel, const char *text, ...); // Show trace log messages (LOG_DEBUG, LOG_INFO, LOG_WARNING, LOG_ERROR...) -RLAPI void SetTraceLogLevel(int logLevel); // Set the current threshold (minimum) log level -RLAPI void *MemAlloc(unsigned int size); // Internal memory allocator -RLAPI void *MemRealloc(void *ptr, unsigned int size); // Internal memory reallocator -RLAPI void MemFree(void *ptr); // Internal memory free - -// Set custom callbacks -// WARNING: Callbacks setup is intended for advanced users -RLAPI void SetTraceLogCallback(TraceLogCallback callback); // Set custom trace log -RLAPI void SetLoadFileDataCallback(LoadFileDataCallback callback); // Set custom file binary data loader -RLAPI void SetSaveFileDataCallback(SaveFileDataCallback callback); // Set custom file binary data saver -RLAPI void SetLoadFileTextCallback(LoadFileTextCallback callback); // Set custom file text data loader -RLAPI void SetSaveFileTextCallback(SaveFileTextCallback callback); // Set custom file text data saver - -// Files management functions -RLAPI unsigned char *LoadFileData(const char *fileName, int *dataSize); // Load file data as byte array (read) -RLAPI void UnloadFileData(unsigned char *data); // Unload file data allocated by LoadFileData() -RLAPI bool SaveFileData(const char *fileName, void *data, int dataSize); // Save data to file from byte array (write), returns true on success -RLAPI bool ExportDataAsCode(const unsigned char *data, int dataSize, const char *fileName); // Export data to code (.h), returns true on success -RLAPI char *LoadFileText(const char *fileName); // Load text data from file (read), returns a '\0' terminated string -RLAPI void UnloadFileText(char *text); // Unload file text data allocated by LoadFileText() -RLAPI bool SaveFileText(const char *fileName, char *text); // Save text data to file (write), string must be '\0' terminated, returns true on success -//------------------------------------------------------------------ - -// File system functions -RLAPI bool FileExists(const char *fileName); // Check if file exists -RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists -RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (including point: .png, .wav) -RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h) -RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png') -RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string -RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string) -RLAPI const char *GetDirectoryPath(const char *filePath); // Get full path for a given fileName with path (uses static string) -RLAPI const char *GetPrevDirectoryPath(const char *dirPath); // Get previous directory path for a given path (uses static string) -RLAPI const char *GetWorkingDirectory(void); // Get current working directory (uses static string) -RLAPI const char *GetApplicationDirectory(void); // Get the directory of the running application (uses static string) -RLAPI int MakeDirectory(const char *dirPath); // Create directories (including full path requested), returns 0 on success -RLAPI bool ChangeDirectory(const char *dir); // Change working directory, return true on success -RLAPI bool IsPathFile(const char *path); // Check if a given path is a file or a directory -RLAPI bool IsFileNameValid(const char *fileName); // Check if fileName is valid for the platform/OS -RLAPI FilePathList LoadDirectoryFiles(const char *dirPath); // Load directory filepaths -RLAPI FilePathList LoadDirectoryFilesEx(const char *basePath, const char *filter, bool scanSubdirs); // Load directory filepaths with extension filtering and recursive directory scan. Use 'DIR' in the filter string to include directories in the result -RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload filepaths -RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window -RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths -RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths -RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time) - -// Compression/Encoding functionality -RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree() -RLAPI unsigned char *DecompressData(const unsigned char *compData, int compDataSize, int *dataSize); // Decompress data (DEFLATE algorithm), memory must be MemFree() -RLAPI char *EncodeDataBase64(const unsigned char *data, int dataSize, int *outputSize); // Encode data to Base64 string, memory must be MemFree() -RLAPI unsigned char *DecodeDataBase64(const unsigned char *data, int *outputSize); // Decode Base64 string data, memory must be MemFree() -RLAPI unsigned int ComputeCRC32(unsigned char *data, int dataSize); // Compute CRC32 hash code -RLAPI unsigned int *ComputeMD5(unsigned char *data, int dataSize); // Compute MD5 hash code, returns static int[4] (16 bytes) -RLAPI unsigned int *ComputeSHA1(unsigned char *data, int dataSize); // Compute SHA1 hash code, returns static int[5] (20 bytes) - - -// Automation events functionality -RLAPI AutomationEventList LoadAutomationEventList(const char *fileName); // Load automation events list from file, NULL for empty list, capacity = MAX_AUTOMATION_EVENTS -RLAPI void UnloadAutomationEventList(AutomationEventList list); // Unload automation events list from file -RLAPI bool ExportAutomationEventList(AutomationEventList list, const char *fileName); // Export automation events list as text file -RLAPI void SetAutomationEventList(AutomationEventList *list); // Set automation event list to record to -RLAPI void SetAutomationEventBaseFrame(int frame); // Set automation event internal base frame to start recording -RLAPI void StartAutomationEventRecording(void); // Start recording automation events (AutomationEventList must be set) -RLAPI void StopAutomationEventRecording(void); // Stop recording automation events -RLAPI void PlayAutomationEvent(AutomationEvent event); // Play a recorded automation event - -//------------------------------------------------------------------------------------ -// Input Handling Functions (Module: core) -//------------------------------------------------------------------------------------ - -// Input-related functions: keyboard -RLAPI bool IsKeyPressed(int key); // Check if a key has been pressed once -RLAPI bool IsKeyPressedRepeat(int key); // Check if a key has been pressed again -RLAPI bool IsKeyDown(int key); // Check if a key is being pressed -RLAPI bool IsKeyReleased(int key); // Check if a key has been released once -RLAPI bool IsKeyUp(int key); // Check if a key is NOT being pressed -RLAPI int GetKeyPressed(void); // Get key pressed (keycode), call it multiple times for keys queued, returns 0 when the queue is empty -RLAPI int GetCharPressed(void); // Get char pressed (unicode), call it multiple times for chars queued, returns 0 when the queue is empty -RLAPI void SetExitKey(int key); // Set a custom key to exit program (default is ESC) - -// Input-related functions: gamepads -RLAPI bool IsGamepadAvailable(int gamepad); // Check if a gamepad is available -RLAPI const char *GetGamepadName(int gamepad); // Get gamepad internal name id -RLAPI bool IsGamepadButtonPressed(int gamepad, int button); // Check if a gamepad button has been pressed once -RLAPI bool IsGamepadButtonDown(int gamepad, int button); // Check if a gamepad button is being pressed -RLAPI bool IsGamepadButtonReleased(int gamepad, int button); // Check if a gamepad button has been released once -RLAPI bool IsGamepadButtonUp(int gamepad, int button); // Check if a gamepad button is NOT being pressed -RLAPI int GetGamepadButtonPressed(void); // Get the last gamepad button pressed -RLAPI int GetGamepadAxisCount(int gamepad); // Get gamepad axis count for a gamepad -RLAPI float GetGamepadAxisMovement(int gamepad, int axis); // Get axis movement value for a gamepad axis -RLAPI int SetGamepadMappings(const char *mappings); // Set internal gamepad mappings (SDL_GameControllerDB) -RLAPI void SetGamepadVibration(int gamepad, float leftMotor, float rightMotor, float duration); // Set gamepad vibration for both motors (duration in seconds) - -// Input-related functions: mouse -RLAPI bool IsMouseButtonPressed(int button); // Check if a mouse button has been pressed once -RLAPI bool IsMouseButtonDown(int button); // Check if a mouse button is being pressed -RLAPI bool IsMouseButtonReleased(int button); // Check if a mouse button has been released once -RLAPI bool IsMouseButtonUp(int button); // Check if a mouse button is NOT being pressed -RLAPI int GetMouseX(void); // Get mouse position X -RLAPI int GetMouseY(void); // Get mouse position Y -RLAPI Vector2 GetMousePosition(void); // Get mouse position XY -RLAPI Vector2 GetMouseDelta(void); // Get mouse delta between frames -RLAPI void SetMousePosition(int x, int y); // Set mouse position XY -RLAPI void SetMouseOffset(int offsetX, int offsetY); // Set mouse offset -RLAPI void SetMouseScale(float scaleX, float scaleY); // Set mouse scaling -RLAPI float GetMouseWheelMove(void); // Get mouse wheel movement for X or Y, whichever is larger -RLAPI Vector2 GetMouseWheelMoveV(void); // Get mouse wheel movement for both X and Y -RLAPI void SetMouseCursor(int cursor); // Set mouse cursor - -// Input-related functions: touch -RLAPI int GetTouchX(void); // Get touch position X for touch point 0 (relative to screen size) -RLAPI int GetTouchY(void); // Get touch position Y for touch point 0 (relative to screen size) -RLAPI Vector2 GetTouchPosition(int index); // Get touch position XY for a touch point index (relative to screen size) -RLAPI int GetTouchPointId(int index); // Get touch point identifier for given index -RLAPI int GetTouchPointCount(void); // Get number of touch points - -//------------------------------------------------------------------------------------ -// Gestures and Touch Handling Functions (Module: rgestures) -//------------------------------------------------------------------------------------ -RLAPI void SetGesturesEnabled(unsigned int flags); // Enable a set of gestures using flags -RLAPI bool IsGestureDetected(unsigned int gesture); // Check if a gesture have been detected -RLAPI int GetGestureDetected(void); // Get latest detected gesture -RLAPI float GetGestureHoldDuration(void); // Get gesture hold time in seconds -RLAPI Vector2 GetGestureDragVector(void); // Get gesture drag vector -RLAPI float GetGestureDragAngle(void); // Get gesture drag angle -RLAPI Vector2 GetGesturePinchVector(void); // Get gesture pinch delta -RLAPI float GetGesturePinchAngle(void); // Get gesture pinch angle - -//------------------------------------------------------------------------------------ -// Camera System Functions (Module: rcamera) -//------------------------------------------------------------------------------------ -RLAPI void UpdateCamera(Camera *camera, int mode); // Update camera position for selected mode -RLAPI void UpdateCameraPro(Camera *camera, Vector3 movement, Vector3 rotation, float zoom); // Update camera movement/rotation - -//------------------------------------------------------------------------------------ -// Basic Shapes Drawing Functions (Module: shapes) -//------------------------------------------------------------------------------------ -// Set texture and rectangle to be used on shapes drawing -// NOTE: It can be useful when using basic shapes and one single font, -// defining a font char white rectangle would allow drawing everything in a single draw call -RLAPI void SetShapesTexture(Texture2D texture, Rectangle source); // Set texture and rectangle to be used on shapes drawing -RLAPI Texture2D GetShapesTexture(void); // Get texture that is used for shapes drawing -RLAPI Rectangle GetShapesTextureRectangle(void); // Get texture source rectangle that is used for shapes drawing - -// Basic shapes drawing functions -RLAPI void DrawPixel(int posX, int posY, Color color); // Draw a pixel using geometry [Can be slow, use with care] -RLAPI void DrawPixelV(Vector2 position, Color color); // Draw a pixel using geometry (Vector version) [Can be slow, use with care] -RLAPI void DrawLine(int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw a line -RLAPI void DrawLineV(Vector2 startPos, Vector2 endPos, Color color); // Draw a line (using gl lines) -RLAPI void DrawLineEx(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw a line (using triangles/quads) -RLAPI void DrawLineStrip(const Vector2 *points, int pointCount, Color color); // Draw lines sequence (using gl lines) -RLAPI void DrawLineBezier(Vector2 startPos, Vector2 endPos, float thick, Color color); // Draw line segment cubic-bezier in-out interpolation -RLAPI void DrawCircle(int centerX, int centerY, float radius, Color color); // Draw a color-filled circle -RLAPI void DrawCircleSector(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw a piece of a circle -RLAPI void DrawCircleSectorLines(Vector2 center, float radius, float startAngle, float endAngle, int segments, Color color); // Draw circle sector outline -RLAPI void DrawCircleGradient(int centerX, int centerY, float radius, Color inner, Color outer); // Draw a gradient-filled circle -RLAPI void DrawCircleV(Vector2 center, float radius, Color color); // Draw a color-filled circle (Vector version) -RLAPI void DrawCircleLines(int centerX, int centerY, float radius, Color color); // Draw circle outline -RLAPI void DrawCircleLinesV(Vector2 center, float radius, Color color); // Draw circle outline (Vector version) -RLAPI void DrawEllipse(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse -RLAPI void DrawEllipseLines(int centerX, int centerY, float radiusH, float radiusV, Color color); // Draw ellipse outline -RLAPI void DrawRing(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring -RLAPI void DrawRingLines(Vector2 center, float innerRadius, float outerRadius, float startAngle, float endAngle, int segments, Color color); // Draw ring outline -RLAPI void DrawRectangle(int posX, int posY, int width, int height, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectangleV(Vector2 position, Vector2 size, Color color); // Draw a color-filled rectangle (Vector version) -RLAPI void DrawRectangleRec(Rectangle rec, Color color); // Draw a color-filled rectangle -RLAPI void DrawRectanglePro(Rectangle rec, Vector2 origin, float rotation, Color color); // Draw a color-filled rectangle with pro parameters -RLAPI void DrawRectangleGradientV(int posX, int posY, int width, int height, Color top, Color bottom); // Draw a vertical-gradient-filled rectangle -RLAPI void DrawRectangleGradientH(int posX, int posY, int width, int height, Color left, Color right); // Draw a horizontal-gradient-filled rectangle -RLAPI void DrawRectangleGradientEx(Rectangle rec, Color topLeft, Color bottomLeft, Color topRight, Color bottomRight); // Draw a gradient-filled rectangle with custom vertex colors -RLAPI void DrawRectangleLines(int posX, int posY, int width, int height, Color color); // Draw rectangle outline -RLAPI void DrawRectangleLinesEx(Rectangle rec, float lineThick, Color color); // Draw rectangle outline with extended parameters -RLAPI void DrawRectangleRounded(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle with rounded edges -RLAPI void DrawRectangleRoundedLines(Rectangle rec, float roundness, int segments, Color color); // Draw rectangle lines with rounded edges -RLAPI void DrawRectangleRoundedLinesEx(Rectangle rec, float roundness, int segments, float lineThick, Color color); // Draw rectangle with rounded edges outline -RLAPI void DrawTriangle(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleLines(Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline (vertex in counter-clockwise order!) -RLAPI void DrawTriangleFan(const Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points (first vertex is the center) -RLAPI void DrawTriangleStrip(const Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawPoly(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a regular polygon (Vector version) -RLAPI void DrawPolyLines(Vector2 center, int sides, float radius, float rotation, Color color); // Draw a polygon outline of n sides -RLAPI void DrawPolyLinesEx(Vector2 center, int sides, float radius, float rotation, float lineThick, Color color); // Draw a polygon outline of n sides with extended parameters - -// Splines drawing functions -RLAPI void DrawSplineLinear(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Linear, minimum 2 points -RLAPI void DrawSplineBasis(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: B-Spline, minimum 4 points -RLAPI void DrawSplineCatmullRom(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Catmull-Rom, minimum 4 points -RLAPI void DrawSplineBezierQuadratic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Quadratic Bezier, minimum 3 points (1 control point): [p1, c2, p3, c4...] -RLAPI void DrawSplineBezierCubic(const Vector2 *points, int pointCount, float thick, Color color); // Draw spline: Cubic Bezier, minimum 4 points (2 control points): [p1, c2, c3, p4, c5, c6...] -RLAPI void DrawSplineSegmentLinear(Vector2 p1, Vector2 p2, float thick, Color color); // Draw spline segment: Linear, 2 points -RLAPI void DrawSplineSegmentBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: B-Spline, 4 points -RLAPI void DrawSplineSegmentCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float thick, Color color); // Draw spline segment: Catmull-Rom, 4 points -RLAPI void DrawSplineSegmentBezierQuadratic(Vector2 p1, Vector2 c2, Vector2 p3, float thick, Color color); // Draw spline segment: Quadratic Bezier, 2 points, 1 control point -RLAPI void DrawSplineSegmentBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float thick, Color color); // Draw spline segment: Cubic Bezier, 2 points, 2 control points - -// Spline segment point evaluation functions, for a given t [0.0f .. 1.0f] -RLAPI Vector2 GetSplinePointLinear(Vector2 startPos, Vector2 endPos, float t); // Get (evaluate) spline point: Linear -RLAPI Vector2 GetSplinePointBasis(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: B-Spline -RLAPI Vector2 GetSplinePointCatmullRom(Vector2 p1, Vector2 p2, Vector2 p3, Vector2 p4, float t); // Get (evaluate) spline point: Catmull-Rom -RLAPI Vector2 GetSplinePointBezierQuad(Vector2 p1, Vector2 c2, Vector2 p3, float t); // Get (evaluate) spline point: Quadratic Bezier -RLAPI Vector2 GetSplinePointBezierCubic(Vector2 p1, Vector2 c2, Vector2 c3, Vector2 p4, float t); // Get (evaluate) spline point: Cubic Bezier - -// Basic shapes collision detection functions -RLAPI bool CheckCollisionRecs(Rectangle rec1, Rectangle rec2); // Check collision between two rectangles -RLAPI bool CheckCollisionCircles(Vector2 center1, float radius1, Vector2 center2, float radius2); // Check collision between two circles -RLAPI bool CheckCollisionCircleRec(Vector2 center, float radius, Rectangle rec); // Check collision between circle and rectangle -RLAPI bool CheckCollisionCircleLine(Vector2 center, float radius, Vector2 p1, Vector2 p2); // Check if circle collides with a line created betweeen two points [p1] and [p2] -RLAPI bool CheckCollisionPointRec(Vector2 point, Rectangle rec); // Check if point is inside rectangle -RLAPI bool CheckCollisionPointCircle(Vector2 point, Vector2 center, float radius); // Check if point is inside circle -RLAPI bool CheckCollisionPointTriangle(Vector2 point, Vector2 p1, Vector2 p2, Vector2 p3); // Check if point is inside a triangle -RLAPI bool CheckCollisionPointLine(Vector2 point, Vector2 p1, Vector2 p2, int threshold); // Check if point belongs to line created between two points [p1] and [p2] with defined margin in pixels [threshold] -RLAPI bool CheckCollisionPointPoly(Vector2 point, const Vector2 *points, int pointCount); // Check if point is within a polygon described by array of vertices -RLAPI bool CheckCollisionLines(Vector2 startPos1, Vector2 endPos1, Vector2 startPos2, Vector2 endPos2, Vector2 *collisionPoint); // Check the collision between two lines defined by two points each, returns collision point by reference -RLAPI Rectangle GetCollisionRec(Rectangle rec1, Rectangle rec2); // Get collision rectangle for two rectangles collision - -//------------------------------------------------------------------------------------ -// Texture Loading and Drawing Functions (Module: textures) -//------------------------------------------------------------------------------------ - -// Image loading functions -// NOTE: These functions do not require GPU access -RLAPI Image LoadImage(const char *fileName); // Load image from file into CPU memory (RAM) -RLAPI Image LoadImageRaw(const char *fileName, int width, int height, int format, int headerSize); // Load image from RAW file data -RLAPI Image LoadImageAnim(const char *fileName, int *frames); // Load image sequence from file (frames appended to image.data) -RLAPI Image LoadImageAnimFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int *frames); // Load image sequence from memory buffer -RLAPI Image LoadImageFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load image from memory buffer, fileType refers to extension: i.e. '.png' -RLAPI Image LoadImageFromTexture(Texture2D texture); // Load image from GPU texture data -RLAPI Image LoadImageFromScreen(void); // Load image from screen buffer and (screenshot) -RLAPI bool IsImageValid(Image image); // Check if an image is valid (data and parameters) -RLAPI void UnloadImage(Image image); // Unload image from CPU memory (RAM) -RLAPI bool ExportImage(Image image, const char *fileName); // Export image data to file, returns true on success -RLAPI unsigned char *ExportImageToMemory(Image image, const char *fileType, int *fileSize); // Export image to memory buffer -RLAPI bool ExportImageAsCode(Image image, const char *fileName); // Export image as code file defining an array of bytes, returns true on success - -// Image generation functions -RLAPI Image GenImageColor(int width, int height, Color color); // Generate image: plain color -RLAPI Image GenImageGradientLinear(int width, int height, int direction, Color start, Color end); // Generate image: linear gradient, direction in degrees [0..360], 0=Vertical gradient -RLAPI Image GenImageGradientRadial(int width, int height, float density, Color inner, Color outer); // Generate image: radial gradient -RLAPI Image GenImageGradientSquare(int width, int height, float density, Color inner, Color outer); // Generate image: square gradient -RLAPI Image GenImageChecked(int width, int height, int checksX, int checksY, Color col1, Color col2); // Generate image: checked -RLAPI Image GenImageWhiteNoise(int width, int height, float factor); // Generate image: white noise -RLAPI Image GenImagePerlinNoise(int width, int height, int offsetX, int offsetY, float scale); // Generate image: perlin noise -RLAPI Image GenImageCellular(int width, int height, int tileSize); // Generate image: cellular algorithm, bigger tileSize means bigger cells -RLAPI Image GenImageText(int width, int height, const char *text); // Generate image: grayscale image from text data - -// Image manipulation functions -RLAPI Image ImageCopy(Image image); // Create an image duplicate (useful for transformations) -RLAPI Image ImageFromImage(Image image, Rectangle rec); // Create an image from another image piece -RLAPI Image ImageFromChannel(Image image, int selectedChannel); // Create an image from a selected channel of another image (GRAYSCALE) -RLAPI Image ImageText(const char *text, int fontSize, Color color); // Create an image from text (default font) -RLAPI Image ImageTextEx(Font font, const char *text, float fontSize, float spacing, Color tint); // Create an image from text (custom sprite font) -RLAPI void ImageFormat(Image *image, int newFormat); // Convert image data to desired format -RLAPI void ImageToPOT(Image *image, Color fill); // Convert image to POT (power-of-two) -RLAPI void ImageCrop(Image *image, Rectangle crop); // Crop an image to a defined rectangle -RLAPI void ImageAlphaCrop(Image *image, float threshold); // Crop image depending on alpha value -RLAPI void ImageAlphaClear(Image *image, Color color, float threshold); // Clear alpha channel to desired color -RLAPI void ImageAlphaMask(Image *image, Image alphaMask); // Apply alpha mask to image -RLAPI void ImageAlphaPremultiply(Image *image); // Premultiply alpha channel -RLAPI void ImageBlurGaussian(Image *image, int blurSize); // Apply Gaussian blur using a box blur approximation -RLAPI void ImageKernelConvolution(Image *image, const float *kernel, int kernelSize); // Apply custom square convolution kernel to image -RLAPI void ImageResize(Image *image, int newWidth, int newHeight); // Resize image (Bicubic scaling algorithm) -RLAPI void ImageResizeNN(Image *image, int newWidth,int newHeight); // Resize image (Nearest-Neighbor scaling algorithm) -RLAPI void ImageResizeCanvas(Image *image, int newWidth, int newHeight, int offsetX, int offsetY, Color fill); // Resize canvas and fill with color -RLAPI void ImageMipmaps(Image *image); // Compute all mipmap levels for a provided image -RLAPI void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp); // Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -RLAPI void ImageFlipVertical(Image *image); // Flip image vertically -RLAPI void ImageFlipHorizontal(Image *image); // Flip image horizontally -RLAPI void ImageRotate(Image *image, int degrees); // Rotate image by input angle in degrees (-359 to 359) -RLAPI void ImageRotateCW(Image *image); // Rotate image clockwise 90deg -RLAPI void ImageRotateCCW(Image *image); // Rotate image counter-clockwise 90deg -RLAPI void ImageColorTint(Image *image, Color color); // Modify image color: tint -RLAPI void ImageColorInvert(Image *image); // Modify image color: invert -RLAPI void ImageColorGrayscale(Image *image); // Modify image color: grayscale -RLAPI void ImageColorContrast(Image *image, float contrast); // Modify image color: contrast (-100 to 100) -RLAPI void ImageColorBrightness(Image *image, int brightness); // Modify image color: brightness (-255 to 255) -RLAPI void ImageColorReplace(Image *image, Color color, Color replace); // Modify image color: replace color -RLAPI Color *LoadImageColors(Image image); // Load color data from image as a Color array (RGBA - 32bit) -RLAPI Color *LoadImagePalette(Image image, int maxPaletteSize, int *colorCount); // Load colors palette from image as a Color array (RGBA - 32bit) -RLAPI void UnloadImageColors(Color *colors); // Unload color data loaded with LoadImageColors() -RLAPI void UnloadImagePalette(Color *colors); // Unload colors palette loaded with LoadImagePalette() -RLAPI Rectangle GetImageAlphaBorder(Image image, float threshold); // Get image alpha border rectangle -RLAPI Color GetImageColor(Image image, int x, int y); // Get image pixel color at (x, y) position - -// Image drawing functions -// NOTE: Image software-rendering functions (CPU) -RLAPI void ImageClearBackground(Image *dst, Color color); // Clear image background with given color -RLAPI void ImageDrawPixel(Image *dst, int posX, int posY, Color color); // Draw pixel within an image -RLAPI void ImageDrawPixelV(Image *dst, Vector2 position, Color color); // Draw pixel within an image (Vector version) -RLAPI void ImageDrawLine(Image *dst, int startPosX, int startPosY, int endPosX, int endPosY, Color color); // Draw line within an image -RLAPI void ImageDrawLineV(Image *dst, Vector2 start, Vector2 end, Color color); // Draw line within an image (Vector version) -RLAPI void ImageDrawLineEx(Image *dst, Vector2 start, Vector2 end, int thick, Color color); // Draw a line defining thickness within an image -RLAPI void ImageDrawCircle(Image *dst, int centerX, int centerY, int radius, Color color); // Draw a filled circle within an image -RLAPI void ImageDrawCircleV(Image *dst, Vector2 center, int radius, Color color); // Draw a filled circle within an image (Vector version) -RLAPI void ImageDrawCircleLines(Image *dst, int centerX, int centerY, int radius, Color color); // Draw circle outline within an image -RLAPI void ImageDrawCircleLinesV(Image *dst, Vector2 center, int radius, Color color); // Draw circle outline within an image (Vector version) -RLAPI void ImageDrawRectangle(Image *dst, int posX, int posY, int width, int height, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleV(Image *dst, Vector2 position, Vector2 size, Color color); // Draw rectangle within an image (Vector version) -RLAPI void ImageDrawRectangleRec(Image *dst, Rectangle rec, Color color); // Draw rectangle within an image -RLAPI void ImageDrawRectangleLines(Image *dst, Rectangle rec, int thick, Color color); // Draw rectangle lines within an image -RLAPI void ImageDrawTriangle(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle within an image -RLAPI void ImageDrawTriangleEx(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color c1, Color c2, Color c3); // Draw triangle with interpolated colors within an image -RLAPI void ImageDrawTriangleLines(Image *dst, Vector2 v1, Vector2 v2, Vector2 v3, Color color); // Draw triangle outline within an image -RLAPI void ImageDrawTriangleFan(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle fan defined by points within an image (first vertex is the center) -RLAPI void ImageDrawTriangleStrip(Image *dst, Vector2 *points, int pointCount, Color color); // Draw a triangle strip defined by points within an image -RLAPI void ImageDraw(Image *dst, Image src, Rectangle srcRec, Rectangle dstRec, Color tint); // Draw a source image within a destination image (tint applied to source) -RLAPI void ImageDrawText(Image *dst, const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) within an image (destination) -RLAPI void ImageDrawTextEx(Image *dst, Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text (custom sprite font) within an image (destination) - -// Texture loading functions -// NOTE: These functions require GPU access -RLAPI Texture2D LoadTexture(const char *fileName); // Load texture from file into GPU memory (VRAM) -RLAPI Texture2D LoadTextureFromImage(Image image); // Load texture from image data -RLAPI TextureCubemap LoadTextureCubemap(Image image, int layout); // Load cubemap from image, multiple image cubemap layouts supported -RLAPI RenderTexture2D LoadRenderTexture(int width, int height); // Load texture for rendering (framebuffer) -RLAPI bool IsTextureValid(Texture2D texture); // Check if a texture is valid (loaded in GPU) -RLAPI void UnloadTexture(Texture2D texture); // Unload texture from GPU memory (VRAM) -RLAPI bool IsRenderTextureValid(RenderTexture2D target); // Check if a render texture is valid (loaded in GPU) -RLAPI void UnloadRenderTexture(RenderTexture2D target); // Unload render texture from GPU memory (VRAM) -RLAPI void UpdateTexture(Texture2D texture, const void *pixels); // Update GPU texture with new data -RLAPI void UpdateTextureRec(Texture2D texture, Rectangle rec, const void *pixels); // Update GPU texture rectangle with new data - -// Texture configuration functions -RLAPI void GenTextureMipmaps(Texture2D *texture); // Generate GPU mipmaps for a texture -RLAPI void SetTextureFilter(Texture2D texture, int filter); // Set texture scaling filter mode -RLAPI void SetTextureWrap(Texture2D texture, int wrap); // Set texture wrapping mode - -// Texture drawing functions -RLAPI void DrawTexture(Texture2D texture, int posX, int posY, Color tint); // Draw a Texture2D -RLAPI void DrawTextureV(Texture2D texture, Vector2 position, Color tint); // Draw a Texture2D with position defined as Vector2 -RLAPI void DrawTextureEx(Texture2D texture, Vector2 position, float rotation, float scale, Color tint); // Draw a Texture2D with extended parameters -RLAPI void DrawTextureRec(Texture2D texture, Rectangle source, Vector2 position, Color tint); // Draw a part of a texture defined by a rectangle -RLAPI void DrawTexturePro(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draw a part of a texture defined by a rectangle with 'pro' parameters -RLAPI void DrawTextureNPatch(Texture2D texture, NPatchInfo nPatchInfo, Rectangle dest, Vector2 origin, float rotation, Color tint); // Draws a texture (or part of it) that stretches or shrinks nicely - -// Color/pixel related functions -RLAPI bool ColorIsEqual(Color col1, Color col2); // Check if two colors are equal -RLAPI Color Fade(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI int ColorToInt(Color color); // Get hexadecimal value for a Color (0xRRGGBBAA) -RLAPI Vector4 ColorNormalize(Color color); // Get Color normalized as float [0..1] -RLAPI Color ColorFromNormalized(Vector4 normalized); // Get Color from normalized values [0..1] -RLAPI Vector3 ColorToHSV(Color color); // Get HSV values for a Color, hue [0..360], saturation/value [0..1] -RLAPI Color ColorFromHSV(float hue, float saturation, float value); // Get a Color from HSV values, hue [0..360], saturation/value [0..1] -RLAPI Color ColorTint(Color color, Color tint); // Get color multiplied with another color -RLAPI Color ColorBrightness(Color color, float factor); // Get color with brightness correction, brightness factor goes from -1.0f to 1.0f -RLAPI Color ColorContrast(Color color, float contrast); // Get color with contrast correction, contrast values between -1.0f and 1.0f -RLAPI Color ColorAlpha(Color color, float alpha); // Get color with alpha applied, alpha goes from 0.0f to 1.0f -RLAPI Color ColorAlphaBlend(Color dst, Color src, Color tint); // Get src alpha-blended into dst color with tint -RLAPI Color ColorLerp(Color color1, Color color2, float factor); // Get color lerp interpolation between two colors, factor [0.0f..1.0f] -RLAPI Color GetColor(unsigned int hexValue); // Get Color structure from hexadecimal value -RLAPI Color GetPixelColor(void *srcPtr, int format); // Get Color from a source pixel pointer of certain format -RLAPI void SetPixelColor(void *dstPtr, Color color, int format); // Set color formatted into destination pixel pointer -RLAPI int GetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes for certain format - -//------------------------------------------------------------------------------------ -// Font Loading and Text Drawing Functions (Module: text) -//------------------------------------------------------------------------------------ - -// Font loading/unloading functions -RLAPI Font GetFontDefault(void); // Get the default Font -RLAPI Font LoadFont(const char *fileName); // Load font from file into GPU memory (VRAM) -RLAPI Font LoadFontEx(const char *fileName, int fontSize, int *codepoints, int codepointCount); // Load font from file with extended parameters, use NULL for codepoints and 0 for codepointCount to load the default character set, font size is provided in pixels height -RLAPI Font LoadFontFromImage(Image image, Color key, int firstChar); // Load font from Image (XNA style) -RLAPI Font LoadFontFromMemory(const char *fileType, const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount); // Load font from memory buffer, fileType refers to extension: i.e. '.ttf' -RLAPI bool IsFontValid(Font font); // Check if a font is valid (font data loaded, WARNING: GPU texture not checked) -RLAPI GlyphInfo *LoadFontData(const unsigned char *fileData, int dataSize, int fontSize, int *codepoints, int codepointCount, int type); // Load font data for further use -RLAPI Image GenImageFontAtlas(const GlyphInfo *glyphs, Rectangle **glyphRecs, int glyphCount, int fontSize, int padding, int packMethod); // Generate image font atlas using chars info -RLAPI void UnloadFontData(GlyphInfo *glyphs, int glyphCount); // Unload font chars info data (RAM) -RLAPI void UnloadFont(Font font); // Unload font from GPU memory (VRAM) -RLAPI bool ExportFontAsCode(Font font, const char *fileName); // Export font as code file, returns true on success - -// Text drawing functions -RLAPI void DrawFPS(int posX, int posY); // Draw current FPS -RLAPI void DrawText(const char *text, int posX, int posY, int fontSize, Color color); // Draw text (using default font) -RLAPI void DrawTextEx(Font font, const char *text, Vector2 position, float fontSize, float spacing, Color tint); // Draw text using font and additional parameters -RLAPI void DrawTextPro(Font font, const char *text, Vector2 position, Vector2 origin, float rotation, float fontSize, float spacing, Color tint); // Draw text using Font and pro parameters (rotation) -RLAPI void DrawTextCodepoint(Font font, int codepoint, Vector2 position, float fontSize, Color tint); // Draw one character (codepoint) -RLAPI void DrawTextCodepoints(Font font, const int *codepoints, int codepointCount, Vector2 position, float fontSize, float spacing, Color tint); // Draw multiple character (codepoint) - -// Text font info functions -RLAPI void SetTextLineSpacing(int spacing); // Set vertical line spacing when drawing with line-breaks -RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font -RLAPI Vector2 MeasureTextEx(Font font, const char *text, float fontSize, float spacing); // Measure string size for Font -RLAPI int GetGlyphIndex(Font font, int codepoint); // Get glyph index position in font for a codepoint (unicode character), fallback to '?' if not found -RLAPI GlyphInfo GetGlyphInfo(Font font, int codepoint); // Get glyph font info data for a codepoint (unicode character), fallback to '?' if not found -RLAPI Rectangle GetGlyphAtlasRec(Font font, int codepoint); // Get glyph rectangle in font atlas for a codepoint (unicode character), fallback to '?' if not found - -// Text codepoints management functions (unicode characters) -RLAPI char *LoadUTF8(const int *codepoints, int length); // Load UTF-8 text encoded from codepoints array -RLAPI void UnloadUTF8(char *text); // Unload UTF-8 text encoded from codepoints array -RLAPI int *LoadCodepoints(const char *text, int *count); // Load all codepoints from a UTF-8 text string, codepoints count returned by parameter -RLAPI void UnloadCodepoints(int *codepoints); // Unload codepoints data from memory -RLAPI int GetCodepointCount(const char *text); // Get total number of codepoints in a UTF-8 encoded string -RLAPI int GetCodepoint(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointNext(const char *text, int *codepointSize); // Get next codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI int GetCodepointPrevious(const char *text, int *codepointSize); // Get previous codepoint in a UTF-8 encoded string, 0x3f('?') is returned on failure -RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter) - -// Text strings management functions (no UTF-8 strings, only byte chars) -// NOTE: Some strings allocate memory internally for returned strings, just be careful! -RLAPI int TextCopy(char *dst, const char *src); // Copy one string to another, returns bytes copied -RLAPI bool TextIsEqual(const char *text1, const char *text2); // Check if two text string are equal -RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending -RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style) -RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string -RLAPI char *TextReplace(const char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!) -RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!) -RLAPI const char *TextJoin(const char **textList, int count, const char *delimiter); // Join text strings with delimiter -RLAPI const char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings -RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor! -RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string -RLAPI const char *TextToUpper(const char *text); // Get upper case version of provided string -RLAPI const char *TextToLower(const char *text); // Get lower case version of provided string -RLAPI const char *TextToPascal(const char *text); // Get Pascal case notation version of provided string -RLAPI const char *TextToSnake(const char *text); // Get Snake case notation version of provided string -RLAPI const char *TextToCamel(const char *text); // Get Camel case notation version of provided string - -RLAPI int TextToInteger(const char *text); // Get integer value from text (negative values not supported) -RLAPI float TextToFloat(const char *text); // Get float value from text (negative values not supported) - -//------------------------------------------------------------------------------------ -// Basic 3d Shapes Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Basic geometric 3D shapes drawing functions -RLAPI void DrawLine3D(Vector3 startPos, Vector3 endPos, Color color); // Draw a line in 3D world space -RLAPI void DrawPoint3D(Vector3 position, Color color); // Draw a point in 3D space, actually a small line -RLAPI void DrawCircle3D(Vector3 center, float radius, Vector3 rotationAxis, float rotationAngle, Color color); // Draw a circle in 3D world space -RLAPI void DrawTriangle3D(Vector3 v1, Vector3 v2, Vector3 v3, Color color); // Draw a color-filled triangle (vertex in counter-clockwise order!) -RLAPI void DrawTriangleStrip3D(const Vector3 *points, int pointCount, Color color); // Draw a triangle strip defined by points -RLAPI void DrawCube(Vector3 position, float width, float height, float length, Color color); // Draw cube -RLAPI void DrawCubeV(Vector3 position, Vector3 size, Color color); // Draw cube (Vector version) -RLAPI void DrawCubeWires(Vector3 position, float width, float height, float length, Color color); // Draw cube wires -RLAPI void DrawCubeWiresV(Vector3 position, Vector3 size, Color color); // Draw cube wires (Vector version) -RLAPI void DrawSphere(Vector3 centerPos, float radius, Color color); // Draw sphere -RLAPI void DrawSphereEx(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere with extended parameters -RLAPI void DrawSphereWires(Vector3 centerPos, float radius, int rings, int slices, Color color); // Draw sphere wires -RLAPI void DrawCylinder(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone -RLAPI void DrawCylinderEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder with base at startPos and top at endPos -RLAPI void DrawCylinderWires(Vector3 position, float radiusTop, float radiusBottom, float height, int slices, Color color); // Draw a cylinder/cone wires -RLAPI void DrawCylinderWiresEx(Vector3 startPos, Vector3 endPos, float startRadius, float endRadius, int sides, Color color); // Draw a cylinder wires with base at startPos and top at endPos -RLAPI void DrawCapsule(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw a capsule with the center of its sphere caps at startPos and endPos -RLAPI void DrawCapsuleWires(Vector3 startPos, Vector3 endPos, float radius, int slices, int rings, Color color); // Draw capsule wireframe with the center of its sphere caps at startPos and endPos -RLAPI void DrawPlane(Vector3 centerPos, Vector2 size, Color color); // Draw a plane XZ -RLAPI void DrawRay(Ray ray, Color color); // Draw a ray line -RLAPI void DrawGrid(int slices, float spacing); // Draw a grid (centered at (0, 0, 0)) - -//------------------------------------------------------------------------------------ -// Model 3d Loading and Drawing Functions (Module: models) -//------------------------------------------------------------------------------------ - -// Model management functions -RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) -RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh (default material) -RLAPI bool IsModelValid(Model model); // Check if a model is valid (loaded in GPU, VAO/VBOs) -RLAPI void UnloadModel(Model model); // Unload model (including meshes) from memory (RAM and/or VRAM) -RLAPI BoundingBox GetModelBoundingBox(Model model); // Compute model bounding box limits (considers all meshes) - -// Model drawing functions -RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -RLAPI void DrawModelEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model with extended parameters -RLAPI void DrawModelWires(Model model, Vector3 position, float scale, Color tint); // Draw a model wires (with texture if set) -RLAPI void DrawModelWiresEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model wires (with texture if set) with extended parameters -RLAPI void DrawModelPoints(Model model, Vector3 position, float scale, Color tint); // Draw a model as points -RLAPI void DrawModelPointsEx(Model model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); // Draw a model as points with extended parameters -RLAPI void DrawBoundingBox(BoundingBox box, Color color); // Draw bounding box (wires) -RLAPI void DrawBillboard(Camera camera, Texture2D texture, Vector3 position, float scale, Color tint); // Draw a billboard texture -RLAPI void DrawBillboardRec(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector2 size, Color tint); // Draw a billboard texture defined by source -RLAPI void DrawBillboardPro(Camera camera, Texture2D texture, Rectangle source, Vector3 position, Vector3 up, Vector2 size, Vector2 origin, float rotation, Color tint); // Draw a billboard texture defined by source and rotation - -// Mesh management functions -RLAPI void UploadMesh(Mesh *mesh, bool dynamic); // Upload mesh vertex data in GPU and provide VAO/VBO ids -RLAPI void UpdateMeshBuffer(Mesh mesh, int index, const void *data, int dataSize, int offset); // Update mesh vertex data in GPU for a specific buffer index -RLAPI void UnloadMesh(Mesh mesh); // Unload mesh data from CPU and GPU -RLAPI void DrawMesh(Mesh mesh, Material material, Matrix transform); // Draw a 3d mesh with material and transform -RLAPI void DrawMeshInstanced(Mesh mesh, Material material, const Matrix *transforms, int instances); // Draw multiple mesh instances with material and different transforms -RLAPI BoundingBox GetMeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits -RLAPI void GenMeshTangents(Mesh *mesh); // Compute mesh tangents -RLAPI bool ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file, returns true on success -RLAPI bool ExportMeshAsCode(Mesh mesh, const char *fileName); // Export mesh as code file (.h) defining multiple arrays of vertex attributes - -// Mesh generation functions -RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh -RLAPI Mesh GenMeshPlane(float width, float length, int resX, int resZ); // Generate plane mesh (with subdivisions) -RLAPI Mesh GenMeshCube(float width, float height, float length); // Generate cuboid mesh -RLAPI Mesh GenMeshSphere(float radius, int rings, int slices); // Generate sphere mesh (standard sphere) -RLAPI Mesh GenMeshHemiSphere(float radius, int rings, int slices); // Generate half-sphere mesh (no bottom cap) -RLAPI Mesh GenMeshCylinder(float radius, float height, int slices); // Generate cylinder mesh -RLAPI Mesh GenMeshCone(float radius, float height, int slices); // Generate cone/pyramid mesh -RLAPI Mesh GenMeshTorus(float radius, float size, int radSeg, int sides); // Generate torus mesh -RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); // Generate trefoil knot mesh -RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data -RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data - -// Material loading/unloading functions -RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI bool IsMaterialValid(Material material); // Check if a material is valid (shader assigned, map textures loaded in GPU) -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) -RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MATERIAL_MAP_DIFFUSE, MATERIAL_MAP_SPECULAR...) -RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh - -// Model animations loading/unloading functions -RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animCount); // Load model animations from file -RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose (CPU) -RLAPI void UpdateModelAnimationBones(Model model, ModelAnimation anim, int frame); // Update model animation mesh bone matrices (GPU skinning) -RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data -RLAPI void UnloadModelAnimations(ModelAnimation *animations, int animCount); // Unload animation array data -RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match - -// Collision detection functions -RLAPI bool CheckCollisionSpheres(Vector3 center1, float radius1, Vector3 center2, float radius2); // Check collision between two spheres -RLAPI bool CheckCollisionBoxes(BoundingBox box1, BoundingBox box2); // Check collision between two bounding boxes -RLAPI bool CheckCollisionBoxSphere(BoundingBox box, Vector3 center, float radius); // Check collision between box and sphere -RLAPI RayCollision GetRayCollisionSphere(Ray ray, Vector3 center, float radius); // Get collision info between ray and sphere -RLAPI RayCollision GetRayCollisionBox(Ray ray, BoundingBox box); // Get collision info between ray and box -RLAPI RayCollision GetRayCollisionMesh(Ray ray, Mesh mesh, Matrix transform); // Get collision info between ray and mesh -RLAPI RayCollision GetRayCollisionTriangle(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3); // Get collision info between ray and triangle -RLAPI RayCollision GetRayCollisionQuad(Ray ray, Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4); // Get collision info between ray and quad - -//------------------------------------------------------------------------------------ -// Audio Loading and Playing Functions (Module: audio) -//------------------------------------------------------------------------------------ -typedef void (*AudioCallback)(void *bufferData, unsigned int frames); - -// Audio device management functions -RLAPI void InitAudioDevice(void); // Initialize audio device and context -RLAPI void CloseAudioDevice(void); // Close the audio device and context -RLAPI bool IsAudioDeviceReady(void); // Check if audio device has been initialized successfully -RLAPI void SetMasterVolume(float volume); // Set master volume (listener) -RLAPI float GetMasterVolume(void); // Get master volume (listener) - -// Wave/Sound loading/unloading functions -RLAPI Wave LoadWave(const char *fileName); // Load wave data from file -RLAPI Wave LoadWaveFromMemory(const char *fileType, const unsigned char *fileData, int dataSize); // Load wave from memory buffer, fileType refers to extension: i.e. '.wav' -RLAPI bool IsWaveValid(Wave wave); // Checks if wave data is valid (data loaded and parameters) -RLAPI Sound LoadSound(const char *fileName); // Load sound from file -RLAPI Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -RLAPI Sound LoadSoundAlias(Sound source); // Create a new sound that shares the same sample data as the source sound, does not own the sound data -RLAPI bool IsSoundValid(Sound sound); // Checks if a sound is valid (data loaded and buffers initialized) -RLAPI void UpdateSound(Sound sound, const void *data, int sampleCount); // Update sound buffer with new data -RLAPI void UnloadWave(Wave wave); // Unload wave data -RLAPI void UnloadSound(Sound sound); // Unload sound -RLAPI void UnloadSoundAlias(Sound alias); // Unload a sound alias (does not deallocate sample data) -RLAPI bool ExportWave(Wave wave, const char *fileName); // Export wave data to file, returns true on success -RLAPI bool ExportWaveAsCode(Wave wave, const char *fileName); // Export wave sample data to code (.h), returns true on success - -// Wave/Sound management functions -RLAPI void PlaySound(Sound sound); // Play a sound -RLAPI void StopSound(Sound sound); // Stop playing a sound -RLAPI void PauseSound(Sound sound); // Pause a sound -RLAPI void ResumeSound(Sound sound); // Resume a paused sound -RLAPI bool IsSoundPlaying(Sound sound); // Check if a sound is currently playing -RLAPI void SetSoundVolume(Sound sound, float volume); // Set volume for a sound (1.0 is max level) -RLAPI void SetSoundPitch(Sound sound, float pitch); // Set pitch for a sound (1.0 is base level) -RLAPI void SetSoundPan(Sound sound, float pan); // Set pan for a sound (0.5 is center) -RLAPI Wave WaveCopy(Wave wave); // Copy a wave to a new wave -RLAPI void WaveCrop(Wave *wave, int initFrame, int finalFrame); // Crop a wave to defined frames range -RLAPI void WaveFormat(Wave *wave, int sampleRate, int sampleSize, int channels); // Convert wave data to desired format -RLAPI float *LoadWaveSamples(Wave wave); // Load samples data from wave as a 32bit float data array -RLAPI void UnloadWaveSamples(float *samples); // Unload samples data loaded with LoadWaveSamples() - -// Music management functions -RLAPI Music LoadMusicStream(const char *fileName); // Load music stream from file -RLAPI Music LoadMusicStreamFromMemory(const char *fileType, const unsigned char *data, int dataSize); // Load music stream from data -RLAPI bool IsMusicValid(Music music); // Checks if a music stream is valid (context and buffers initialized) -RLAPI void UnloadMusicStream(Music music); // Unload music stream -RLAPI void PlayMusicStream(Music music); // Start music playing -RLAPI bool IsMusicStreamPlaying(Music music); // Check if music is playing -RLAPI void UpdateMusicStream(Music music); // Updates buffers for music streaming -RLAPI void StopMusicStream(Music music); // Stop music playing -RLAPI void PauseMusicStream(Music music); // Pause music playing -RLAPI void ResumeMusicStream(Music music); // Resume playing paused music -RLAPI void SeekMusicStream(Music music, float position); // Seek music to a position (in seconds) -RLAPI void SetMusicVolume(Music music, float volume); // Set volume for music (1.0 is max level) -RLAPI void SetMusicPitch(Music music, float pitch); // Set pitch for a music (1.0 is base level) -RLAPI void SetMusicPan(Music music, float pan); // Set pan for a music (0.5 is center) -RLAPI float GetMusicTimeLength(Music music); // Get music time length (in seconds) -RLAPI float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) - -// AudioStream management functions -RLAPI AudioStream LoadAudioStream(unsigned int sampleRate, unsigned int sampleSize, unsigned int channels); // Load audio stream (to stream raw audio pcm data) -RLAPI bool IsAudioStreamValid(AudioStream stream); // Checks if an audio stream is valid (buffers initialized) -RLAPI void UnloadAudioStream(AudioStream stream); // Unload audio stream and free memory -RLAPI void UpdateAudioStream(AudioStream stream, const void *data, int frameCount); // Update audio stream buffers with data -RLAPI bool IsAudioStreamProcessed(AudioStream stream); // Check if any audio stream buffers requires refill -RLAPI void PlayAudioStream(AudioStream stream); // Play audio stream -RLAPI void PauseAudioStream(AudioStream stream); // Pause audio stream -RLAPI void ResumeAudioStream(AudioStream stream); // Resume audio stream -RLAPI bool IsAudioStreamPlaying(AudioStream stream); // Check if audio stream is playing -RLAPI void StopAudioStream(AudioStream stream); // Stop audio stream -RLAPI void SetAudioStreamVolume(AudioStream stream, float volume); // Set volume for audio stream (1.0 is max level) -RLAPI void SetAudioStreamPitch(AudioStream stream, float pitch); // Set pitch for audio stream (1.0 is base level) -RLAPI void SetAudioStreamPan(AudioStream stream, float pan); // Set pan for audio stream (0.5 is centered) -RLAPI void SetAudioStreamBufferSizeDefault(int size); // Default size for new audio streams -RLAPI void SetAudioStreamCallback(AudioStream stream, AudioCallback callback); // Audio thread callback to request new data - -RLAPI void AttachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Attach audio stream processor to stream, receives the samples as 'float' -RLAPI void DetachAudioStreamProcessor(AudioStream stream, AudioCallback processor); // Detach audio stream processor from stream - -RLAPI void AttachAudioMixedProcessor(AudioCallback processor); // Attach audio stream processor to the entire audio pipeline, receives the samples as 'float' -RLAPI void DetachAudioMixedProcessor(AudioCallback processor); // Detach audio stream processor from the entire audio pipeline - -#if defined(__cplusplus) -} -#endif - -#endif // RAYLIB_H diff --git a/examples/raylib/raylib-5.5_linux_amd64/include/raymath.h b/examples/raylib/raylib-5.5_linux_amd64/include/raymath.h deleted file mode 100644 index e522113..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/include/raymath.h +++ /dev/null @@ -1,2941 +0,0 @@ -/********************************************************************************************** -* -* raymath v2.0 - Math functions to work with Vector2, Vector3, Matrix and Quaternions -* -* CONVENTIONS: -* - Matrix structure is defined as row-major (memory layout) but parameters naming AND all -* math operations performed by the library consider the structure as it was column-major -* It is like transposed versions of the matrices are used for all the maths -* It benefits some functions making them cache-friendly and also avoids matrix -* transpositions sometimes required by OpenGL -* Example: In memory order, row0 is [m0 m4 m8 m12] but in semantic math row0 is [m0 m1 m2 m3] -* - Functions are always self-contained, no function use another raymath function inside, -* required code is directly re-implemented inside -* - Functions input parameters are always received by value (2 unavoidable exceptions) -* - Functions use always a "result" variable for return (except C++ operators) -* - Functions are always defined inline -* - Angles are always in radians (DEG2RAD/RAD2DEG macros provided for convenience) -* - No compound literals used to make sure libray is compatible with C++ -* -* CONFIGURATION: -* #define RAYMATH_IMPLEMENTATION -* Generates the implementation of the library into the included file. -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation. -* -* #define RAYMATH_STATIC_INLINE -* Define static inline functions code, so #include header suffices for use. -* This may use up lots of memory. -* -* #define RAYMATH_DISABLE_CPP_OPERATORS -* Disables C++ operator overloads for raymath types. -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2015-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RAYMATH_H -#define RAYMATH_H - -#if defined(RAYMATH_IMPLEMENTATION) && defined(RAYMATH_STATIC_INLINE) - #error "Specifying both RAYMATH_IMPLEMENTATION and RAYMATH_STATIC_INLINE is contradictory" -#endif - -// Function specifiers definition -#if defined(RAYMATH_IMPLEMENTATION) - #if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __declspec(dllexport) extern inline // We are building raylib as a Win32 shared library (.dll) - #elif defined(BUILD_LIBTYPE_SHARED) - #define RMAPI __attribute__((visibility("default"))) // We are building raylib as a Unix shared library (.so/.dylib) - #elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RMAPI __declspec(dllimport) // We are using raylib as a Win32 shared library (.dll) - #else - #define RMAPI extern inline // Provide external definition - #endif -#elif defined(RAYMATH_STATIC_INLINE) - #define RMAPI static inline // Functions may be inlined, no external out-of-line definition -#else - #if defined(__TINYC__) - #define RMAPI static inline // plain inline not supported by tinycc (See issue #435) - #else - #define RMAPI inline // Functions may be inlined or external definition used - #endif -#endif - - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif - -#ifndef EPSILON - #define EPSILON 0.000001f -#endif - -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif - -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -// Get float vector for Matrix -#ifndef MatrixToFloat - #define MatrixToFloat(mat) (MatrixToFloatV(mat).v) -#endif - -// Get float vector for Vector3 -#ifndef Vector3ToFloat - #define Vector3ToFloat(vec) (Vector3ToFloatV(vec).v) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if !defined(RL_VECTOR2_TYPE) -// Vector2 type -typedef struct Vector2 { - float x; - float y; -} Vector2; -#define RL_VECTOR2_TYPE -#endif - -#if !defined(RL_VECTOR3_TYPE) -// Vector3 type -typedef struct Vector3 { - float x; - float y; - float z; -} Vector3; -#define RL_VECTOR3_TYPE -#endif - -#if !defined(RL_VECTOR4_TYPE) -// Vector4 type -typedef struct Vector4 { - float x; - float y; - float z; - float w; -} Vector4; -#define RL_VECTOR4_TYPE -#endif - -#if !defined(RL_QUATERNION_TYPE) -// Quaternion type -typedef Vector4 Quaternion; -#define RL_QUATERNION_TYPE -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix type (OpenGL style 4x4 - right handed, column major) -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// NOTE: Helper types to be used instead of array return types for *ToFloat functions -typedef struct float3 { - float v[3]; -} float3; - -typedef struct float16 { - float v[16]; -} float16; - -#include // Required for: sinf(), cosf(), tan(), atan2f(), sqrtf(), floor(), fminf(), fmaxf(), fabsf() - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Utils math -//---------------------------------------------------------------------------------- - -// Clamp float value -RMAPI float Clamp(float value, float min, float max) -{ - float result = (value < min)? min : value; - - if (result > max) result = max; - - return result; -} - -// Calculate linear interpolation between two floats -RMAPI float Lerp(float start, float end, float amount) -{ - float result = start + amount*(end - start); - - return result; -} - -// Normalize input value within input range -RMAPI float Normalize(float value, float start, float end) -{ - float result = (value - start)/(end - start); - - return result; -} - -// Remap input value within input range to output range -RMAPI float Remap(float value, float inputStart, float inputEnd, float outputStart, float outputEnd) -{ - float result = (value - inputStart)/(inputEnd - inputStart)*(outputEnd - outputStart) + outputStart; - - return result; -} - -// Wrap input value from min to max -RMAPI float Wrap(float value, float min, float max) -{ - float result = value - (max - min)*floorf((value - min)/(max - min)); - - return result; -} - -// Check whether two given floats are almost equal -RMAPI int FloatEquals(float x, float y) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (fabsf(x - y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(x), fabsf(y)))); - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector2 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector2 Vector2Zero(void) -{ - Vector2 result = { 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector2 Vector2One(void) -{ - Vector2 result = { 1.0f, 1.0f }; - - return result; -} - -// Add two vectors (v1 + v2) -RMAPI Vector2 Vector2Add(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x + v2.x, v1.y + v2.y }; - - return result; -} - -// Add vector and float value -RMAPI Vector2 Vector2AddValue(Vector2 v, float add) -{ - Vector2 result = { v.x + add, v.y + add }; - - return result; -} - -// Subtract two vectors (v1 - v2) -RMAPI Vector2 Vector2Subtract(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x - v2.x, v1.y - v2.y }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector2 Vector2SubtractValue(Vector2 v, float sub) -{ - Vector2 result = { v.x - sub, v.y - sub }; - - return result; -} - -// Calculate vector length -RMAPI float Vector2Length(Vector2 v) -{ - float result = sqrtf((v.x*v.x) + (v.y*v.y)); - - return result; -} - -// Calculate vector square length -RMAPI float Vector2LengthSqr(Vector2 v) -{ - float result = (v.x*v.x) + (v.y*v.y); - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector2DotProduct(Vector2 v1, Vector2 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector2Distance(Vector2 v1, Vector2 v2) -{ - float result = sqrtf((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector2DistanceSqr(Vector2 v1, Vector2 v2) -{ - float result = ((v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y)); - - return result; -} - -// Calculate angle between two vectors -// NOTE: Angle is calculated from origin point (0, 0) -RMAPI float Vector2Angle(Vector2 v1, Vector2 v2) -{ - float result = 0.0f; - - float dot = v1.x*v2.x + v1.y*v2.y; - float det = v1.x*v2.y - v1.y*v2.x; - - result = atan2f(det, dot); - - return result; -} - -// Calculate angle defined by a two vectors line -// NOTE: Parameters need to be normalized -// Current implementation should be aligned with glm::angle -RMAPI float Vector2LineAngle(Vector2 start, Vector2 end) -{ - float result = 0.0f; - - // TODO(10/9/2023): Currently angles move clockwise, determine if this is wanted behavior - result = -atan2f(end.y - start.y, end.x - start.x); - - return result; -} - -// Scale vector (multiply by value) -RMAPI Vector2 Vector2Scale(Vector2 v, float scale) -{ - Vector2 result = { v.x*scale, v.y*scale }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector2 Vector2Multiply(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x*v2.x, v1.y*v2.y }; - - return result; -} - -// Negate vector -RMAPI Vector2 Vector2Negate(Vector2 v) -{ - Vector2 result = { -v.x, -v.y }; - - return result; -} - -// Divide vector by vector -RMAPI Vector2 Vector2Divide(Vector2 v1, Vector2 v2) -{ - Vector2 result = { v1.x/v2.x, v1.y/v2.y }; - - return result; -} - -// Normalize provided vector -RMAPI Vector2 Vector2Normalize(Vector2 v) -{ - Vector2 result = { 0 }; - float length = sqrtf((v.x*v.x) + (v.y*v.y)); - - if (length > 0) - { - float ilength = 1.0f/length; - result.x = v.x*ilength; - result.y = v.y*ilength; - } - - return result; -} - -// Transforms a Vector2 by a given Matrix -RMAPI Vector2 Vector2Transform(Vector2 v, Matrix mat) -{ - Vector2 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = 0; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector2 Vector2Lerp(Vector2 v1, Vector2 v2, float amount) -{ - Vector2 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector2 Vector2Reflect(Vector2 v, Vector2 normal) -{ - Vector2 result = { 0 }; - - float dotProduct = (v.x*normal.x + v.y*normal.y); // Dot product - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - - return result; -} - -// Get min value for each pair of components -RMAPI Vector2 Vector2Min(Vector2 v1, Vector2 v2) -{ - Vector2 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector2 Vector2Max(Vector2 v1, Vector2 v2) -{ - Vector2 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - - return result; -} - -// Rotate vector by angle -RMAPI Vector2 Vector2Rotate(Vector2 v, float angle) -{ - Vector2 result = { 0 }; - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.x = v.x*cosres - v.y*sinres; - result.y = v.x*sinres + v.y*cosres; - - return result; -} - -// Move Vector towards target -RMAPI Vector2 Vector2MoveTowards(Vector2 v, Vector2 target, float maxDistance) -{ - Vector2 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float value = (dx*dx) + (dy*dy); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - - return result; -} - -// Invert the given vector -RMAPI Vector2 Vector2Invert(Vector2 v) -{ - Vector2 result = { 1.0f/v.x, 1.0f/v.y }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector2 Vector2Clamp(Vector2 v, Vector2 min, Vector2 max) -{ - Vector2 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - - return result; -} - -// Clamp the magnitude of the vector between two min and max values -RMAPI Vector2 Vector2ClampValue(Vector2 v, float min, float max) -{ - Vector2 result = v; - - float length = (v.x*v.x) + (v.y*v.y); - if (length > 0.0f) - { - length = sqrtf(length); - - float scale = 1; // By default, 1 as the neutral element. - if (length < min) - { - scale = min/length; - } - else if (length > max) - { - scale = max/length; - } - - result.x = v.x*scale; - result.y = v.y*scale; - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector2Equals(Vector2 p, Vector2 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))); - - return result; -} - -// Compute the direction of a refracted ray -// v: normalized direction of the incoming ray -// n: normalized normal vector of the interface of two optical media -// r: ratio of the refractive index of the medium from where the ray comes -// to the refractive index of the medium on the other side of the surface -RMAPI Vector2 Vector2Refract(Vector2 v, Vector2 n, float r) -{ - Vector2 result = { 0 }; - - float dot = v.x*n.x + v.y*n.y; - float d = 1.0f - r*r*(1.0f - dot*dot); - - if (d >= 0.0f) - { - d = sqrtf(d); - v.x = r*v.x - (r*dot + d)*n.x; - v.y = r*v.y - (r*dot + d)*n.y; - - result = v; - } - - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector3 math -//---------------------------------------------------------------------------------- - -// Vector with components value 0.0f -RMAPI Vector3 Vector3Zero(void) -{ - Vector3 result = { 0.0f, 0.0f, 0.0f }; - - return result; -} - -// Vector with components value 1.0f -RMAPI Vector3 Vector3One(void) -{ - Vector3 result = { 1.0f, 1.0f, 1.0f }; - - return result; -} - -// Add two vectors -RMAPI Vector3 Vector3Add(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x + v2.x, v1.y + v2.y, v1.z + v2.z }; - - return result; -} - -// Add vector and float value -RMAPI Vector3 Vector3AddValue(Vector3 v, float add) -{ - Vector3 result = { v.x + add, v.y + add, v.z + add }; - - return result; -} - -// Subtract two vectors -RMAPI Vector3 Vector3Subtract(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x - v2.x, v1.y - v2.y, v1.z - v2.z }; - - return result; -} - -// Subtract vector by float value -RMAPI Vector3 Vector3SubtractValue(Vector3 v, float sub) -{ - Vector3 result = { v.x - sub, v.y - sub, v.z - sub }; - - return result; -} - -// Multiply vector by scalar -RMAPI Vector3 Vector3Scale(Vector3 v, float scalar) -{ - Vector3 result = { v.x*scalar, v.y*scalar, v.z*scalar }; - - return result; -} - -// Multiply vector by vector -RMAPI Vector3 Vector3Multiply(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z }; - - return result; -} - -// Calculate two vectors cross product -RMAPI Vector3 Vector3CrossProduct(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - - return result; -} - -// Calculate one vector perpendicular vector -RMAPI Vector3 Vector3Perpendicular(Vector3 v) -{ - Vector3 result = { 0 }; - - float min = fabsf(v.x); - Vector3 cardinalAxis = {1.0f, 0.0f, 0.0f}; - - if (fabsf(v.y) < min) - { - min = fabsf(v.y); - Vector3 tmp = {0.0f, 1.0f, 0.0f}; - cardinalAxis = tmp; - } - - if (fabsf(v.z) < min) - { - Vector3 tmp = {0.0f, 0.0f, 1.0f}; - cardinalAxis = tmp; - } - - // Cross product between vectors - result.x = v.y*cardinalAxis.z - v.z*cardinalAxis.y; - result.y = v.z*cardinalAxis.x - v.x*cardinalAxis.z; - result.z = v.x*cardinalAxis.y - v.y*cardinalAxis.x; - - return result; -} - -// Calculate vector length -RMAPI float Vector3Length(const Vector3 v) -{ - float result = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - - return result; -} - -// Calculate vector square length -RMAPI float Vector3LengthSqr(const Vector3 v) -{ - float result = v.x*v.x + v.y*v.y + v.z*v.z; - - return result; -} - -// Calculate two vectors dot product -RMAPI float Vector3DotProduct(Vector3 v1, Vector3 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector3Distance(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = sqrtf(dx*dx + dy*dy + dz*dz); - - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector3DistanceSqr(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - float dx = v2.x - v1.x; - float dy = v2.y - v1.y; - float dz = v2.z - v1.z; - result = dx*dx + dy*dy + dz*dz; - - return result; -} - -// Calculate angle between two vectors -RMAPI float Vector3Angle(Vector3 v1, Vector3 v2) -{ - float result = 0.0f; - - Vector3 cross = { v1.y*v2.z - v1.z*v2.y, v1.z*v2.x - v1.x*v2.z, v1.x*v2.y - v1.y*v2.x }; - float len = sqrtf(cross.x*cross.x + cross.y*cross.y + cross.z*cross.z); - float dot = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - result = atan2f(len, dot); - - return result; -} - -// Negate provided vector (invert direction) -RMAPI Vector3 Vector3Negate(Vector3 v) -{ - Vector3 result = { -v.x, -v.y, -v.z }; - - return result; -} - -// Divide vector by vector -RMAPI Vector3 Vector3Divide(Vector3 v1, Vector3 v2) -{ - Vector3 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z }; - - return result; -} - -// Normalize provided vector -RMAPI Vector3 Vector3Normalize(Vector3 v) -{ - Vector3 result = v; - - float length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length != 0.0f) - { - float ilength = 1.0f/length; - - result.x *= ilength; - result.y *= ilength; - result.z *= ilength; - } - - return result; -} - -//Calculate the projection of the vector v1 on to v2 -RMAPI Vector3 Vector3Project(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v2.x*mag; - result.y = v2.y*mag; - result.z = v2.z*mag; - - return result; -} - -//Calculate the rejection of the vector v1 on to v2 -RMAPI Vector3 Vector3Reject(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - float v1dv2 = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z); - float v2dv2 = (v2.x*v2.x + v2.y*v2.y + v2.z*v2.z); - - float mag = v1dv2/v2dv2; - - result.x = v1.x - (v2.x*mag); - result.y = v1.y - (v2.y*mag); - result.z = v1.z - (v2.z*mag); - - return result; -} - -// Orthonormalize provided vectors -// Makes vectors normalized and orthogonal to each other -// Gram-Schmidt function implementation -RMAPI void Vector3OrthoNormalize(Vector3 *v1, Vector3 *v2) -{ - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(*v1); - Vector3 v = *v1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - v1->x *= ilength; - v1->y *= ilength; - v1->z *= ilength; - - // Vector3CrossProduct(*v1, *v2) - Vector3 vn1 = { v1->y*v2->z - v1->z*v2->y, v1->z*v2->x - v1->x*v2->z, v1->x*v2->y - v1->y*v2->x }; - - // Vector3Normalize(vn1); - v = vn1; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vn1.x *= ilength; - vn1.y *= ilength; - vn1.z *= ilength; - - // Vector3CrossProduct(vn1, *v1) - Vector3 vn2 = { vn1.y*v1->z - vn1.z*v1->y, vn1.z*v1->x - vn1.x*v1->z, vn1.x*v1->y - vn1.y*v1->x }; - - *v2 = vn2; -} - -// Transforms a Vector3 by a given Matrix -RMAPI Vector3 Vector3Transform(Vector3 v, Matrix mat) -{ - Vector3 result = { 0 }; - - float x = v.x; - float y = v.y; - float z = v.z; - - result.x = mat.m0*x + mat.m4*y + mat.m8*z + mat.m12; - result.y = mat.m1*x + mat.m5*y + mat.m9*z + mat.m13; - result.z = mat.m2*x + mat.m6*y + mat.m10*z + mat.m14; - - return result; -} - -// Transform a vector by quaternion rotation -RMAPI Vector3 Vector3RotateByQuaternion(Vector3 v, Quaternion q) -{ - Vector3 result = { 0 }; - - result.x = v.x*(q.x*q.x + q.w*q.w - q.y*q.y - q.z*q.z) + v.y*(2*q.x*q.y - 2*q.w*q.z) + v.z*(2*q.x*q.z + 2*q.w*q.y); - result.y = v.x*(2*q.w*q.z + 2*q.x*q.y) + v.y*(q.w*q.w - q.x*q.x + q.y*q.y - q.z*q.z) + v.z*(-2*q.w*q.x + 2*q.y*q.z); - result.z = v.x*(-2*q.w*q.y + 2*q.x*q.z) + v.y*(2*q.w*q.x + 2*q.y*q.z)+ v.z*(q.w*q.w - q.x*q.x - q.y*q.y + q.z*q.z); - - return result; -} - -// Rotates a vector around an axis -RMAPI Vector3 Vector3RotateByAxisAngle(Vector3 v, Vector3 axis, float angle) -{ - // Using Euler-Rodrigues Formula - // Ref.: https://en.wikipedia.org/w/index.php?title=Euler%E2%80%93Rodrigues_formula - - Vector3 result = v; - - // Vector3Normalize(axis); - float length = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - angle /= 2.0f; - float a = sinf(angle); - float b = axis.x*a; - float c = axis.y*a; - float d = axis.z*a; - a = cosf(angle); - Vector3 w = { b, c, d }; - - // Vector3CrossProduct(w, v) - Vector3 wv = { w.y*v.z - w.z*v.y, w.z*v.x - w.x*v.z, w.x*v.y - w.y*v.x }; - - // Vector3CrossProduct(w, wv) - Vector3 wwv = { w.y*wv.z - w.z*wv.y, w.z*wv.x - w.x*wv.z, w.x*wv.y - w.y*wv.x }; - - // Vector3Scale(wv, 2*a) - a *= 2; - wv.x *= a; - wv.y *= a; - wv.z *= a; - - // Vector3Scale(wwv, 2) - wwv.x *= 2; - wwv.y *= 2; - wwv.z *= 2; - - result.x += wv.x; - result.y += wv.y; - result.z += wv.z; - - result.x += wwv.x; - result.y += wwv.y; - result.z += wwv.z; - - return result; -} - -// Move Vector towards target -RMAPI Vector3 Vector3MoveTowards(Vector3 v, Vector3 target, float maxDistance) -{ - Vector3 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float dz = target.z - v.z; - float value = (dx*dx) + (dy*dy) + (dz*dz); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - result.z = v.z + dz/dist*maxDistance; - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector3 Vector3Lerp(Vector3 v1, Vector3 v2, float amount) -{ - Vector3 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - - return result; -} - -// Calculate cubic hermite interpolation between two vectors and their tangents -// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic -RMAPI Vector3 Vector3CubicHermite(Vector3 v1, Vector3 tangent1, Vector3 v2, Vector3 tangent2, float amount) -{ - Vector3 result = { 0 }; - - float amountPow2 = amount*amount; - float amountPow3 = amount*amount*amount; - - result.x = (2*amountPow3 - 3*amountPow2 + 1)*v1.x + (amountPow3 - 2*amountPow2 + amount)*tangent1.x + (-2*amountPow3 + 3*amountPow2)*v2.x + (amountPow3 - amountPow2)*tangent2.x; - result.y = (2*amountPow3 - 3*amountPow2 + 1)*v1.y + (amountPow3 - 2*amountPow2 + amount)*tangent1.y + (-2*amountPow3 + 3*amountPow2)*v2.y + (amountPow3 - amountPow2)*tangent2.y; - result.z = (2*amountPow3 - 3*amountPow2 + 1)*v1.z + (amountPow3 - 2*amountPow2 + amount)*tangent1.z + (-2*amountPow3 + 3*amountPow2)*v2.z + (amountPow3 - amountPow2)*tangent2.z; - - return result; -} - -// Calculate reflected vector to normal -RMAPI Vector3 Vector3Reflect(Vector3 v, Vector3 normal) -{ - Vector3 result = { 0 }; - - // I is the original vector - // N is the normal of the incident plane - // R = I - (2*N*(DotProduct[I, N])) - - float dotProduct = (v.x*normal.x + v.y*normal.y + v.z*normal.z); - - result.x = v.x - (2.0f*normal.x)*dotProduct; - result.y = v.y - (2.0f*normal.y)*dotProduct; - result.z = v.z - (2.0f*normal.z)*dotProduct; - - return result; -} - -// Get min value for each pair of components -RMAPI Vector3 Vector3Min(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - result.z = fminf(v1.z, v2.z); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector3 Vector3Max(Vector3 v1, Vector3 v2) -{ - Vector3 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - result.z = fmaxf(v1.z, v2.z); - - return result; -} - -// Compute barycenter coordinates (u, v, w) for point p with respect to triangle (a, b, c) -// NOTE: Assumes P is on the plane of the triangle -RMAPI Vector3 Vector3Barycenter(Vector3 p, Vector3 a, Vector3 b, Vector3 c) -{ - Vector3 result = { 0 }; - - Vector3 v0 = { b.x - a.x, b.y - a.y, b.z - a.z }; // Vector3Subtract(b, a) - Vector3 v1 = { c.x - a.x, c.y - a.y, c.z - a.z }; // Vector3Subtract(c, a) - Vector3 v2 = { p.x - a.x, p.y - a.y, p.z - a.z }; // Vector3Subtract(p, a) - float d00 = (v0.x*v0.x + v0.y*v0.y + v0.z*v0.z); // Vector3DotProduct(v0, v0) - float d01 = (v0.x*v1.x + v0.y*v1.y + v0.z*v1.z); // Vector3DotProduct(v0, v1) - float d11 = (v1.x*v1.x + v1.y*v1.y + v1.z*v1.z); // Vector3DotProduct(v1, v1) - float d20 = (v2.x*v0.x + v2.y*v0.y + v2.z*v0.z); // Vector3DotProduct(v2, v0) - float d21 = (v2.x*v1.x + v2.y*v1.y + v2.z*v1.z); // Vector3DotProduct(v2, v1) - - float denom = d00*d11 - d01*d01; - - result.y = (d11*d20 - d01*d21)/denom; - result.z = (d00*d21 - d01*d20)/denom; - result.x = 1.0f - (result.z + result.y); - - return result; -} - -// Projects a Vector3 from screen space into object space -// NOTE: We are avoiding calling other raymath functions despite available -RMAPI Vector3 Vector3Unproject(Vector3 source, Matrix projection, Matrix view) -{ - Vector3 result = { 0 }; - - // Calculate unprojected matrix (multiply view matrix by projection matrix) and invert it - Matrix matViewProj = { // MatrixMultiply(view, projection); - view.m0*projection.m0 + view.m1*projection.m4 + view.m2*projection.m8 + view.m3*projection.m12, - view.m0*projection.m1 + view.m1*projection.m5 + view.m2*projection.m9 + view.m3*projection.m13, - view.m0*projection.m2 + view.m1*projection.m6 + view.m2*projection.m10 + view.m3*projection.m14, - view.m0*projection.m3 + view.m1*projection.m7 + view.m2*projection.m11 + view.m3*projection.m15, - view.m4*projection.m0 + view.m5*projection.m4 + view.m6*projection.m8 + view.m7*projection.m12, - view.m4*projection.m1 + view.m5*projection.m5 + view.m6*projection.m9 + view.m7*projection.m13, - view.m4*projection.m2 + view.m5*projection.m6 + view.m6*projection.m10 + view.m7*projection.m14, - view.m4*projection.m3 + view.m5*projection.m7 + view.m6*projection.m11 + view.m7*projection.m15, - view.m8*projection.m0 + view.m9*projection.m4 + view.m10*projection.m8 + view.m11*projection.m12, - view.m8*projection.m1 + view.m9*projection.m5 + view.m10*projection.m9 + view.m11*projection.m13, - view.m8*projection.m2 + view.m9*projection.m6 + view.m10*projection.m10 + view.m11*projection.m14, - view.m8*projection.m3 + view.m9*projection.m7 + view.m10*projection.m11 + view.m11*projection.m15, - view.m12*projection.m0 + view.m13*projection.m4 + view.m14*projection.m8 + view.m15*projection.m12, - view.m12*projection.m1 + view.m13*projection.m5 + view.m14*projection.m9 + view.m15*projection.m13, - view.m12*projection.m2 + view.m13*projection.m6 + view.m14*projection.m10 + view.m15*projection.m14, - view.m12*projection.m3 + view.m13*projection.m7 + view.m14*projection.m11 + view.m15*projection.m15 }; - - // Calculate inverted matrix -> MatrixInvert(matViewProj); - // Cache the matrix values (speed optimization) - float a00 = matViewProj.m0, a01 = matViewProj.m1, a02 = matViewProj.m2, a03 = matViewProj.m3; - float a10 = matViewProj.m4, a11 = matViewProj.m5, a12 = matViewProj.m6, a13 = matViewProj.m7; - float a20 = matViewProj.m8, a21 = matViewProj.m9, a22 = matViewProj.m10, a23 = matViewProj.m11; - float a30 = matViewProj.m12, a31 = matViewProj.m13, a32 = matViewProj.m14, a33 = matViewProj.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - Matrix matViewProjInv = { - (a11*b11 - a12*b10 + a13*b09)*invDet, - (-a01*b11 + a02*b10 - a03*b09)*invDet, - (a31*b05 - a32*b04 + a33*b03)*invDet, - (-a21*b05 + a22*b04 - a23*b03)*invDet, - (-a10*b11 + a12*b08 - a13*b07)*invDet, - (a00*b11 - a02*b08 + a03*b07)*invDet, - (-a30*b05 + a32*b02 - a33*b01)*invDet, - (a20*b05 - a22*b02 + a23*b01)*invDet, - (a10*b10 - a11*b08 + a13*b06)*invDet, - (-a00*b10 + a01*b08 - a03*b06)*invDet, - (a30*b04 - a31*b02 + a33*b00)*invDet, - (-a20*b04 + a21*b02 - a23*b00)*invDet, - (-a10*b09 + a11*b07 - a12*b06)*invDet, - (a00*b09 - a01*b07 + a02*b06)*invDet, - (-a30*b03 + a31*b01 - a32*b00)*invDet, - (a20*b03 - a21*b01 + a22*b00)*invDet }; - - // Create quaternion from source point - Quaternion quat = { source.x, source.y, source.z, 1.0f }; - - // Multiply quat point by unprojecte matrix - Quaternion qtransformed = { // QuaternionTransform(quat, matViewProjInv) - matViewProjInv.m0*quat.x + matViewProjInv.m4*quat.y + matViewProjInv.m8*quat.z + matViewProjInv.m12*quat.w, - matViewProjInv.m1*quat.x + matViewProjInv.m5*quat.y + matViewProjInv.m9*quat.z + matViewProjInv.m13*quat.w, - matViewProjInv.m2*quat.x + matViewProjInv.m6*quat.y + matViewProjInv.m10*quat.z + matViewProjInv.m14*quat.w, - matViewProjInv.m3*quat.x + matViewProjInv.m7*quat.y + matViewProjInv.m11*quat.z + matViewProjInv.m15*quat.w }; - - // Normalized world points in vectors - result.x = qtransformed.x/qtransformed.w; - result.y = qtransformed.y/qtransformed.w; - result.z = qtransformed.z/qtransformed.w; - - return result; -} - -// Get Vector3 as float array -RMAPI float3 Vector3ToFloatV(Vector3 v) -{ - float3 buffer = { 0 }; - - buffer.v[0] = v.x; - buffer.v[1] = v.y; - buffer.v[2] = v.z; - - return buffer; -} - -// Invert the given vector -RMAPI Vector3 Vector3Invert(Vector3 v) -{ - Vector3 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z }; - - return result; -} - -// Clamp the components of the vector between -// min and max values specified by the given vectors -RMAPI Vector3 Vector3Clamp(Vector3 v, Vector3 min, Vector3 max) -{ - Vector3 result = { 0 }; - - result.x = fminf(max.x, fmaxf(min.x, v.x)); - result.y = fminf(max.y, fmaxf(min.y, v.y)); - result.z = fminf(max.z, fmaxf(min.z, v.z)); - - return result; -} - -// Clamp the magnitude of the vector between two values -RMAPI Vector3 Vector3ClampValue(Vector3 v, float min, float max) -{ - Vector3 result = v; - - float length = (v.x*v.x) + (v.y*v.y) + (v.z*v.z); - if (length > 0.0f) - { - length = sqrtf(length); - - float scale = 1; // By default, 1 as the neutral element. - if (length < min) - { - scale = min/length; - } - else if (length > max) - { - scale = max/length; - } - - result.x = v.x*scale; - result.y = v.y*scale; - result.z = v.z*scale; - } - - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector3Equals(Vector3 p, Vector3 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))); - - return result; -} - -// Compute the direction of a refracted ray -// v: normalized direction of the incoming ray -// n: normalized normal vector of the interface of two optical media -// r: ratio of the refractive index of the medium from where the ray comes -// to the refractive index of the medium on the other side of the surface -RMAPI Vector3 Vector3Refract(Vector3 v, Vector3 n, float r) -{ - Vector3 result = { 0 }; - - float dot = v.x*n.x + v.y*n.y + v.z*n.z; - float d = 1.0f - r*r*(1.0f - dot*dot); - - if (d >= 0.0f) - { - d = sqrtf(d); - v.x = r*v.x - (r*dot + d)*n.x; - v.y = r*v.y - (r*dot + d)*n.y; - v.z = r*v.z - (r*dot + d)*n.z; - - result = v; - } - - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vector4 math -//---------------------------------------------------------------------------------- - -RMAPI Vector4 Vector4Zero(void) -{ - Vector4 result = { 0.0f, 0.0f, 0.0f, 0.0f }; - return result; -} - -RMAPI Vector4 Vector4One(void) -{ - Vector4 result = { 1.0f, 1.0f, 1.0f, 1.0f }; - return result; -} - -RMAPI Vector4 Vector4Add(Vector4 v1, Vector4 v2) -{ - Vector4 result = { - v1.x + v2.x, - v1.y + v2.y, - v1.z + v2.z, - v1.w + v2.w - }; - return result; -} - -RMAPI Vector4 Vector4AddValue(Vector4 v, float add) -{ - Vector4 result = { - v.x + add, - v.y + add, - v.z + add, - v.w + add - }; - return result; -} - -RMAPI Vector4 Vector4Subtract(Vector4 v1, Vector4 v2) -{ - Vector4 result = { - v1.x - v2.x, - v1.y - v2.y, - v1.z - v2.z, - v1.w - v2.w - }; - return result; -} - -RMAPI Vector4 Vector4SubtractValue(Vector4 v, float add) -{ - Vector4 result = { - v.x - add, - v.y - add, - v.z - add, - v.w - add - }; - return result; -} - -RMAPI float Vector4Length(Vector4 v) -{ - float result = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); - return result; -} - -RMAPI float Vector4LengthSqr(Vector4 v) -{ - float result = (v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w); - return result; -} - -RMAPI float Vector4DotProduct(Vector4 v1, Vector4 v2) -{ - float result = (v1.x*v2.x + v1.y*v2.y + v1.z*v2.z + v1.w*v2.w); - return result; -} - -// Calculate distance between two vectors -RMAPI float Vector4Distance(Vector4 v1, Vector4 v2) -{ - float result = sqrtf( - (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + - (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w)); - return result; -} - -// Calculate square distance between two vectors -RMAPI float Vector4DistanceSqr(Vector4 v1, Vector4 v2) -{ - float result = - (v1.x - v2.x)*(v1.x - v2.x) + (v1.y - v2.y)*(v1.y - v2.y) + - (v1.z - v2.z)*(v1.z - v2.z) + (v1.w - v2.w)*(v1.w - v2.w); - - return result; -} - -RMAPI Vector4 Vector4Scale(Vector4 v, float scale) -{ - Vector4 result = { v.x*scale, v.y*scale, v.z*scale, v.w*scale }; - return result; -} - -// Multiply vector by vector -RMAPI Vector4 Vector4Multiply(Vector4 v1, Vector4 v2) -{ - Vector4 result = { v1.x*v2.x, v1.y*v2.y, v1.z*v2.z, v1.w*v2.w }; - return result; -} - -// Negate vector -RMAPI Vector4 Vector4Negate(Vector4 v) -{ - Vector4 result = { -v.x, -v.y, -v.z, -v.w }; - return result; -} - -// Divide vector by vector -RMAPI Vector4 Vector4Divide(Vector4 v1, Vector4 v2) -{ - Vector4 result = { v1.x/v2.x, v1.y/v2.y, v1.z/v2.z, v1.w/v2.w }; - return result; -} - -// Normalize provided vector -RMAPI Vector4 Vector4Normalize(Vector4 v) -{ - Vector4 result = { 0 }; - float length = sqrtf((v.x*v.x) + (v.y*v.y) + (v.z*v.z) + (v.w*v.w)); - - if (length > 0) - { - float ilength = 1.0f/length; - result.x = v.x*ilength; - result.y = v.y*ilength; - result.z = v.z*ilength; - result.w = v.w*ilength; - } - - return result; -} - -// Get min value for each pair of components -RMAPI Vector4 Vector4Min(Vector4 v1, Vector4 v2) -{ - Vector4 result = { 0 }; - - result.x = fminf(v1.x, v2.x); - result.y = fminf(v1.y, v2.y); - result.z = fminf(v1.z, v2.z); - result.w = fminf(v1.w, v2.w); - - return result; -} - -// Get max value for each pair of components -RMAPI Vector4 Vector4Max(Vector4 v1, Vector4 v2) -{ - Vector4 result = { 0 }; - - result.x = fmaxf(v1.x, v2.x); - result.y = fmaxf(v1.y, v2.y); - result.z = fmaxf(v1.z, v2.z); - result.w = fmaxf(v1.w, v2.w); - - return result; -} - -// Calculate linear interpolation between two vectors -RMAPI Vector4 Vector4Lerp(Vector4 v1, Vector4 v2, float amount) -{ - Vector4 result = { 0 }; - - result.x = v1.x + amount*(v2.x - v1.x); - result.y = v1.y + amount*(v2.y - v1.y); - result.z = v1.z + amount*(v2.z - v1.z); - result.w = v1.w + amount*(v2.w - v1.w); - - return result; -} - -// Move Vector towards target -RMAPI Vector4 Vector4MoveTowards(Vector4 v, Vector4 target, float maxDistance) -{ - Vector4 result = { 0 }; - - float dx = target.x - v.x; - float dy = target.y - v.y; - float dz = target.z - v.z; - float dw = target.w - v.w; - float value = (dx*dx) + (dy*dy) + (dz*dz) + (dw*dw); - - if ((value == 0) || ((maxDistance >= 0) && (value <= maxDistance*maxDistance))) return target; - - float dist = sqrtf(value); - - result.x = v.x + dx/dist*maxDistance; - result.y = v.y + dy/dist*maxDistance; - result.z = v.z + dz/dist*maxDistance; - result.w = v.w + dw/dist*maxDistance; - - return result; -} - -// Invert the given vector -RMAPI Vector4 Vector4Invert(Vector4 v) -{ - Vector4 result = { 1.0f/v.x, 1.0f/v.y, 1.0f/v.z, 1.0f/v.w }; - return result; -} - -// Check whether two given vectors are almost equal -RMAPI int Vector4Equals(Vector4 p, Vector4 q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = ((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w))))); - return result; -} - - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix math -//---------------------------------------------------------------------------------- - -// Compute matrix determinant -RMAPI float MatrixDeterminant(Matrix mat) -{ - float result = 0.0f; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - result = a30*a21*a12*a03 - a20*a31*a12*a03 - a30*a11*a22*a03 + a10*a31*a22*a03 + - a20*a11*a32*a03 - a10*a21*a32*a03 - a30*a21*a02*a13 + a20*a31*a02*a13 + - a30*a01*a22*a13 - a00*a31*a22*a13 - a20*a01*a32*a13 + a00*a21*a32*a13 + - a30*a11*a02*a23 - a10*a31*a02*a23 - a30*a01*a12*a23 + a00*a31*a12*a23 + - a10*a01*a32*a23 - a00*a11*a32*a23 - a20*a11*a02*a33 + a10*a21*a02*a33 + - a20*a01*a12*a33 - a00*a21*a12*a33 - a10*a01*a22*a33 + a00*a11*a22*a33; - - return result; -} - -// Get the trace of the matrix (sum of the values along the diagonal) -RMAPI float MatrixTrace(Matrix mat) -{ - float result = (mat.m0 + mat.m5 + mat.m10 + mat.m15); - - return result; -} - -// Transposes provided matrix -RMAPI Matrix MatrixTranspose(Matrix mat) -{ - Matrix result = { 0 }; - - result.m0 = mat.m0; - result.m1 = mat.m4; - result.m2 = mat.m8; - result.m3 = mat.m12; - result.m4 = mat.m1; - result.m5 = mat.m5; - result.m6 = mat.m9; - result.m7 = mat.m13; - result.m8 = mat.m2; - result.m9 = mat.m6; - result.m10 = mat.m10; - result.m11 = mat.m14; - result.m12 = mat.m3; - result.m13 = mat.m7; - result.m14 = mat.m11; - result.m15 = mat.m15; - - return result; -} - -// Invert provided matrix -RMAPI Matrix MatrixInvert(Matrix mat) -{ - Matrix result = { 0 }; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - return result; -} - -// Get identity matrix -RMAPI Matrix MatrixIdentity(void) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Add two matrices -RMAPI Matrix MatrixAdd(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 + right.m0; - result.m1 = left.m1 + right.m1; - result.m2 = left.m2 + right.m2; - result.m3 = left.m3 + right.m3; - result.m4 = left.m4 + right.m4; - result.m5 = left.m5 + right.m5; - result.m6 = left.m6 + right.m6; - result.m7 = left.m7 + right.m7; - result.m8 = left.m8 + right.m8; - result.m9 = left.m9 + right.m9; - result.m10 = left.m10 + right.m10; - result.m11 = left.m11 + right.m11; - result.m12 = left.m12 + right.m12; - result.m13 = left.m13 + right.m13; - result.m14 = left.m14 + right.m14; - result.m15 = left.m15 + right.m15; - - return result; -} - -// Subtract two matrices (left - right) -RMAPI Matrix MatrixSubtract(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0 - right.m0; - result.m1 = left.m1 - right.m1; - result.m2 = left.m2 - right.m2; - result.m3 = left.m3 - right.m3; - result.m4 = left.m4 - right.m4; - result.m5 = left.m5 - right.m5; - result.m6 = left.m6 - right.m6; - result.m7 = left.m7 - right.m7; - result.m8 = left.m8 - right.m8; - result.m9 = left.m9 - right.m9; - result.m10 = left.m10 - right.m10; - result.m11 = left.m11 - right.m11; - result.m12 = left.m12 - right.m12; - result.m13 = left.m13 - right.m13; - result.m14 = left.m14 - right.m14; - result.m15 = left.m15 - right.m15; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -RMAPI Matrix MatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Get translation matrix -RMAPI Matrix MatrixTranslate(float x, float y, float z) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Create rotation matrix from axis and angle -// NOTE: Angle should be provided in radians -RMAPI Matrix MatrixRotate(Vector3 axis, float angle) -{ - Matrix result = { 0 }; - - float x = axis.x, y = axis.y, z = axis.z; - - float lengthSquared = x*x + y*y + z*z; - - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float ilength = 1.0f/sqrtf(lengthSquared); - x *= ilength; - y *= ilength; - z *= ilength; - } - - float sinres = sinf(angle); - float cosres = cosf(angle); - float t = 1.0f - cosres; - - result.m0 = x*x*t + cosres; - result.m1 = y*x*t + z*sinres; - result.m2 = z*x*t - y*sinres; - result.m3 = 0.0f; - - result.m4 = x*y*t - z*sinres; - result.m5 = y*y*t + cosres; - result.m6 = z*y*t + x*sinres; - result.m7 = 0.0f; - - result.m8 = x*z*t + y*sinres; - result.m9 = y*z*t - x*sinres; - result.m10 = z*z*t + cosres; - result.m11 = 0.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = 0.0f; - result.m15 = 1.0f; - - return result; -} - -// Get x-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateX(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m5 = cosres; - result.m6 = sinres; - result.m9 = -sinres; - result.m10 = cosres; - - return result; -} - -// Get y-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateY(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m2 = -sinres; - result.m8 = sinres; - result.m10 = cosres; - - return result; -} - -// Get z-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZ(float angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosres = cosf(angle); - float sinres = sinf(angle); - - result.m0 = cosres; - result.m1 = sinres; - result.m4 = -sinres; - result.m5 = cosres; - - return result; -} - - -// Get xyz-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateXYZ(Vector3 angle) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float cosz = cosf(-angle.z); - float sinz = sinf(-angle.z); - float cosy = cosf(-angle.y); - float siny = sinf(-angle.y); - float cosx = cosf(-angle.x); - float sinx = sinf(-angle.x); - - result.m0 = cosz*cosy; - result.m1 = (cosz*siny*sinx) - (sinz*cosx); - result.m2 = (cosz*siny*cosx) + (sinz*sinx); - - result.m4 = sinz*cosy; - result.m5 = (sinz*siny*sinx) + (cosz*cosx); - result.m6 = (sinz*siny*cosx) - (cosz*sinx); - - result.m8 = -siny; - result.m9 = cosy*sinx; - result.m10= cosy*cosx; - - return result; -} - -// Get zyx-rotation matrix -// NOTE: Angle must be provided in radians -RMAPI Matrix MatrixRotateZYX(Vector3 angle) -{ - Matrix result = { 0 }; - - float cz = cosf(angle.z); - float sz = sinf(angle.z); - float cy = cosf(angle.y); - float sy = sinf(angle.y); - float cx = cosf(angle.x); - float sx = sinf(angle.x); - - result.m0 = cz*cy; - result.m4 = cz*sy*sx - cx*sz; - result.m8 = sz*sx + cz*cx*sy; - result.m12 = 0; - - result.m1 = cy*sz; - result.m5 = cz*cx + sz*sy*sx; - result.m9 = cx*sz*sy - cz*sx; - result.m13 = 0; - - result.m2 = -sy; - result.m6 = cy*sx; - result.m10 = cy*cx; - result.m14 = 0; - - result.m3 = 0; - result.m7 = 0; - result.m11 = 0; - result.m15 = 1; - - return result; -} - -// Get scaling matrix -RMAPI Matrix MatrixScale(float x, float y, float z) -{ - Matrix result = { x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Get perspective projection matrix -RMAPI Matrix MatrixFrustum(double left, double right, double bottom, double top, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = ((float)nearPlane*2.0f)/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - - result.m4 = 0.0f; - result.m5 = ((float)nearPlane*2.0f)/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)farPlane + (float)nearPlane)/fn; - result.m11 = -1.0f; - - result.m12 = 0.0f; - result.m13 = 0.0f; - result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; - result.m15 = 0.0f; - - return result; -} - -// Get perspective projection matrix -// NOTE: Fovy angle must be provided in radians -RMAPI Matrix MatrixPerspective(double fovY, double aspect, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - double top = nearPlane*tan(fovY*0.5); - double bottom = -top; - double right = top*aspect; - double left = -right; - - // MatrixFrustum(-right, right, -top, top, near, far); - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = ((float)nearPlane*2.0f)/rl; - result.m5 = ((float)nearPlane*2.0f)/tb; - result.m8 = ((float)right + (float)left)/rl; - result.m9 = ((float)top + (float)bottom)/tb; - result.m10 = -((float)farPlane + (float)nearPlane)/fn; - result.m11 = -1.0f; - result.m14 = -((float)farPlane*(float)nearPlane*2.0f)/fn; - - return result; -} - -// Get orthographic projection matrix -RMAPI Matrix MatrixOrtho(double left, double right, double bottom, double top, double nearPlane, double farPlane) -{ - Matrix result = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(farPlane - nearPlane); - - result.m0 = 2.0f/rl; - result.m1 = 0.0f; - result.m2 = 0.0f; - result.m3 = 0.0f; - result.m4 = 0.0f; - result.m5 = 2.0f/tb; - result.m6 = 0.0f; - result.m7 = 0.0f; - result.m8 = 0.0f; - result.m9 = 0.0f; - result.m10 = -2.0f/fn; - result.m11 = 0.0f; - result.m12 = -((float)left + (float)right)/rl; - result.m13 = -((float)top + (float)bottom)/tb; - result.m14 = -((float)farPlane + (float)nearPlane)/fn; - result.m15 = 1.0f; - - return result; -} - -// Get camera look-at matrix (view matrix) -RMAPI Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up) -{ - Matrix result = { 0 }; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Subtract(eye, target) - Vector3 vz = { eye.x - target.x, eye.y - target.y, eye.z - target.z }; - - // Vector3Normalize(vz) - Vector3 v = vz; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vz.x *= ilength; - vz.y *= ilength; - vz.z *= ilength; - - // Vector3CrossProduct(up, vz) - Vector3 vx = { up.y*vz.z - up.z*vz.y, up.z*vz.x - up.x*vz.z, up.x*vz.y - up.y*vz.x }; - - // Vector3Normalize(x) - v = vx; - length = sqrtf(v.x*v.x + v.y*v.y + v.z*v.z); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - vx.x *= ilength; - vx.y *= ilength; - vx.z *= ilength; - - // Vector3CrossProduct(vz, vx) - Vector3 vy = { vz.y*vx.z - vz.z*vx.y, vz.z*vx.x - vz.x*vx.z, vz.x*vx.y - vz.y*vx.x }; - - result.m0 = vx.x; - result.m1 = vy.x; - result.m2 = vz.x; - result.m3 = 0.0f; - result.m4 = vx.y; - result.m5 = vy.y; - result.m6 = vz.y; - result.m7 = 0.0f; - result.m8 = vx.z; - result.m9 = vy.z; - result.m10 = vz.z; - result.m11 = 0.0f; - result.m12 = -(vx.x*eye.x + vx.y*eye.y + vx.z*eye.z); // Vector3DotProduct(vx, eye) - result.m13 = -(vy.x*eye.x + vy.y*eye.y + vy.z*eye.z); // Vector3DotProduct(vy, eye) - result.m14 = -(vz.x*eye.x + vz.y*eye.y + vz.z*eye.z); // Vector3DotProduct(vz, eye) - result.m15 = 1.0f; - - return result; -} - -// Get float array of matrix data -RMAPI float16 MatrixToFloatV(Matrix mat) -{ - float16 result = { 0 }; - - result.v[0] = mat.m0; - result.v[1] = mat.m1; - result.v[2] = mat.m2; - result.v[3] = mat.m3; - result.v[4] = mat.m4; - result.v[5] = mat.m5; - result.v[6] = mat.m6; - result.v[7] = mat.m7; - result.v[8] = mat.m8; - result.v[9] = mat.m9; - result.v[10] = mat.m10; - result.v[11] = mat.m11; - result.v[12] = mat.m12; - result.v[13] = mat.m13; - result.v[14] = mat.m14; - result.v[15] = mat.m15; - - return result; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Quaternion math -//---------------------------------------------------------------------------------- - -// Add two quaternions -RMAPI Quaternion QuaternionAdd(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x + q2.x, q1.y + q2.y, q1.z + q2.z, q1.w + q2.w}; - - return result; -} - -// Add quaternion and float value -RMAPI Quaternion QuaternionAddValue(Quaternion q, float add) -{ - Quaternion result = {q.x + add, q.y + add, q.z + add, q.w + add}; - - return result; -} - -// Subtract two quaternions -RMAPI Quaternion QuaternionSubtract(Quaternion q1, Quaternion q2) -{ - Quaternion result = {q1.x - q2.x, q1.y - q2.y, q1.z - q2.z, q1.w - q2.w}; - - return result; -} - -// Subtract quaternion and float value -RMAPI Quaternion QuaternionSubtractValue(Quaternion q, float sub) -{ - Quaternion result = {q.x - sub, q.y - sub, q.z - sub, q.w - sub}; - - return result; -} - -// Get identity quaternion -RMAPI Quaternion QuaternionIdentity(void) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - return result; -} - -// Computes the length of a quaternion -RMAPI float QuaternionLength(Quaternion q) -{ - float result = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - - return result; -} - -// Normalize provided quaternion -RMAPI Quaternion QuaternionNormalize(Quaternion q) -{ - Quaternion result = { 0 }; - - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Invert provided quaternion -RMAPI Quaternion QuaternionInvert(Quaternion q) -{ - Quaternion result = q; - - float lengthSq = q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w; - - if (lengthSq != 0.0f) - { - float invLength = 1.0f/lengthSq; - - result.x *= -invLength; - result.y *= -invLength; - result.z *= -invLength; - result.w *= invLength; - } - - return result; -} - -// Calculate two quaternion multiplication -RMAPI Quaternion QuaternionMultiply(Quaternion q1, Quaternion q2) -{ - Quaternion result = { 0 }; - - float qax = q1.x, qay = q1.y, qaz = q1.z, qaw = q1.w; - float qbx = q2.x, qby = q2.y, qbz = q2.z, qbw = q2.w; - - result.x = qax*qbw + qaw*qbx + qay*qbz - qaz*qby; - result.y = qay*qbw + qaw*qby + qaz*qbx - qax*qbz; - result.z = qaz*qbw + qaw*qbz + qax*qby - qay*qbx; - result.w = qaw*qbw - qax*qbx - qay*qby - qaz*qbz; - - return result; -} - -// Scale quaternion by float value -RMAPI Quaternion QuaternionScale(Quaternion q, float mul) -{ - Quaternion result = { 0 }; - - result.x = q.x*mul; - result.y = q.y*mul; - result.z = q.z*mul; - result.w = q.w*mul; - - return result; -} - -// Divide two quaternions -RMAPI Quaternion QuaternionDivide(Quaternion q1, Quaternion q2) -{ - Quaternion result = { q1.x/q2.x, q1.y/q2.y, q1.z/q2.z, q1.w/q2.w }; - - return result; -} - -// Calculate linear interpolation between two quaternions -RMAPI Quaternion QuaternionLerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - return result; -} - -// Calculate slerp-optimized interpolation between two quaternions -RMAPI Quaternion QuaternionNlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - - // QuaternionLerp(q1, q2, amount) - result.x = q1.x + amount*(q2.x - q1.x); - result.y = q1.y + amount*(q2.y - q1.y); - result.z = q1.z + amount*(q2.z - q1.z); - result.w = q1.w + amount*(q2.w - q1.w); - - // QuaternionNormalize(q); - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Calculates spherical linear interpolation between two quaternions -RMAPI Quaternion QuaternionSlerp(Quaternion q1, Quaternion q2, float amount) -{ - Quaternion result = { 0 }; - -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - float cosHalfTheta = q1.x*q2.x + q1.y*q2.y + q1.z*q2.z + q1.w*q2.w; - - if (cosHalfTheta < 0) - { - q2.x = -q2.x; q2.y = -q2.y; q2.z = -q2.z; q2.w = -q2.w; - cosHalfTheta = -cosHalfTheta; - } - - if (fabsf(cosHalfTheta) >= 1.0f) result = q1; - else if (cosHalfTheta > 0.95f) result = QuaternionNlerp(q1, q2, amount); - else - { - float halfTheta = acosf(cosHalfTheta); - float sinHalfTheta = sqrtf(1.0f - cosHalfTheta*cosHalfTheta); - - if (fabsf(sinHalfTheta) < EPSILON) - { - result.x = (q1.x*0.5f + q2.x*0.5f); - result.y = (q1.y*0.5f + q2.y*0.5f); - result.z = (q1.z*0.5f + q2.z*0.5f); - result.w = (q1.w*0.5f + q2.w*0.5f); - } - else - { - float ratioA = sinf((1 - amount)*halfTheta)/sinHalfTheta; - float ratioB = sinf(amount*halfTheta)/sinHalfTheta; - - result.x = (q1.x*ratioA + q2.x*ratioB); - result.y = (q1.y*ratioA + q2.y*ratioB); - result.z = (q1.z*ratioA + q2.z*ratioB); - result.w = (q1.w*ratioA + q2.w*ratioB); - } - } - - return result; -} - -// Calculate quaternion cubic spline interpolation using Cubic Hermite Spline algorithm -// as described in the GLTF 2.0 specification: https://registry.khronos.org/glTF/specs/2.0/glTF-2.0.html#interpolation-cubic -RMAPI Quaternion QuaternionCubicHermiteSpline(Quaternion q1, Quaternion outTangent1, Quaternion q2, Quaternion inTangent2, float t) -{ - float t2 = t*t; - float t3 = t2*t; - float h00 = 2*t3 - 3*t2 + 1; - float h10 = t3 - 2*t2 + t; - float h01 = -2*t3 + 3*t2; - float h11 = t3 - t2; - - Quaternion p0 = QuaternionScale(q1, h00); - Quaternion m0 = QuaternionScale(outTangent1, h10); - Quaternion p1 = QuaternionScale(q2, h01); - Quaternion m1 = QuaternionScale(inTangent2, h11); - - Quaternion result = { 0 }; - - result = QuaternionAdd(p0, m0); - result = QuaternionAdd(result, p1); - result = QuaternionAdd(result, m1); - result = QuaternionNormalize(result); - - return result; -} - -// Calculate quaternion based on the rotation from one vector to another -RMAPI Quaternion QuaternionFromVector3ToVector3(Vector3 from, Vector3 to) -{ - Quaternion result = { 0 }; - - float cos2Theta = (from.x*to.x + from.y*to.y + from.z*to.z); // Vector3DotProduct(from, to) - Vector3 cross = { from.y*to.z - from.z*to.y, from.z*to.x - from.x*to.z, from.x*to.y - from.y*to.x }; // Vector3CrossProduct(from, to) - - result.x = cross.x; - result.y = cross.y; - result.z = cross.z; - result.w = 1.0f + cos2Theta; - - // QuaternionNormalize(q); - // NOTE: Normalize to essentially nlerp the original and identity to 0.5 - Quaternion q = result; - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - - return result; -} - -// Get a quaternion for a given rotation matrix -RMAPI Quaternion QuaternionFromMatrix(Matrix mat) -{ - Quaternion result = { 0 }; - - float fourWSquaredMinus1 = mat.m0 + mat.m5 + mat.m10; - float fourXSquaredMinus1 = mat.m0 - mat.m5 - mat.m10; - float fourYSquaredMinus1 = mat.m5 - mat.m0 - mat.m10; - float fourZSquaredMinus1 = mat.m10 - mat.m0 - mat.m5; - - int biggestIndex = 0; - float fourBiggestSquaredMinus1 = fourWSquaredMinus1; - if (fourXSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourXSquaredMinus1; - biggestIndex = 1; - } - - if (fourYSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourYSquaredMinus1; - biggestIndex = 2; - } - - if (fourZSquaredMinus1 > fourBiggestSquaredMinus1) - { - fourBiggestSquaredMinus1 = fourZSquaredMinus1; - biggestIndex = 3; - } - - float biggestVal = sqrtf(fourBiggestSquaredMinus1 + 1.0f)*0.5f; - float mult = 0.25f/biggestVal; - - switch (biggestIndex) - { - case 0: - result.w = biggestVal; - result.x = (mat.m6 - mat.m9)*mult; - result.y = (mat.m8 - mat.m2)*mult; - result.z = (mat.m1 - mat.m4)*mult; - break; - case 1: - result.x = biggestVal; - result.w = (mat.m6 - mat.m9)*mult; - result.y = (mat.m1 + mat.m4)*mult; - result.z = (mat.m8 + mat.m2)*mult; - break; - case 2: - result.y = biggestVal; - result.w = (mat.m8 - mat.m2)*mult; - result.x = (mat.m1 + mat.m4)*mult; - result.z = (mat.m6 + mat.m9)*mult; - break; - case 3: - result.z = biggestVal; - result.w = (mat.m1 - mat.m4)*mult; - result.x = (mat.m8 + mat.m2)*mult; - result.y = (mat.m6 + mat.m9)*mult; - break; - } - - return result; -} - -// Get a matrix for a given quaternion -RMAPI Matrix QuaternionToMatrix(Quaternion q) -{ - Matrix result = { 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f }; // MatrixIdentity() - - float a2 = q.x*q.x; - float b2 = q.y*q.y; - float c2 = q.z*q.z; - float ac = q.x*q.z; - float ab = q.x*q.y; - float bc = q.y*q.z; - float ad = q.w*q.x; - float bd = q.w*q.y; - float cd = q.w*q.z; - - result.m0 = 1 - 2*(b2 + c2); - result.m1 = 2*(ab + cd); - result.m2 = 2*(ac - bd); - - result.m4 = 2*(ab - cd); - result.m5 = 1 - 2*(a2 + c2); - result.m6 = 2*(bc + ad); - - result.m8 = 2*(ac + bd); - result.m9 = 2*(bc - ad); - result.m10 = 1 - 2*(a2 + b2); - - return result; -} - -// Get rotation quaternion for an angle and axis -// NOTE: Angle must be provided in radians -RMAPI Quaternion QuaternionFromAxisAngle(Vector3 axis, float angle) -{ - Quaternion result = { 0.0f, 0.0f, 0.0f, 1.0f }; - - float axisLength = sqrtf(axis.x*axis.x + axis.y*axis.y + axis.z*axis.z); - - if (axisLength != 0.0f) - { - angle *= 0.5f; - - float length = 0.0f; - float ilength = 0.0f; - - // Vector3Normalize(axis) - length = axisLength; - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - axis.x *= ilength; - axis.y *= ilength; - axis.z *= ilength; - - float sinres = sinf(angle); - float cosres = cosf(angle); - - result.x = axis.x*sinres; - result.y = axis.y*sinres; - result.z = axis.z*sinres; - result.w = cosres; - - // QuaternionNormalize(q); - Quaternion q = result; - length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - ilength = 1.0f/length; - result.x = q.x*ilength; - result.y = q.y*ilength; - result.z = q.z*ilength; - result.w = q.w*ilength; - } - - return result; -} - -// Get the rotation angle and axis for a given quaternion -RMAPI void QuaternionToAxisAngle(Quaternion q, Vector3 *outAxis, float *outAngle) -{ - if (fabsf(q.w) > 1.0f) - { - // QuaternionNormalize(q); - float length = sqrtf(q.x*q.x + q.y*q.y + q.z*q.z + q.w*q.w); - if (length == 0.0f) length = 1.0f; - float ilength = 1.0f/length; - - q.x = q.x*ilength; - q.y = q.y*ilength; - q.z = q.z*ilength; - q.w = q.w*ilength; - } - - Vector3 resAxis = { 0.0f, 0.0f, 0.0f }; - float resAngle = 2.0f*acosf(q.w); - float den = sqrtf(1.0f - q.w*q.w); - - if (den > EPSILON) - { - resAxis.x = q.x/den; - resAxis.y = q.y/den; - resAxis.z = q.z/den; - } - else - { - // This occurs when the angle is zero. - // Not a problem: just set an arbitrary normalized axis. - resAxis.x = 1.0f; - } - - *outAxis = resAxis; - *outAngle = resAngle; -} - -// Get the quaternion equivalent to Euler angles -// NOTE: Rotation order is ZYX -RMAPI Quaternion QuaternionFromEuler(float pitch, float yaw, float roll) -{ - Quaternion result = { 0 }; - - float x0 = cosf(pitch*0.5f); - float x1 = sinf(pitch*0.5f); - float y0 = cosf(yaw*0.5f); - float y1 = sinf(yaw*0.5f); - float z0 = cosf(roll*0.5f); - float z1 = sinf(roll*0.5f); - - result.x = x1*y0*z0 - x0*y1*z1; - result.y = x0*y1*z0 + x1*y0*z1; - result.z = x0*y0*z1 - x1*y1*z0; - result.w = x0*y0*z0 + x1*y1*z1; - - return result; -} - -// Get the Euler angles equivalent to quaternion (roll, pitch, yaw) -// NOTE: Angles are returned in a Vector3 struct in radians -RMAPI Vector3 QuaternionToEuler(Quaternion q) -{ - Vector3 result = { 0 }; - - // Roll (x-axis rotation) - float x0 = 2.0f*(q.w*q.x + q.y*q.z); - float x1 = 1.0f - 2.0f*(q.x*q.x + q.y*q.y); - result.x = atan2f(x0, x1); - - // Pitch (y-axis rotation) - float y0 = 2.0f*(q.w*q.y - q.z*q.x); - y0 = y0 > 1.0f ? 1.0f : y0; - y0 = y0 < -1.0f ? -1.0f : y0; - result.y = asinf(y0); - - // Yaw (z-axis rotation) - float z0 = 2.0f*(q.w*q.z + q.x*q.y); - float z1 = 1.0f - 2.0f*(q.y*q.y + q.z*q.z); - result.z = atan2f(z0, z1); - - return result; -} - -// Transform a quaternion given a transformation matrix -RMAPI Quaternion QuaternionTransform(Quaternion q, Matrix mat) -{ - Quaternion result = { 0 }; - - result.x = mat.m0*q.x + mat.m4*q.y + mat.m8*q.z + mat.m12*q.w; - result.y = mat.m1*q.x + mat.m5*q.y + mat.m9*q.z + mat.m13*q.w; - result.z = mat.m2*q.x + mat.m6*q.y + mat.m10*q.z + mat.m14*q.w; - result.w = mat.m3*q.x + mat.m7*q.y + mat.m11*q.z + mat.m15*q.w; - - return result; -} - -// Check whether two given quaternions are almost equal -RMAPI int QuaternionEquals(Quaternion p, Quaternion q) -{ -#if !defined(EPSILON) - #define EPSILON 0.000001f -#endif - - int result = (((fabsf(p.x - q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y - q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z - q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w - q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))) || - (((fabsf(p.x + q.x)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.x), fabsf(q.x))))) && - ((fabsf(p.y + q.y)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.y), fabsf(q.y))))) && - ((fabsf(p.z + q.z)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.z), fabsf(q.z))))) && - ((fabsf(p.w + q.w)) <= (EPSILON*fmaxf(1.0f, fmaxf(fabsf(p.w), fabsf(q.w)))))); - - return result; -} - -// Decompose a transformation matrix into its rotational, translational and scaling components -RMAPI void MatrixDecompose(Matrix mat, Vector3 *translation, Quaternion *rotation, Vector3 *scale) -{ - // Extract translation. - translation->x = mat.m12; - translation->y = mat.m13; - translation->z = mat.m14; - - // Extract upper-left for determinant computation - const float a = mat.m0; - const float b = mat.m4; - const float c = mat.m8; - const float d = mat.m1; - const float e = mat.m5; - const float f = mat.m9; - const float g = mat.m2; - const float h = mat.m6; - const float i = mat.m10; - const float A = e*i - f*h; - const float B = f*g - d*i; - const float C = d*h - e*g; - - // Extract scale - const float det = a*A + b*B + c*C; - Vector3 abc = { a, b, c }; - Vector3 def = { d, e, f }; - Vector3 ghi = { g, h, i }; - - float scalex = Vector3Length(abc); - float scaley = Vector3Length(def); - float scalez = Vector3Length(ghi); - Vector3 s = { scalex, scaley, scalez }; - - if (det < 0) s = Vector3Negate(s); - - *scale = s; - - // Remove scale from the matrix if it is not close to zero - Matrix clone = mat; - if (!FloatEquals(det, 0)) - { - clone.m0 /= s.x; - clone.m4 /= s.x; - clone.m8 /= s.x; - clone.m1 /= s.y; - clone.m5 /= s.y; - clone.m9 /= s.y; - clone.m2 /= s.z; - clone.m6 /= s.z; - clone.m10 /= s.z; - - // Extract rotation - *rotation = QuaternionFromMatrix(clone); - } - else - { - // Set to identity if close to zero - *rotation = QuaternionIdentity(); - } -} - -#if defined(__cplusplus) && !defined(RAYMATH_DISABLE_CPP_OPERATORS) - -// Optional C++ math operators -//------------------------------------------------------------------------------- - -// Vector2 operators -static constexpr Vector2 Vector2Zeros = { 0, 0 }; -static constexpr Vector2 Vector2Ones = { 1, 1 }; -static constexpr Vector2 Vector2UnitX = { 1, 0 }; -static constexpr Vector2 Vector2UnitY = { 0, 1 }; - -inline Vector2 operator + (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Add(lhs, rhs); -} - -inline const Vector2& operator += (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Add(lhs, rhs); - return lhs; -} - -inline Vector2 operator - (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Subtract(lhs, rhs); -} - -inline const Vector2& operator -= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Subtract(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const float& rhs) -{ - return Vector2Scale(lhs, rhs); -} - -inline const Vector2& operator *= (Vector2& lhs, const float& rhs) -{ - lhs = Vector2Scale(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Multiply(lhs, rhs); -} - -inline const Vector2& operator *= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Multiply(lhs, rhs); - return lhs; -} - -inline Vector2 operator * (const Vector2& lhs, const Matrix& rhs) -{ - return Vector2Transform(lhs, rhs); -} - -inline const Vector2& operator -= (Vector2& lhs, const Matrix& rhs) -{ - lhs = Vector2Transform(lhs, rhs); - return lhs; -} - -inline Vector2 operator / (const Vector2& lhs, const float& rhs) -{ - return Vector2Scale(lhs, 1.0f / rhs); -} - -inline const Vector2& operator /= (Vector2& lhs, const float& rhs) -{ - lhs = Vector2Scale(lhs, rhs); - return lhs; -} - -inline Vector2 operator / (const Vector2& lhs, const Vector2& rhs) -{ - return Vector2Divide(lhs, rhs); -} - -inline const Vector2& operator /= (Vector2& lhs, const Vector2& rhs) -{ - lhs = Vector2Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector2& lhs, const Vector2& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y); -} - -inline bool operator != (const Vector2& lhs, const Vector2& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y); -} - -// Vector3 operators -static constexpr Vector3 Vector3Zeros = { 0, 0, 0 }; -static constexpr Vector3 Vector3Ones = { 1, 1, 1 }; -static constexpr Vector3 Vector3UnitX = { 1, 0, 0 }; -static constexpr Vector3 Vector3UnitY = { 0, 1, 0 }; -static constexpr Vector3 Vector3UnitZ = { 0, 0, 1 }; - -inline Vector3 operator + (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Add(lhs, rhs); -} - -inline const Vector3& operator += (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Add(lhs, rhs); - return lhs; -} - -inline Vector3 operator - (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Subtract(lhs, rhs); -} - -inline const Vector3& operator -= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Subtract(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const float& rhs) -{ - return Vector3Scale(lhs, rhs); -} - -inline const Vector3& operator *= (Vector3& lhs, const float& rhs) -{ - lhs = Vector3Scale(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Multiply(lhs, rhs); -} - -inline const Vector3& operator *= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Multiply(lhs, rhs); - return lhs; -} - -inline Vector3 operator * (const Vector3& lhs, const Matrix& rhs) -{ - return Vector3Transform(lhs, rhs); -} - -inline const Vector3& operator -= (Vector3& lhs, const Matrix& rhs) -{ - lhs = Vector3Transform(lhs, rhs); - return lhs; -} - -inline Vector3 operator / (const Vector3& lhs, const float& rhs) -{ - return Vector3Scale(lhs, 1.0f / rhs); -} - -inline const Vector3& operator /= (Vector3& lhs, const float& rhs) -{ - lhs = Vector3Scale(lhs, rhs); - return lhs; -} - -inline Vector3 operator / (const Vector3& lhs, const Vector3& rhs) -{ - return Vector3Divide(lhs, rhs); -} - -inline const Vector3& operator /= (Vector3& lhs, const Vector3& rhs) -{ - lhs = Vector3Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector3& lhs, const Vector3& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y) && FloatEquals(lhs.z, rhs.z); -} - -inline bool operator != (const Vector3& lhs, const Vector3& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y) || !FloatEquals(lhs.z, rhs.z); -} - -// Vector4 operators -static constexpr Vector4 Vector4Zeros = { 0, 0, 0, 0 }; -static constexpr Vector4 Vector4Ones = { 1, 1, 1, 1 }; -static constexpr Vector4 Vector4UnitX = { 1, 0, 0, 0 }; -static constexpr Vector4 Vector4UnitY = { 0, 1, 0, 0 }; -static constexpr Vector4 Vector4UnitZ = { 0, 0, 1, 0 }; -static constexpr Vector4 Vector4UnitW = { 0, 0, 0, 1 }; - -inline Vector4 operator + (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Add(lhs, rhs); -} - -inline const Vector4& operator += (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Add(lhs, rhs); - return lhs; -} - -inline Vector4 operator - (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Subtract(lhs, rhs); -} - -inline const Vector4& operator -= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Subtract(lhs, rhs); - return lhs; -} - -inline Vector4 operator * (const Vector4& lhs, const float& rhs) -{ - return Vector4Scale(lhs, rhs); -} - -inline const Vector4& operator *= (Vector4& lhs, const float& rhs) -{ - lhs = Vector4Scale(lhs, rhs); - return lhs; -} - -inline Vector4 operator * (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Multiply(lhs, rhs); -} - -inline const Vector4& operator *= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Multiply(lhs, rhs); - return lhs; -} - -inline Vector4 operator / (const Vector4& lhs, const float& rhs) -{ - return Vector4Scale(lhs, 1.0f / rhs); -} - -inline const Vector4& operator /= (Vector4& lhs, const float& rhs) -{ - lhs = Vector4Scale(lhs, rhs); - return lhs; -} - -inline Vector4 operator / (const Vector4& lhs, const Vector4& rhs) -{ - return Vector4Divide(lhs, rhs); -} - -inline const Vector4& operator /= (Vector4& lhs, const Vector4& rhs) -{ - lhs = Vector4Divide(lhs, rhs); - return lhs; -} - -inline bool operator == (const Vector4& lhs, const Vector4& rhs) -{ - return FloatEquals(lhs.x, rhs.x) && FloatEquals(lhs.y, rhs.y) && FloatEquals(lhs.z, rhs.z) && FloatEquals(lhs.w, rhs.w); -} - -inline bool operator != (const Vector4& lhs, const Vector4& rhs) -{ - return !FloatEquals(lhs.x, rhs.x) || !FloatEquals(lhs.y, rhs.y) || !FloatEquals(lhs.z, rhs.z) || !FloatEquals(lhs.w, rhs.w); -} - -// Quaternion operators -static constexpr Quaternion QuaternionZeros = { 0, 0, 0, 0 }; -static constexpr Quaternion QuaternionOnes = { 1, 1, 1, 1 }; -static constexpr Quaternion QuaternionUnitX = { 0, 0, 0, 1 }; - -inline Quaternion operator + (const Quaternion& lhs, const float& rhs) -{ - return QuaternionAddValue(lhs, rhs); -} - -inline const Quaternion& operator += (Quaternion& lhs, const float& rhs) -{ - lhs = QuaternionAddValue(lhs, rhs); - return lhs; -} - -inline Quaternion operator - (const Quaternion& lhs, const float& rhs) -{ - return QuaternionSubtractValue(lhs, rhs); -} - -inline const Quaternion& operator -= (Quaternion& lhs, const float& rhs) -{ - lhs = QuaternionSubtractValue(lhs, rhs); - return lhs; -} - -inline Quaternion operator * (const Quaternion& lhs, const Matrix& rhs) -{ - return QuaternionTransform(lhs, rhs); -} - -inline const Quaternion& operator *= (Quaternion& lhs, const Matrix& rhs) -{ - lhs = QuaternionTransform(lhs, rhs); - return lhs; -} - -// Matrix operators -inline Matrix operator + (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixAdd(lhs, rhs); -} - -inline const Matrix& operator += (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixAdd(lhs, rhs); - return lhs; -} - -inline Matrix operator - (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixSubtract(lhs, rhs); -} - -inline const Matrix& operator -= (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixSubtract(lhs, rhs); - return lhs; -} - -inline Matrix operator * (const Matrix& lhs, const Matrix& rhs) -{ - return MatrixMultiply(lhs, rhs); -} - -inline const Matrix& operator *= (Matrix& lhs, const Matrix& rhs) -{ - lhs = MatrixMultiply(lhs, rhs); - return lhs; -} -//------------------------------------------------------------------------------- -#endif // C++ operators - -#endif // RAYMATH_H diff --git a/examples/raylib/raylib-5.5_linux_amd64/include/rlgl.h b/examples/raylib/raylib-5.5_linux_amd64/include/rlgl.h deleted file mode 100644 index 756656e..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/include/rlgl.h +++ /dev/null @@ -1,5262 +0,0 @@ -/********************************************************************************************** -* -* rlgl v5.0 - A multi-OpenGL abstraction layer with an immediate-mode style API -* -* DESCRIPTION: -* An abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, 4.3 Core, ES 2.0) -* that provides a pseudo-OpenGL 1.1 immediate-mode style API (rlVertex, rlTranslate, rlRotate...) -* -* ADDITIONAL NOTES: -* When choosing an OpenGL backend different than OpenGL 1.1, some internal buffer are -* initialized on rlglInit() to accumulate vertex data -* -* When an internal state change is required all the stored vertex data is renderer in batch, -* additionally, rlDrawRenderBatchActive() could be called to force flushing of the batch -* -* Some resources are also loaded for convenience, here the complete list: -* - Default batch (RLGL.defaultBatch): RenderBatch system to accumulate vertex data -* - Default texture (RLGL.defaultTextureId): 1x1 white pixel R8G8B8A8 -* - Default shader (RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs) -* -* Internal buffer (and resources) must be manually unloaded calling rlglClose() -* -* CONFIGURATION: -* #define GRAPHICS_API_OPENGL_11 -* #define GRAPHICS_API_OPENGL_21 -* #define GRAPHICS_API_OPENGL_33 -* #define GRAPHICS_API_OPENGL_43 -* #define GRAPHICS_API_OPENGL_ES2 -* #define GRAPHICS_API_OPENGL_ES3 -* Use selected OpenGL graphics backend, should be supported by platform -* Those preprocessor defines are only used on rlgl module, if OpenGL version is -* required by any other module, use rlGetVersion() to check it -* -* #define RLGL_IMPLEMENTATION -* Generates the implementation of the library into the included file -* If not defined, the library is in header only mode and can be included in other headers -* or source files without problems. But only ONE file should hold the implementation -* -* #define RLGL_RENDER_TEXTURES_HINT -* Enable framebuffer objects (fbo) support (enabled by default) -* Some GPUs could not support them despite the OpenGL version -* -* #define RLGL_SHOW_GL_DETAILS_INFO -* Show OpenGL extensions and capabilities detailed logs on init -* -* #define RLGL_ENABLE_OPENGL_DEBUG_CONTEXT -* Enable debug context (only available on OpenGL 4.3) -* -* rlgl capabilities could be customized just defining some internal -* values before library inclusion (default values listed): -* -* #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 // Default internal render batch elements limits -* #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -* #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -* #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -* -* #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack -* #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -* #define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance -* #define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance -* -* When loading a shader, the following vertex attributes and uniform -* location names are tried to be set automatically: -* -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS "vertexBoneIds" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS -* #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS "vertexBoneWeights" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView))) -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -* #define RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES "boneMatrices" // bone matrices -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -* #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -* -* DEPENDENCIES: -* - OpenGL libraries (depending on platform and OpenGL version selected) -* - GLAD OpenGL extensions loading library (only for OpenGL 3.3 Core, 4.3 Core) -* -* -* LICENSE: zlib/libpng -* -* Copyright (c) 2014-2024 Ramon Santamaria (@raysan5) -* -* This software is provided "as-is", without any express or implied warranty. In no event -* will the authors be held liable for any damages arising from the use of this software. -* -* Permission is granted to anyone to use this software for any purpose, including commercial -* applications, and to alter it and redistribute it freely, subject to the following restrictions: -* -* 1. The origin of this software must not be misrepresented; you must not claim that you -* wrote the original software. If you use this software in a product, an acknowledgment -* in the product documentation would be appreciated but is not required. -* -* 2. Altered source versions must be plainly marked as such, and must not be misrepresented -* as being the original software. -* -* 3. This notice may not be removed or altered from any source distribution. -* -**********************************************************************************************/ - -#ifndef RLGL_H -#define RLGL_H - -#define RLGL_VERSION "5.0" - -// Function specifiers in case library is build/used as a shared library -// NOTE: Microsoft specifiers to tell compiler that symbols are imported/exported from a .dll -// NOTE: visibility(default) attribute makes symbols "visible" when compiled with -fvisibility=hidden -#if defined(_WIN32) && defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __declspec(dllexport) // We are building the library as a Win32 shared library (.dll) -#elif defined(BUILD_LIBTYPE_SHARED) - #define RLAPI __attribute__((visibility("default"))) // We are building the library as a Unix shared library (.so/.dylib) -#elif defined(_WIN32) && defined(USE_LIBTYPE_SHARED) - #define RLAPI __declspec(dllimport) // We are using the library as a Win32 shared library (.dll) -#endif - -// Function specifiers definition -#ifndef RLAPI - #define RLAPI // Functions defined as 'extern' by default (implicit specifiers) -#endif - -// Support TRACELOG macros -#ifndef TRACELOG - #define TRACELOG(level, ...) (void)0 - #define TRACELOGD(...) (void)0 -#endif - -// Allow custom memory allocators -#ifndef RL_MALLOC - #define RL_MALLOC(sz) malloc(sz) -#endif -#ifndef RL_CALLOC - #define RL_CALLOC(n,sz) calloc(n,sz) -#endif -#ifndef RL_REALLOC - #define RL_REALLOC(n,sz) realloc(n,sz) -#endif -#ifndef RL_FREE - #define RL_FREE(p) free(p) -#endif - -// Security check in case no GRAPHICS_API_OPENGL_* defined -#if !defined(GRAPHICS_API_OPENGL_11) && \ - !defined(GRAPHICS_API_OPENGL_21) && \ - !defined(GRAPHICS_API_OPENGL_33) && \ - !defined(GRAPHICS_API_OPENGL_43) && \ - !defined(GRAPHICS_API_OPENGL_ES2) && \ - !defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_33 -#endif - -// Security check in case multiple GRAPHICS_API_OPENGL_* defined -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_21) - #undef GRAPHICS_API_OPENGL_21 - #endif - #if defined(GRAPHICS_API_OPENGL_33) - #undef GRAPHICS_API_OPENGL_33 - #endif - #if defined(GRAPHICS_API_OPENGL_43) - #undef GRAPHICS_API_OPENGL_43 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - #undef GRAPHICS_API_OPENGL_ES2 - #endif -#endif - -// OpenGL 2.1 uses most of OpenGL 3.3 Core functionality -// WARNING: Specific parts are checked with #if defines -#if defined(GRAPHICS_API_OPENGL_21) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL 4.3 uses OpenGL 3.3 Core functionality -#if defined(GRAPHICS_API_OPENGL_43) - #define GRAPHICS_API_OPENGL_33 -#endif - -// OpenGL ES 3.0 uses OpenGL ES 2.0 functionality (and more) -#if defined(GRAPHICS_API_OPENGL_ES3) - #define GRAPHICS_API_OPENGL_ES2 -#endif - -// Support framebuffer objects by default -// NOTE: Some driver implementation do not support it, despite they should -#define RLGL_RENDER_TEXTURES_HINT - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- - -// Default internal render batch elements limits -#ifndef RL_DEFAULT_BATCH_BUFFER_ELEMENTS - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // This is the maximum amount of elements (quads) per batch - // NOTE: Be careful with text, every letter maps to a quad - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - // We reduce memory sizes for embedded systems (RPI and HTML5) - // NOTE: On HTML5 (emscripten) this is allocated on heap, - // by default it's only 16MB!...just take care... - #define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 2048 - #endif -#endif -#ifndef RL_DEFAULT_BATCH_BUFFERS - #define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering) -#endif -#ifndef RL_DEFAULT_BATCH_DRAWCALLS - #define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture) -#endif -#ifndef RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS - #define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture()) -#endif - -// Internal Matrix stack -#ifndef RL_MAX_MATRIX_STACK_SIZE - #define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of Matrix stack -#endif - -// Shader limits -#ifndef RL_MAX_SHADER_LOCATIONS - #define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported -#endif - -// Projection matrix culling -#ifndef RL_CULL_DISTANCE_NEAR - #define RL_CULL_DISTANCE_NEAR 0.01 // Default near cull distance -#endif -#ifndef RL_CULL_DISTANCE_FAR - #define RL_CULL_DISTANCE_FAR 1000.0 // Default far cull distance -#endif - -// Texture parameters (equivalent to OpenGL defines) -#define RL_TEXTURE_WRAP_S 0x2802 // GL_TEXTURE_WRAP_S -#define RL_TEXTURE_WRAP_T 0x2803 // GL_TEXTURE_WRAP_T -#define RL_TEXTURE_MAG_FILTER 0x2800 // GL_TEXTURE_MAG_FILTER -#define RL_TEXTURE_MIN_FILTER 0x2801 // GL_TEXTURE_MIN_FILTER - -#define RL_TEXTURE_FILTER_NEAREST 0x2600 // GL_NEAREST -#define RL_TEXTURE_FILTER_LINEAR 0x2601 // GL_LINEAR -#define RL_TEXTURE_FILTER_MIP_NEAREST 0x2700 // GL_NEAREST_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_NEAREST_MIP_LINEAR 0x2702 // GL_NEAREST_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_LINEAR_MIP_NEAREST 0x2701 // GL_LINEAR_MIPMAP_NEAREST -#define RL_TEXTURE_FILTER_MIP_LINEAR 0x2703 // GL_LINEAR_MIPMAP_LINEAR -#define RL_TEXTURE_FILTER_ANISOTROPIC 0x3000 // Anisotropic filter (custom identifier) -#define RL_TEXTURE_MIPMAP_BIAS_RATIO 0x4000 // Texture mipmap bias, percentage ratio (custom identifier) - -#define RL_TEXTURE_WRAP_REPEAT 0x2901 // GL_REPEAT -#define RL_TEXTURE_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE -#define RL_TEXTURE_WRAP_MIRROR_REPEAT 0x8370 // GL_MIRRORED_REPEAT -#define RL_TEXTURE_WRAP_MIRROR_CLAMP 0x8742 // GL_MIRROR_CLAMP_EXT - -// Matrix modes (equivalent to OpenGL) -#define RL_MODELVIEW 0x1700 // GL_MODELVIEW -#define RL_PROJECTION 0x1701 // GL_PROJECTION -#define RL_TEXTURE 0x1702 // GL_TEXTURE - -// Primitive assembly draw modes -#define RL_LINES 0x0001 // GL_LINES -#define RL_TRIANGLES 0x0004 // GL_TRIANGLES -#define RL_QUADS 0x0007 // GL_QUADS - -// GL equivalent data types -#define RL_UNSIGNED_BYTE 0x1401 // GL_UNSIGNED_BYTE -#define RL_FLOAT 0x1406 // GL_FLOAT - -// GL buffer usage hint -#define RL_STREAM_DRAW 0x88E0 // GL_STREAM_DRAW -#define RL_STREAM_READ 0x88E1 // GL_STREAM_READ -#define RL_STREAM_COPY 0x88E2 // GL_STREAM_COPY -#define RL_STATIC_DRAW 0x88E4 // GL_STATIC_DRAW -#define RL_STATIC_READ 0x88E5 // GL_STATIC_READ -#define RL_STATIC_COPY 0x88E6 // GL_STATIC_COPY -#define RL_DYNAMIC_DRAW 0x88E8 // GL_DYNAMIC_DRAW -#define RL_DYNAMIC_READ 0x88E9 // GL_DYNAMIC_READ -#define RL_DYNAMIC_COPY 0x88EA // GL_DYNAMIC_COPY - -// GL Shader type -#define RL_FRAGMENT_SHADER 0x8B30 // GL_FRAGMENT_SHADER -#define RL_VERTEX_SHADER 0x8B31 // GL_VERTEX_SHADER -#define RL_COMPUTE_SHADER 0x91B9 // GL_COMPUTE_SHADER - -// GL blending factors -#define RL_ZERO 0 // GL_ZERO -#define RL_ONE 1 // GL_ONE -#define RL_SRC_COLOR 0x0300 // GL_SRC_COLOR -#define RL_ONE_MINUS_SRC_COLOR 0x0301 // GL_ONE_MINUS_SRC_COLOR -#define RL_SRC_ALPHA 0x0302 // GL_SRC_ALPHA -#define RL_ONE_MINUS_SRC_ALPHA 0x0303 // GL_ONE_MINUS_SRC_ALPHA -#define RL_DST_ALPHA 0x0304 // GL_DST_ALPHA -#define RL_ONE_MINUS_DST_ALPHA 0x0305 // GL_ONE_MINUS_DST_ALPHA -#define RL_DST_COLOR 0x0306 // GL_DST_COLOR -#define RL_ONE_MINUS_DST_COLOR 0x0307 // GL_ONE_MINUS_DST_COLOR -#define RL_SRC_ALPHA_SATURATE 0x0308 // GL_SRC_ALPHA_SATURATE -#define RL_CONSTANT_COLOR 0x8001 // GL_CONSTANT_COLOR -#define RL_ONE_MINUS_CONSTANT_COLOR 0x8002 // GL_ONE_MINUS_CONSTANT_COLOR -#define RL_CONSTANT_ALPHA 0x8003 // GL_CONSTANT_ALPHA -#define RL_ONE_MINUS_CONSTANT_ALPHA 0x8004 // GL_ONE_MINUS_CONSTANT_ALPHA - -// GL blending functions/equations -#define RL_FUNC_ADD 0x8006 // GL_FUNC_ADD -#define RL_MIN 0x8007 // GL_MIN -#define RL_MAX 0x8008 // GL_MAX -#define RL_FUNC_SUBTRACT 0x800A // GL_FUNC_SUBTRACT -#define RL_FUNC_REVERSE_SUBTRACT 0x800B // GL_FUNC_REVERSE_SUBTRACT -#define RL_BLEND_EQUATION 0x8009 // GL_BLEND_EQUATION -#define RL_BLEND_EQUATION_RGB 0x8009 // GL_BLEND_EQUATION_RGB // (Same as BLEND_EQUATION) -#define RL_BLEND_EQUATION_ALPHA 0x883D // GL_BLEND_EQUATION_ALPHA -#define RL_BLEND_DST_RGB 0x80C8 // GL_BLEND_DST_RGB -#define RL_BLEND_SRC_RGB 0x80C9 // GL_BLEND_SRC_RGB -#define RL_BLEND_DST_ALPHA 0x80CA // GL_BLEND_DST_ALPHA -#define RL_BLEND_SRC_ALPHA 0x80CB // GL_BLEND_SRC_ALPHA -#define RL_BLEND_COLOR 0x8005 // GL_BLEND_COLOR - -#define RL_READ_FRAMEBUFFER 0x8CA8 // GL_READ_FRAMEBUFFER -#define RL_DRAW_FRAMEBUFFER 0x8CA9 // GL_DRAW_FRAMEBUFFER - -// Default shader vertex attribute locations -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION 0 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD 1 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL 2 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR 3 -#endif - #ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT -#define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT 4 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2 5 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_INDICES 6 -#endif -#ifdef RL_SUPPORT_MESH_GPU_SKINNING -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS 7 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS - #define RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS 8 -#endif -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if (defined(__STDC__) && __STDC_VERSION__ >= 199901L) || (defined(_MSC_VER) && _MSC_VER >= 1800) - #include -#elif !defined(__cplusplus) && !defined(bool) && !defined(RL_BOOL_TYPE) - // Boolean type -typedef enum bool { false = 0, true = !false } bool; -#endif - -#if !defined(RL_MATRIX_TYPE) -// Matrix, 4x4 components, column major, OpenGL style, right handed -typedef struct Matrix { - float m0, m4, m8, m12; // Matrix first row (4 components) - float m1, m5, m9, m13; // Matrix second row (4 components) - float m2, m6, m10, m14; // Matrix third row (4 components) - float m3, m7, m11, m15; // Matrix fourth row (4 components) -} Matrix; -#define RL_MATRIX_TYPE -#endif - -// Dynamic vertex buffers (position + texcoords + colors + indices arrays) -typedef struct rlVertexBuffer { - int elementCount; // Number of elements in the buffer (QUADS) - - float *vertices; // Vertex position (XYZ - 3 components per vertex) (shader-location = 0) - float *texcoords; // Vertex texture coordinates (UV - 2 components per vertex) (shader-location = 1) - float *normals; // Vertex normal (XYZ - 3 components per vertex) (shader-location = 2) - unsigned char *colors; // Vertex colors (RGBA - 4 components per vertex) (shader-location = 3) -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - unsigned int *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - unsigned short *indices; // Vertex indices (in case vertex data comes indexed) (6 indices per quad) -#endif - unsigned int vaoId; // OpenGL Vertex Array Object id - unsigned int vboId[5]; // OpenGL Vertex Buffer Objects id (5 types of vertex data) -} rlVertexBuffer; - -// Draw call type -// NOTE: Only texture changes register a new draw, other state-change-related elements are not -// used at this moment (vaoId, shaderId, matrices), raylib just forces a batch draw call if any -// of those state-change happens (this is done in core module) -typedef struct rlDrawCall { - int mode; // Drawing mode: LINES, TRIANGLES, QUADS - int vertexCount; // Number of vertex of the draw - int vertexAlignment; // Number of vertex required for index alignment (LINES, TRIANGLES) - //unsigned int vaoId; // Vertex array id to be used on the draw -> Using RLGL.currentBatch->vertexBuffer.vaoId - //unsigned int shaderId; // Shader id to be used on the draw -> Using RLGL.currentShaderId - unsigned int textureId; // Texture id to be used on the draw -> Use to create new draw call if changes - - //Matrix projection; // Projection matrix for this draw -> Using RLGL.projection by default - //Matrix modelview; // Modelview matrix for this draw -> Using RLGL.modelview by default -} rlDrawCall; - -// rlRenderBatch type -typedef struct rlRenderBatch { - int bufferCount; // Number of vertex buffers (multi-buffering support) - int currentBuffer; // Current buffer tracking in case of multi-buffering - rlVertexBuffer *vertexBuffer; // Dynamic buffer(s) for vertex data - - rlDrawCall *draws; // Draw calls array, depends on textureId - int drawCounter; // Draw calls counter - float currentDepth; // Current depth value for next draw -} rlRenderBatch; - -// OpenGL version -typedef enum { - RL_OPENGL_11 = 1, // OpenGL 1.1 - RL_OPENGL_21, // OpenGL 2.1 (GLSL 120) - RL_OPENGL_33, // OpenGL 3.3 (GLSL 330) - RL_OPENGL_43, // OpenGL 4.3 (using GLSL 330) - RL_OPENGL_ES_20, // OpenGL ES 2.0 (GLSL 100) - RL_OPENGL_ES_30 // OpenGL ES 3.0 (GLSL 300 es) -} rlGlVersion; - -// Trace log level -// NOTE: Organized by priority level -typedef enum { - RL_LOG_ALL = 0, // Display all logs - RL_LOG_TRACE, // Trace logging, intended for internal use only - RL_LOG_DEBUG, // Debug logging, used for internal debugging, it should be disabled on release builds - RL_LOG_INFO, // Info logging, used for program execution info - RL_LOG_WARNING, // Warning logging, used on recoverable failures - RL_LOG_ERROR, // Error logging, used on unrecoverable failures - RL_LOG_FATAL, // Fatal logging, used to abort program: exit(EXIT_FAILURE) - RL_LOG_NONE // Disable logging -} rlTraceLogLevel; - -// Texture pixel formats -// NOTE: Support depends on OpenGL version -typedef enum { - RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE = 1, // 8 bit per pixel (no alpha) - RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA, // 8*2 bpp (2 channels) - RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5, // 16 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8, // 24 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1, // 16 bpp (1 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4, // 16 bpp (4 bit alpha) - RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, // 32 bpp - RL_PIXELFORMAT_UNCOMPRESSED_R32, // 32 bpp (1 channel - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32, // 32*3 bpp (3 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32, // 32*4 bpp (4 channels - float) - RL_PIXELFORMAT_UNCOMPRESSED_R16, // 16 bpp (1 channel - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16, // 16*3 bpp (3 channels - half float) - RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16, // 16*4 bpp (4 channels - half float) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGB, // 4 bpp (no alpha) - RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA, // 4 bpp (1 bit alpha) - RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ETC1_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGB, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA, // 4 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA, // 8 bpp - RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA // 2 bpp -} rlPixelFormat; - -// Texture parameters: filter mode -// NOTE 1: Filtering considers mipmaps if available in the texture -// NOTE 2: Filter is accordingly set for minification and magnification -typedef enum { - RL_TEXTURE_FILTER_POINT = 0, // No filter, just pixel approximation - RL_TEXTURE_FILTER_BILINEAR, // Linear filtering - RL_TEXTURE_FILTER_TRILINEAR, // Trilinear filtering (linear with mipmaps) - RL_TEXTURE_FILTER_ANISOTROPIC_4X, // Anisotropic filtering 4x - RL_TEXTURE_FILTER_ANISOTROPIC_8X, // Anisotropic filtering 8x - RL_TEXTURE_FILTER_ANISOTROPIC_16X, // Anisotropic filtering 16x -} rlTextureFilter; - -// Color blending modes (pre-defined) -typedef enum { - RL_BLEND_ALPHA = 0, // Blend textures considering alpha (default) - RL_BLEND_ADDITIVE, // Blend textures adding colors - RL_BLEND_MULTIPLIED, // Blend textures multiplying colors - RL_BLEND_ADD_COLORS, // Blend textures adding colors (alternative) - RL_BLEND_SUBTRACT_COLORS, // Blend textures subtracting colors (alternative) - RL_BLEND_ALPHA_PREMULTIPLY, // Blend premultiplied textures considering alpha - RL_BLEND_CUSTOM, // Blend textures using custom src/dst factors (use rlSetBlendFactors()) - RL_BLEND_CUSTOM_SEPARATE // Blend textures using custom src/dst factors (use rlSetBlendFactorsSeparate()) -} rlBlendMode; - -// Shader location point type -typedef enum { - RL_SHADER_LOC_VERTEX_POSITION = 0, // Shader location: vertex attribute: position - RL_SHADER_LOC_VERTEX_TEXCOORD01, // Shader location: vertex attribute: texcoord01 - RL_SHADER_LOC_VERTEX_TEXCOORD02, // Shader location: vertex attribute: texcoord02 - RL_SHADER_LOC_VERTEX_NORMAL, // Shader location: vertex attribute: normal - RL_SHADER_LOC_VERTEX_TANGENT, // Shader location: vertex attribute: tangent - RL_SHADER_LOC_VERTEX_COLOR, // Shader location: vertex attribute: color - RL_SHADER_LOC_MATRIX_MVP, // Shader location: matrix uniform: model-view-projection - RL_SHADER_LOC_MATRIX_VIEW, // Shader location: matrix uniform: view (camera transform) - RL_SHADER_LOC_MATRIX_PROJECTION, // Shader location: matrix uniform: projection - RL_SHADER_LOC_MATRIX_MODEL, // Shader location: matrix uniform: model (transform) - RL_SHADER_LOC_MATRIX_NORMAL, // Shader location: matrix uniform: normal - RL_SHADER_LOC_VECTOR_VIEW, // Shader location: vector uniform: view - RL_SHADER_LOC_COLOR_DIFFUSE, // Shader location: vector uniform: diffuse color - RL_SHADER_LOC_COLOR_SPECULAR, // Shader location: vector uniform: specular color - RL_SHADER_LOC_COLOR_AMBIENT, // Shader location: vector uniform: ambient color - RL_SHADER_LOC_MAP_ALBEDO, // Shader location: sampler2d texture: albedo (same as: RL_SHADER_LOC_MAP_DIFFUSE) - RL_SHADER_LOC_MAP_METALNESS, // Shader location: sampler2d texture: metalness (same as: RL_SHADER_LOC_MAP_SPECULAR) - RL_SHADER_LOC_MAP_NORMAL, // Shader location: sampler2d texture: normal - RL_SHADER_LOC_MAP_ROUGHNESS, // Shader location: sampler2d texture: roughness - RL_SHADER_LOC_MAP_OCCLUSION, // Shader location: sampler2d texture: occlusion - RL_SHADER_LOC_MAP_EMISSION, // Shader location: sampler2d texture: emission - RL_SHADER_LOC_MAP_HEIGHT, // Shader location: sampler2d texture: height - RL_SHADER_LOC_MAP_CUBEMAP, // Shader location: samplerCube texture: cubemap - RL_SHADER_LOC_MAP_IRRADIANCE, // Shader location: samplerCube texture: irradiance - RL_SHADER_LOC_MAP_PREFILTER, // Shader location: samplerCube texture: prefilter - RL_SHADER_LOC_MAP_BRDF // Shader location: sampler2d texture: brdf -} rlShaderLocationIndex; - -#define RL_SHADER_LOC_MAP_DIFFUSE RL_SHADER_LOC_MAP_ALBEDO -#define RL_SHADER_LOC_MAP_SPECULAR RL_SHADER_LOC_MAP_METALNESS - -// Shader uniform data type -typedef enum { - RL_SHADER_UNIFORM_FLOAT = 0, // Shader uniform type: float - RL_SHADER_UNIFORM_VEC2, // Shader uniform type: vec2 (2 float) - RL_SHADER_UNIFORM_VEC3, // Shader uniform type: vec3 (3 float) - RL_SHADER_UNIFORM_VEC4, // Shader uniform type: vec4 (4 float) - RL_SHADER_UNIFORM_INT, // Shader uniform type: int - RL_SHADER_UNIFORM_IVEC2, // Shader uniform type: ivec2 (2 int) - RL_SHADER_UNIFORM_IVEC3, // Shader uniform type: ivec3 (3 int) - RL_SHADER_UNIFORM_IVEC4, // Shader uniform type: ivec4 (4 int) - RL_SHADER_UNIFORM_UINT, // Shader uniform type: unsigned int - RL_SHADER_UNIFORM_UIVEC2, // Shader uniform type: uivec2 (2 unsigned int) - RL_SHADER_UNIFORM_UIVEC3, // Shader uniform type: uivec3 (3 unsigned int) - RL_SHADER_UNIFORM_UIVEC4, // Shader uniform type: uivec4 (4 unsigned int) - RL_SHADER_UNIFORM_SAMPLER2D // Shader uniform type: sampler2d -} rlShaderUniformDataType; - -// Shader attribute data types -typedef enum { - RL_SHADER_ATTRIB_FLOAT = 0, // Shader attribute type: float - RL_SHADER_ATTRIB_VEC2, // Shader attribute type: vec2 (2 float) - RL_SHADER_ATTRIB_VEC3, // Shader attribute type: vec3 (3 float) - RL_SHADER_ATTRIB_VEC4 // Shader attribute type: vec4 (4 float) -} rlShaderAttributeDataType; - -// Framebuffer attachment type -// NOTE: By default up to 8 color channels defined, but it can be more -typedef enum { - RL_ATTACHMENT_COLOR_CHANNEL0 = 0, // Framebuffer attachment type: color 0 - RL_ATTACHMENT_COLOR_CHANNEL1 = 1, // Framebuffer attachment type: color 1 - RL_ATTACHMENT_COLOR_CHANNEL2 = 2, // Framebuffer attachment type: color 2 - RL_ATTACHMENT_COLOR_CHANNEL3 = 3, // Framebuffer attachment type: color 3 - RL_ATTACHMENT_COLOR_CHANNEL4 = 4, // Framebuffer attachment type: color 4 - RL_ATTACHMENT_COLOR_CHANNEL5 = 5, // Framebuffer attachment type: color 5 - RL_ATTACHMENT_COLOR_CHANNEL6 = 6, // Framebuffer attachment type: color 6 - RL_ATTACHMENT_COLOR_CHANNEL7 = 7, // Framebuffer attachment type: color 7 - RL_ATTACHMENT_DEPTH = 100, // Framebuffer attachment type: depth - RL_ATTACHMENT_STENCIL = 200, // Framebuffer attachment type: stencil -} rlFramebufferAttachType; - -// Framebuffer texture attachment type -typedef enum { - RL_ATTACHMENT_CUBEMAP_POSITIVE_X = 0, // Framebuffer texture attachment type: cubemap, +X side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_X = 1, // Framebuffer texture attachment type: cubemap, -X side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Y = 2, // Framebuffer texture attachment type: cubemap, +Y side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Y = 3, // Framebuffer texture attachment type: cubemap, -Y side - RL_ATTACHMENT_CUBEMAP_POSITIVE_Z = 4, // Framebuffer texture attachment type: cubemap, +Z side - RL_ATTACHMENT_CUBEMAP_NEGATIVE_Z = 5, // Framebuffer texture attachment type: cubemap, -Z side - RL_ATTACHMENT_TEXTURE2D = 100, // Framebuffer texture attachment type: texture2d - RL_ATTACHMENT_RENDERBUFFER = 200, // Framebuffer texture attachment type: renderbuffer -} rlFramebufferAttachTextureType; - -// Face culling mode -typedef enum { - RL_CULL_FACE_FRONT = 0, - RL_CULL_FACE_BACK -} rlCullMode; - -//------------------------------------------------------------------------------------ -// Functions Declaration - Matrix operations -//------------------------------------------------------------------------------------ - -#if defined(__cplusplus) -extern "C" { // Prevents name mangling of functions -#endif - -RLAPI void rlMatrixMode(int mode); // Choose the current matrix to be transformed -RLAPI void rlPushMatrix(void); // Push the current matrix to stack -RLAPI void rlPopMatrix(void); // Pop latest inserted matrix from stack -RLAPI void rlLoadIdentity(void); // Reset current matrix to identity matrix -RLAPI void rlTranslatef(float x, float y, float z); // Multiply the current matrix by a translation matrix -RLAPI void rlRotatef(float angle, float x, float y, float z); // Multiply the current matrix by a rotation matrix -RLAPI void rlScalef(float x, float y, float z); // Multiply the current matrix by a scaling matrix -RLAPI void rlMultMatrixf(const float *matf); // Multiply the current matrix by another matrix -RLAPI void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar); -RLAPI void rlViewport(int x, int y, int width, int height); // Set the viewport area -RLAPI void rlSetClipPlanes(double nearPlane, double farPlane); // Set clip planes distances -RLAPI double rlGetCullDistanceNear(void); // Get cull plane distance near -RLAPI double rlGetCullDistanceFar(void); // Get cull plane distance far - -//------------------------------------------------------------------------------------ -// Functions Declaration - Vertex level operations -//------------------------------------------------------------------------------------ -RLAPI void rlBegin(int mode); // Initialize drawing mode (how to organize vertex) -RLAPI void rlEnd(void); // Finish vertex providing -RLAPI void rlVertex2i(int x, int y); // Define one vertex (position) - 2 int -RLAPI void rlVertex2f(float x, float y); // Define one vertex (position) - 2 float -RLAPI void rlVertex3f(float x, float y, float z); // Define one vertex (position) - 3 float -RLAPI void rlTexCoord2f(float x, float y); // Define one vertex (texture coordinate) - 2 float -RLAPI void rlNormal3f(float x, float y, float z); // Define one vertex (normal) - 3 float -RLAPI void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Define one vertex (color) - 4 byte -RLAPI void rlColor3f(float x, float y, float z); // Define one vertex (color) - 3 float -RLAPI void rlColor4f(float x, float y, float z, float w); // Define one vertex (color) - 4 float - -//------------------------------------------------------------------------------------ -// Functions Declaration - OpenGL style functions (common to 1.1, 3.3+, ES2) -// NOTE: This functions are used to completely abstract raylib code from OpenGL layer, -// some of them are direct wrappers over OpenGL calls, some others are custom -//------------------------------------------------------------------------------------ - -// Vertex buffers state -RLAPI bool rlEnableVertexArray(unsigned int vaoId); // Enable vertex array (VAO, if supported) -RLAPI void rlDisableVertexArray(void); // Disable vertex array (VAO, if supported) -RLAPI void rlEnableVertexBuffer(unsigned int id); // Enable vertex buffer (VBO) -RLAPI void rlDisableVertexBuffer(void); // Disable vertex buffer (VBO) -RLAPI void rlEnableVertexBufferElement(unsigned int id); // Enable vertex buffer element (VBO element) -RLAPI void rlDisableVertexBufferElement(void); // Disable vertex buffer element (VBO element) -RLAPI void rlEnableVertexAttribute(unsigned int index); // Enable vertex attribute index -RLAPI void rlDisableVertexAttribute(unsigned int index); // Disable vertex attribute index -#if defined(GRAPHICS_API_OPENGL_11) -RLAPI void rlEnableStatePointer(int vertexAttribType, void *buffer); // Enable attribute state pointer -RLAPI void rlDisableStatePointer(int vertexAttribType); // Disable attribute state pointer -#endif - -// Textures state -RLAPI void rlActiveTextureSlot(int slot); // Select and active a texture slot -RLAPI void rlEnableTexture(unsigned int id); // Enable texture -RLAPI void rlDisableTexture(void); // Disable texture -RLAPI void rlEnableTextureCubemap(unsigned int id); // Enable texture cubemap -RLAPI void rlDisableTextureCubemap(void); // Disable texture cubemap -RLAPI void rlTextureParameters(unsigned int id, int param, int value); // Set texture parameters (filter, wrap) -RLAPI void rlCubemapParameters(unsigned int id, int param, int value); // Set cubemap parameters (filter, wrap) - -// Shader state -RLAPI void rlEnableShader(unsigned int id); // Enable shader program -RLAPI void rlDisableShader(void); // Disable shader program - -// Framebuffer state -RLAPI void rlEnableFramebuffer(unsigned int id); // Enable render texture (fbo) -RLAPI void rlDisableFramebuffer(void); // Disable render texture (fbo), return to default framebuffer -RLAPI unsigned int rlGetActiveFramebuffer(void); // Get the currently active render texture (fbo), 0 for default framebuffer -RLAPI void rlActiveDrawBuffers(int count); // Activate multiple draw color buffers -RLAPI void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask); // Blit active framebuffer to main framebuffer -RLAPI void rlBindFramebuffer(unsigned int target, unsigned int framebuffer); // Bind framebuffer (FBO) - -// General render state -RLAPI void rlEnableColorBlend(void); // Enable color blending -RLAPI void rlDisableColorBlend(void); // Disable color blending -RLAPI void rlEnableDepthTest(void); // Enable depth test -RLAPI void rlDisableDepthTest(void); // Disable depth test -RLAPI void rlEnableDepthMask(void); // Enable depth write -RLAPI void rlDisableDepthMask(void); // Disable depth write -RLAPI void rlEnableBackfaceCulling(void); // Enable backface culling -RLAPI void rlDisableBackfaceCulling(void); // Disable backface culling -RLAPI void rlColorMask(bool r, bool g, bool b, bool a); // Color mask control -RLAPI void rlSetCullFace(int mode); // Set face culling mode -RLAPI void rlEnableScissorTest(void); // Enable scissor test -RLAPI void rlDisableScissorTest(void); // Disable scissor test -RLAPI void rlScissor(int x, int y, int width, int height); // Scissor test -RLAPI void rlEnableWireMode(void); // Enable wire mode -RLAPI void rlEnablePointMode(void); // Enable point mode -RLAPI void rlDisableWireMode(void); // Disable wire (and point) mode -RLAPI void rlSetLineWidth(float width); // Set the line drawing width -RLAPI float rlGetLineWidth(void); // Get the line drawing width -RLAPI void rlEnableSmoothLines(void); // Enable line aliasing -RLAPI void rlDisableSmoothLines(void); // Disable line aliasing -RLAPI void rlEnableStereoRender(void); // Enable stereo rendering -RLAPI void rlDisableStereoRender(void); // Disable stereo rendering -RLAPI bool rlIsStereoRenderEnabled(void); // Check if stereo render is enabled - -RLAPI void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a); // Clear color buffer with color -RLAPI void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) -RLAPI void rlCheckErrors(void); // Check and log OpenGL error codes -RLAPI void rlSetBlendMode(int mode); // Set blending mode -RLAPI void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation); // Set blending mode factor and equation (using OpenGL factors) -RLAPI void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha); // Set blending mode factors and equations separately (using OpenGL factors) - -//------------------------------------------------------------------------------------ -// Functions Declaration - rlgl functionality -//------------------------------------------------------------------------------------ -// rlgl initialization functions -RLAPI void rlglInit(int width, int height); // Initialize rlgl (buffers, shaders, textures, states) -RLAPI void rlglClose(void); // De-initialize rlgl (buffers, shaders, textures) -RLAPI void rlLoadExtensions(void *loader); // Load OpenGL extensions (loader function required) -RLAPI int rlGetVersion(void); // Get current OpenGL version -RLAPI void rlSetFramebufferWidth(int width); // Set current framebuffer width -RLAPI int rlGetFramebufferWidth(void); // Get default framebuffer width -RLAPI void rlSetFramebufferHeight(int height); // Set current framebuffer height -RLAPI int rlGetFramebufferHeight(void); // Get default framebuffer height - -RLAPI unsigned int rlGetTextureIdDefault(void); // Get default texture id -RLAPI unsigned int rlGetShaderIdDefault(void); // Get default shader id -RLAPI int *rlGetShaderLocsDefault(void); // Get default shader locations - -// Render batch management -// NOTE: rlgl provides a default render batch to behave like OpenGL 1.1 immediate mode -// but this render batch API is exposed in case of custom batches are required -RLAPI rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements); // Load a render batch system -RLAPI void rlUnloadRenderBatch(rlRenderBatch batch); // Unload render batch system -RLAPI void rlDrawRenderBatch(rlRenderBatch *batch); // Draw render batch data (Update->Draw->Reset) -RLAPI void rlSetRenderBatchActive(rlRenderBatch *batch); // Set the active render batch for rlgl (NULL for default internal) -RLAPI void rlDrawRenderBatchActive(void); // Update and draw internal render batch -RLAPI bool rlCheckRenderBatchLimit(int vCount); // Check internal buffer overflow for a given number of vertex - -RLAPI void rlSetTexture(unsigned int id); // Set current texture for render batch and check buffers limits - -//------------------------------------------------------------------------------------------------------------------------ - -// Vertex buffers management -RLAPI unsigned int rlLoadVertexArray(void); // Load vertex array (vao) if supported -RLAPI unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic); // Load a vertex buffer object -RLAPI unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic); // Load vertex buffer elements object -RLAPI void rlUpdateVertexBuffer(unsigned int bufferId, const void *data, int dataSize, int offset); // Update vertex buffer object data on GPU buffer -RLAPI void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset); // Update vertex buffer elements data on GPU buffer -RLAPI void rlUnloadVertexArray(unsigned int vaoId); // Unload vertex array (vao) -RLAPI void rlUnloadVertexBuffer(unsigned int vboId); // Unload vertex buffer object -RLAPI void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset); // Set vertex attribute data configuration -RLAPI void rlSetVertexAttributeDivisor(unsigned int index, int divisor); // Set vertex attribute data divisor -RLAPI void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count); // Set vertex attribute default value, when attribute to provided -RLAPI void rlDrawVertexArray(int offset, int count); // Draw vertex array (currently active vao) -RLAPI void rlDrawVertexArrayElements(int offset, int count, const void *buffer); // Draw vertex array elements -RLAPI void rlDrawVertexArrayInstanced(int offset, int count, int instances); // Draw vertex array (currently active vao) with instancing -RLAPI void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances); // Draw vertex array elements with instancing - -// Textures management -RLAPI unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount); // Load texture data -RLAPI unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer); // Load depth texture/renderbuffer (to be attached to fbo) -RLAPI unsigned int rlLoadTextureCubemap(const void *data, int size, int format, int mipmapCount); // Load texture cubemap data -RLAPI void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data); // Update texture with new data on GPU -RLAPI void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType); // Get OpenGL internal formats -RLAPI const char *rlGetPixelFormatName(unsigned int format); // Get name string for pixel format -RLAPI void rlUnloadTexture(unsigned int id); // Unload texture from GPU memory -RLAPI void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps); // Generate mipmap data for selected texture -RLAPI void *rlReadTexturePixels(unsigned int id, int width, int height, int format); // Read texture pixel data -RLAPI unsigned char *rlReadScreenPixels(int width, int height); // Read screen pixel data (color buffer) - -// Framebuffer management (fbo) -RLAPI unsigned int rlLoadFramebuffer(void); // Load an empty framebuffer -RLAPI void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel); // Attach texture/renderbuffer to a framebuffer -RLAPI bool rlFramebufferComplete(unsigned int id); // Verify framebuffer is complete -RLAPI void rlUnloadFramebuffer(unsigned int id); // Delete framebuffer from GPU - -// Shaders management -RLAPI unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode); // Load shader from code strings -RLAPI unsigned int rlCompileShader(const char *shaderCode, int type); // Compile custom shader and return shader id (type: RL_VERTEX_SHADER, RL_FRAGMENT_SHADER, RL_COMPUTE_SHADER) -RLAPI unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId); // Load custom shader program -RLAPI void rlUnloadShaderProgram(unsigned int id); // Unload shader program -RLAPI int rlGetLocationUniform(unsigned int shaderId, const char *uniformName); // Get shader location uniform -RLAPI int rlGetLocationAttrib(unsigned int shaderId, const char *attribName); // Get shader location attribute -RLAPI void rlSetUniform(int locIndex, const void *value, int uniformType, int count); // Set shader value uniform -RLAPI void rlSetUniformMatrix(int locIndex, Matrix mat); // Set shader value matrix -RLAPI void rlSetUniformMatrices(int locIndex, const Matrix *mat, int count); // Set shader value matrices -RLAPI void rlSetUniformSampler(int locIndex, unsigned int textureId); // Set shader value sampler -RLAPI void rlSetShader(unsigned int id, int *locs); // Set shader currently active (id and locations) - -// Compute shader management -RLAPI unsigned int rlLoadComputeShaderProgram(unsigned int shaderId); // Load compute shader program -RLAPI void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ); // Dispatch compute shader (equivalent to *draw* for graphics pipeline) - -// Shader buffer storage object management (ssbo) -RLAPI unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint); // Load shader storage buffer object (SSBO) -RLAPI void rlUnloadShaderBuffer(unsigned int ssboId); // Unload shader storage buffer object (SSBO) -RLAPI void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset); // Update SSBO buffer data -RLAPI void rlBindShaderBuffer(unsigned int id, unsigned int index); // Bind SSBO buffer -RLAPI void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset); // Read SSBO buffer data (GPU->CPU) -RLAPI void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count); // Copy SSBO data between buffers -RLAPI unsigned int rlGetShaderBufferSize(unsigned int id); // Get SSBO buffer size - -// Buffer management -RLAPI void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly); // Bind image texture - -// Matrix state management -RLAPI Matrix rlGetMatrixModelview(void); // Get internal modelview matrix -RLAPI Matrix rlGetMatrixProjection(void); // Get internal projection matrix -RLAPI Matrix rlGetMatrixTransform(void); // Get internal accumulated transform matrix -RLAPI Matrix rlGetMatrixProjectionStereo(int eye); // Get internal projection matrix for stereo render (selected eye) -RLAPI Matrix rlGetMatrixViewOffsetStereo(int eye); // Get internal view offset matrix for stereo render (selected eye) -RLAPI void rlSetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) -RLAPI void rlSetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) -RLAPI void rlSetMatrixProjectionStereo(Matrix right, Matrix left); // Set eyes projection matrices for stereo rendering -RLAPI void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left); // Set eyes view offsets matrices for stereo rendering - -// Quick and dirty cube/quad buffers load->draw->unload -RLAPI void rlLoadDrawCube(void); // Load and draw a cube -RLAPI void rlLoadDrawQuad(void); // Load and draw a quad - -#if defined(__cplusplus) -} -#endif - -#endif // RLGL_H - -/*********************************************************************************** -* -* RLGL IMPLEMENTATION -* -************************************************************************************/ - -#if defined(RLGL_IMPLEMENTATION) - -// Expose OpenGL functions from glad in raylib -#if defined(BUILD_LIBTYPE_SHARED) - #define GLAD_API_CALL_EXPORT - #define GLAD_API_CALL_EXPORT_BUILD -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #if defined(__APPLE__) - #include // OpenGL 1.1 library for OSX - #include // OpenGL extensions library - #else - // APIENTRY for OpenGL function pointer declarations is required - #if !defined(APIENTRY) - #if defined(_WIN32) - #define APIENTRY __stdcall - #else - #define APIENTRY - #endif - #endif - // WINGDIAPI definition. Some Windows OpenGL headers need it - #if !defined(WINGDIAPI) && defined(_WIN32) - #define WINGDIAPI __declspec(dllimport) - #endif - - #include // OpenGL 1.1 library - #endif -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - #define GLAD_MALLOC RL_MALLOC - #define GLAD_FREE RL_FREE - - #define GLAD_GL_IMPLEMENTATION - #include "external/glad.h" // GLAD extensions loading library, includes OpenGL headers -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - #include // OpenGL ES 3.0 library - #define GL_GLEXT_PROTOTYPES - #include // OpenGL ES 2.0 extensions library -#elif defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 can be enabled on Desktop platforms, - // in that case, functions are loaded from a custom glad for OpenGL ES 2.0 - #if defined(PLATFORM_DESKTOP_GLFW) || defined(PLATFORM_DESKTOP_SDL) - #define GLAD_GLES2_IMPLEMENTATION - #include "external/glad_gles2.h" - #else - #define GL_GLEXT_PROTOTYPES - //#include // EGL library -> not required, platform layer - #include // OpenGL ES 2.0 library - #include // OpenGL ES 2.0 extensions library - #endif - - // It seems OpenGL ES 2.0 instancing entry points are not defined on Raspberry Pi - // provided headers (despite being defined in official Khronos GLES2 headers) - #if defined(PLATFORM_DRM) - typedef void (GL_APIENTRYP PFNGLDRAWARRAYSINSTANCEDEXTPROC) (GLenum mode, GLint start, GLsizei count, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLDRAWELEMENTSINSTANCEDEXTPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLsizei primcount); - typedef void (GL_APIENTRYP PFNGLVERTEXATTRIBDIVISOREXTPROC) (GLuint index, GLuint divisor); - #endif -#endif - -#include // Required for: malloc(), free() -#include // Required for: strcmp(), strlen() [Used in rlglInit(), on extensions loading] -#include // Required for: sqrtf(), sinf(), cosf(), floor(), log() - -//---------------------------------------------------------------------------------- -// Defines and Macros -//---------------------------------------------------------------------------------- -#ifndef PI - #define PI 3.14159265358979323846f -#endif -#ifndef DEG2RAD - #define DEG2RAD (PI/180.0f) -#endif -#ifndef RAD2DEG - #define RAD2DEG (180.0f/PI) -#endif - -#ifndef GL_SHADING_LANGUAGE_VERSION - #define GL_SHADING_LANGUAGE_VERSION 0x8B8C -#endif - -#ifndef GL_COMPRESSED_RGB_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGB_S3TC_DXT1_EXT 0x83F0 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT1_EXT 0x83F1 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT3_EXT 0x83F2 -#endif -#ifndef GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - #define GL_COMPRESSED_RGBA_S3TC_DXT5_EXT 0x83F3 -#endif -#ifndef GL_ETC1_RGB8_OES - #define GL_ETC1_RGB8_OES 0x8D64 -#endif -#ifndef GL_COMPRESSED_RGB8_ETC2 - #define GL_COMPRESSED_RGB8_ETC2 0x9274 -#endif -#ifndef GL_COMPRESSED_RGBA8_ETC2_EAC - #define GL_COMPRESSED_RGBA8_ETC2_EAC 0x9278 -#endif -#ifndef GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG 0x8C00 -#endif -#ifndef GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG - #define GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG 0x8C02 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_4x4_KHR - #define GL_COMPRESSED_RGBA_ASTC_4x4_KHR 0x93b0 -#endif -#ifndef GL_COMPRESSED_RGBA_ASTC_8x8_KHR - #define GL_COMPRESSED_RGBA_ASTC_8x8_KHR 0x93b7 -#endif - -#ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF -#endif -#ifndef GL_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_TEXTURE_MAX_ANISOTROPY_EXT 0x84FE -#endif - -#ifndef GL_PROGRAM_POINT_SIZE - #define GL_PROGRAM_POINT_SIZE 0x8642 -#endif - -#ifndef GL_LINE_WIDTH - #define GL_LINE_WIDTH 0x0B21 -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - #define GL_LUMINANCE 0x1909 - #define GL_LUMINANCE_ALPHA 0x190A -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #if !defined(GRAPHICS_API_OPENGL_ES3) - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER - #endif -#endif - -// Default shader vertex attribute names to set location points -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION - #define RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION "vertexPosition" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD "vertexTexCoord" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL - #define RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL "vertexNormal" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR - #define RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR "vertexColor" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT "vertexTangent" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 - #define RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 "vertexTexCoord2" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2 -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS - #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS "vertexBoneIds" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS -#endif -#ifndef RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS - #define RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS "vertexBoneWeights" // Bound by default to shader location: RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS -#endif - -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MVP - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MVP "mvp" // model-view-projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW - #define RL_DEFAULT_SHADER_UNIFORM_NAME_VIEW "matView" // view matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION - #define RL_DEFAULT_SHADER_UNIFORM_NAME_PROJECTION "matProjection" // projection matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_MODEL "matModel" // model matrix -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL - #define RL_DEFAULT_SHADER_UNIFORM_NAME_NORMAL "matNormal" // normal matrix (transpose(inverse(matModelView)) -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR - #define RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR "colDiffuse" // color diffuse (base tint color, multiplied by texture color) -#endif -#ifndef RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES - #define RL_DEFAULT_SHADER_UNIFORM_NAME_BONE_MATRICES "boneMatrices" // bone matrices -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0 "texture0" // texture0 (texture slot active 0) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE1 "texture1" // texture1 (texture slot active 1) -#endif -#ifndef RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 - #define RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE2 "texture2" // texture2 (texture slot active 2) -#endif - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -typedef struct rlglData { - rlRenderBatch *currentBatch; // Current render batch - rlRenderBatch defaultBatch; // Default internal render batch - - struct { - int vertexCounter; // Current active render batch vertex counter (generic, used for all batches) - float texcoordx, texcoordy; // Current active texture coordinate (added on glVertex*()) - float normalx, normaly, normalz; // Current active normal (added on glVertex*()) - unsigned char colorr, colorg, colorb, colora; // Current active color (added on glVertex*()) - - int currentMatrixMode; // Current matrix mode - Matrix *currentMatrix; // Current matrix pointer - Matrix modelview; // Default modelview matrix - Matrix projection; // Default projection matrix - Matrix transform; // Transform matrix to be used with rlTranslate, rlRotate, rlScale - bool transformRequired; // Require transform matrix application to current draw-call vertex (if required) - Matrix stack[RL_MAX_MATRIX_STACK_SIZE];// Matrix stack for push/pop - int stackCounter; // Matrix stack counter - - unsigned int defaultTextureId; // Default texture used on shapes/poly drawing (required by shader) - unsigned int activeTextureId[RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS]; // Active texture ids to be enabled on batch drawing (0 active by default) - unsigned int defaultVShaderId; // Default vertex shader id (used by default shader program) - unsigned int defaultFShaderId; // Default fragment shader id (used by default shader program) - unsigned int defaultShaderId; // Default shader program id, supports vertex color and diffuse texture - int *defaultShaderLocs; // Default shader locations pointer to be used on rendering - unsigned int currentShaderId; // Current shader id to be used on rendering (by default, defaultShaderId) - int *currentShaderLocs; // Current shader locations pointer to be used on rendering (by default, defaultShaderLocs) - - bool stereoRender; // Stereo rendering flag - Matrix projectionStereo[2]; // VR stereo rendering eyes projection matrices - Matrix viewOffsetStereo[2]; // VR stereo rendering eyes view offset matrices - - // Blending variables - int currentBlendMode; // Blending mode active - int glBlendSrcFactor; // Blending source factor - int glBlendDstFactor; // Blending destination factor - int glBlendEquation; // Blending equation - int glBlendSrcFactorRGB; // Blending source RGB factor - int glBlendDestFactorRGB; // Blending destination RGB factor - int glBlendSrcFactorAlpha; // Blending source alpha factor - int glBlendDestFactorAlpha; // Blending destination alpha factor - int glBlendEquationRGB; // Blending equation for RGB - int glBlendEquationAlpha; // Blending equation for alpha - bool glCustomBlendModeModified; // Custom blending factor and equation modification status - - int framebufferWidth; // Current framebuffer width - int framebufferHeight; // Current framebuffer height - - } State; // Renderer state - struct { - bool vao; // VAO support (OpenGL ES2 could not support VAO extension) (GL_ARB_vertex_array_object) - bool instancing; // Instancing supported (GL_ANGLE_instanced_arrays, GL_EXT_draw_instanced + GL_EXT_instanced_arrays) - bool texNPOT; // NPOT textures full support (GL_ARB_texture_non_power_of_two, GL_OES_texture_npot) - bool texDepth; // Depth textures supported (GL_ARB_depth_texture, GL_OES_depth_texture) - bool texDepthWebGL; // Depth textures supported WebGL specific (GL_WEBGL_depth_texture) - bool texFloat32; // float textures support (32 bit per channel) (GL_OES_texture_float) - bool texFloat16; // half float textures support (16 bit per channel) (GL_OES_texture_half_float) - bool texCompDXT; // DDS texture compression support (GL_EXT_texture_compression_s3tc, GL_WEBGL_compressed_texture_s3tc, GL_WEBKIT_WEBGL_compressed_texture_s3tc) - bool texCompETC1; // ETC1 texture compression support (GL_OES_compressed_ETC1_RGB8_texture, GL_WEBGL_compressed_texture_etc1) - bool texCompETC2; // ETC2/EAC texture compression support (GL_ARB_ES3_compatibility) - bool texCompPVRT; // PVR texture compression support (GL_IMG_texture_compression_pvrtc) - bool texCompASTC; // ASTC texture compression support (GL_KHR_texture_compression_astc_hdr, GL_KHR_texture_compression_astc_ldr) - bool texMirrorClamp; // Clamp mirror wrap mode supported (GL_EXT_texture_mirror_clamp) - bool texAnisoFilter; // Anisotropic texture filtering support (GL_EXT_texture_filter_anisotropic) - bool computeShader; // Compute shaders support (GL_ARB_compute_shader) - bool ssbo; // Shader storage buffer object support (GL_ARB_shader_storage_buffer_object) - - float maxAnisotropyLevel; // Maximum anisotropy level supported (minimum is 2.0f) - int maxDepthBits; // Maximum bits for depth component - - } ExtSupported; // Extensions supported flags -} rlglData; - -typedef void *(*rlglLoadProc)(const char *name); // OpenGL extension functions loader signature (same as GLADloadproc) - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -//---------------------------------------------------------------------------------- -// Global Variables Definition -//---------------------------------------------------------------------------------- -static double rlCullDistanceNear = RL_CULL_DISTANCE_NEAR; -static double rlCullDistanceFar = RL_CULL_DISTANCE_FAR; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static rlglData RLGL = { 0 }; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -#if defined(GRAPHICS_API_OPENGL_ES2) && !defined(GRAPHICS_API_OPENGL_ES3) -// NOTE: VAO functionality is exposed through extensions (OES) -static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays = NULL; -static PFNGLBINDVERTEXARRAYOESPROC glBindVertexArray = NULL; -static PFNGLDELETEVERTEXARRAYSOESPROC glDeleteVertexArrays = NULL; - -// NOTE: Instancing functionality could also be available through extension -static PFNGLDRAWARRAYSINSTANCEDEXTPROC glDrawArraysInstanced = NULL; -static PFNGLDRAWELEMENTSINSTANCEDEXTPROC glDrawElementsInstanced = NULL; -static PFNGLVERTEXATTRIBDIVISOREXTPROC glVertexAttribDivisor = NULL; -#endif - -//---------------------------------------------------------------------------------- -// Module specific Functions Declaration -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -static void rlLoadShaderDefault(void); // Load default shader -static void rlUnloadShaderDefault(void); // Unload default shader -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -static const char *rlGetCompressedFormatName(int format); // Get compressed format official GL identifier name -#endif // RLGL_SHOW_GL_DETAILS_INFO -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -static int rlGetPixelDataSize(int width, int height, int format); // Get pixel data size in bytes (image or texture) - -// Auxiliar matrix math functions -typedef struct rl_float16 { - float v[16]; -} rl_float16; -static rl_float16 rlMatrixToFloatV(Matrix mat); // Get float array of matrix data -#define rlMatrixToFloat(mat) (rlMatrixToFloatV(mat).v) // Get float vector for Matrix -static Matrix rlMatrixIdentity(void); // Get identity matrix -static Matrix rlMatrixMultiply(Matrix left, Matrix right); // Multiply two matrices -static Matrix rlMatrixTranspose(Matrix mat); // Transposes provided matrix -static Matrix rlMatrixInvert(Matrix mat); // Invert provided matrix - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Matrix operations -//---------------------------------------------------------------------------------- - -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlMatrixMode(int mode) -{ - switch (mode) - { - case RL_PROJECTION: glMatrixMode(GL_PROJECTION); break; - case RL_MODELVIEW: glMatrixMode(GL_MODELVIEW); break; - case RL_TEXTURE: glMatrixMode(GL_TEXTURE); break; - default: break; - } -} - -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - glFrustum(left, right, bottom, top, znear, zfar); -} - -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - glOrtho(left, right, bottom, top, znear, zfar); -} - -void rlPushMatrix(void) { glPushMatrix(); } -void rlPopMatrix(void) { glPopMatrix(); } -void rlLoadIdentity(void) { glLoadIdentity(); } -void rlTranslatef(float x, float y, float z) { glTranslatef(x, y, z); } -void rlRotatef(float angle, float x, float y, float z) { glRotatef(angle, x, y, z); } -void rlScalef(float x, float y, float z) { glScalef(x, y, z); } -void rlMultMatrixf(const float *matf) { glMultMatrixf(matf); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Choose the current matrix to be transformed -void rlMatrixMode(int mode) -{ - if (mode == RL_PROJECTION) RLGL.State.currentMatrix = &RLGL.State.projection; - else if (mode == RL_MODELVIEW) RLGL.State.currentMatrix = &RLGL.State.modelview; - //else if (mode == RL_TEXTURE) // Not supported - - RLGL.State.currentMatrixMode = mode; -} - -// Push the current matrix into RLGL.State.stack -void rlPushMatrix(void) -{ - if (RLGL.State.stackCounter >= RL_MAX_MATRIX_STACK_SIZE) TRACELOG(RL_LOG_ERROR, "RLGL: Matrix stack overflow (RL_MAX_MATRIX_STACK_SIZE)"); - - if (RLGL.State.currentMatrixMode == RL_MODELVIEW) - { - RLGL.State.transformRequired = true; - RLGL.State.currentMatrix = &RLGL.State.transform; - } - - RLGL.State.stack[RLGL.State.stackCounter] = *RLGL.State.currentMatrix; - RLGL.State.stackCounter++; -} - -// Pop lattest inserted matrix from RLGL.State.stack -void rlPopMatrix(void) -{ - if (RLGL.State.stackCounter > 0) - { - Matrix mat = RLGL.State.stack[RLGL.State.stackCounter - 1]; - *RLGL.State.currentMatrix = mat; - RLGL.State.stackCounter--; - } - - if ((RLGL.State.stackCounter == 0) && (RLGL.State.currentMatrixMode == RL_MODELVIEW)) - { - RLGL.State.currentMatrix = &RLGL.State.modelview; - RLGL.State.transformRequired = false; - } -} - -// Reset current matrix to identity matrix -void rlLoadIdentity(void) -{ - *RLGL.State.currentMatrix = rlMatrixIdentity(); -} - -// Multiply the current matrix by a translation matrix -void rlTranslatef(float x, float y, float z) -{ - Matrix matTranslation = { - 1.0f, 0.0f, 0.0f, x, - 0.0f, 1.0f, 0.0f, y, - 0.0f, 0.0f, 1.0f, z, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matTranslation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a rotation matrix -// NOTE: The provided angle must be in degrees -void rlRotatef(float angle, float x, float y, float z) -{ - Matrix matRotation = rlMatrixIdentity(); - - // Axis vector (x, y, z) normalization - float lengthSquared = x*x + y*y + z*z; - if ((lengthSquared != 1.0f) && (lengthSquared != 0.0f)) - { - float inverseLength = 1.0f/sqrtf(lengthSquared); - x *= inverseLength; - y *= inverseLength; - z *= inverseLength; - } - - // Rotation matrix generation - float sinres = sinf(DEG2RAD*angle); - float cosres = cosf(DEG2RAD*angle); - float t = 1.0f - cosres; - - matRotation.m0 = x*x*t + cosres; - matRotation.m1 = y*x*t + z*sinres; - matRotation.m2 = z*x*t - y*sinres; - matRotation.m3 = 0.0f; - - matRotation.m4 = x*y*t - z*sinres; - matRotation.m5 = y*y*t + cosres; - matRotation.m6 = z*y*t + x*sinres; - matRotation.m7 = 0.0f; - - matRotation.m8 = x*z*t + y*sinres; - matRotation.m9 = y*z*t - x*sinres; - matRotation.m10 = z*z*t + cosres; - matRotation.m11 = 0.0f; - - matRotation.m12 = 0.0f; - matRotation.m13 = 0.0f; - matRotation.m14 = 0.0f; - matRotation.m15 = 1.0f; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matRotation, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a scaling matrix -void rlScalef(float x, float y, float z) -{ - Matrix matScale = { - x, 0.0f, 0.0f, 0.0f, - 0.0f, y, 0.0f, 0.0f, - 0.0f, 0.0f, z, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - // NOTE: We transpose matrix with multiplication order - *RLGL.State.currentMatrix = rlMatrixMultiply(matScale, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by another matrix -void rlMultMatrixf(const float *matf) -{ - // Matrix creation from array - Matrix mat = { matf[0], matf[4], matf[8], matf[12], - matf[1], matf[5], matf[9], matf[13], - matf[2], matf[6], matf[10], matf[14], - matf[3], matf[7], matf[11], matf[15] }; - - *RLGL.State.currentMatrix = rlMatrixMultiply(mat, *RLGL.State.currentMatrix); -} - -// Multiply the current matrix by a perspective matrix generated by parameters -void rlFrustum(double left, double right, double bottom, double top, double znear, double zfar) -{ - Matrix matFrustum = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matFrustum.m0 = ((float) znear*2.0f)/rl; - matFrustum.m1 = 0.0f; - matFrustum.m2 = 0.0f; - matFrustum.m3 = 0.0f; - - matFrustum.m4 = 0.0f; - matFrustum.m5 = ((float) znear*2.0f)/tb; - matFrustum.m6 = 0.0f; - matFrustum.m7 = 0.0f; - - matFrustum.m8 = ((float)right + (float)left)/rl; - matFrustum.m9 = ((float)top + (float)bottom)/tb; - matFrustum.m10 = -((float)zfar + (float)znear)/fn; - matFrustum.m11 = -1.0f; - - matFrustum.m12 = 0.0f; - matFrustum.m13 = 0.0f; - matFrustum.m14 = -((float)zfar*(float)znear*2.0f)/fn; - matFrustum.m15 = 0.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matFrustum); -} - -// Multiply the current matrix by an orthographic matrix generated by parameters -void rlOrtho(double left, double right, double bottom, double top, double znear, double zfar) -{ - // NOTE: If left-right and top-botton values are equal it could create a division by zero, - // response to it is platform/compiler dependant - Matrix matOrtho = { 0 }; - - float rl = (float)(right - left); - float tb = (float)(top - bottom); - float fn = (float)(zfar - znear); - - matOrtho.m0 = 2.0f/rl; - matOrtho.m1 = 0.0f; - matOrtho.m2 = 0.0f; - matOrtho.m3 = 0.0f; - matOrtho.m4 = 0.0f; - matOrtho.m5 = 2.0f/tb; - matOrtho.m6 = 0.0f; - matOrtho.m7 = 0.0f; - matOrtho.m8 = 0.0f; - matOrtho.m9 = 0.0f; - matOrtho.m10 = -2.0f/fn; - matOrtho.m11 = 0.0f; - matOrtho.m12 = -((float)left + (float)right)/rl; - matOrtho.m13 = -((float)top + (float)bottom)/tb; - matOrtho.m14 = -((float)zfar + (float)znear)/fn; - matOrtho.m15 = 1.0f; - - *RLGL.State.currentMatrix = rlMatrixMultiply(*RLGL.State.currentMatrix, matOrtho); -} -#endif - -// Set the viewport area (transformation from normalized device coordinates to window coordinates) -// NOTE: We store current viewport dimensions -void rlViewport(int x, int y, int width, int height) -{ - glViewport(x, y, width, height); -} - -// Set clip planes distances -void rlSetClipPlanes(double nearPlane, double farPlane) -{ - rlCullDistanceNear = nearPlane; - rlCullDistanceFar = farPlane; -} - -// Get cull plane distance near -double rlGetCullDistanceNear(void) -{ - return rlCullDistanceNear; -} - -// Get cull plane distance far -double rlGetCullDistanceFar(void) -{ - return rlCullDistanceFar; -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - Vertex level operations -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_11) -// Fallback to OpenGL 1.1 function calls -//--------------------------------------- -void rlBegin(int mode) -{ - switch (mode) - { - case RL_LINES: glBegin(GL_LINES); break; - case RL_TRIANGLES: glBegin(GL_TRIANGLES); break; - case RL_QUADS: glBegin(GL_QUADS); break; - default: break; - } -} - -void rlEnd(void) { glEnd(); } -void rlVertex2i(int x, int y) { glVertex2i(x, y); } -void rlVertex2f(float x, float y) { glVertex2f(x, y); } -void rlVertex3f(float x, float y, float z) { glVertex3f(x, y, z); } -void rlTexCoord2f(float x, float y) { glTexCoord2f(x, y); } -void rlNormal3f(float x, float y, float z) { glNormal3f(x, y, z); } -void rlColor4ub(unsigned char r, unsigned char g, unsigned char b, unsigned char a) { glColor4ub(r, g, b, a); } -void rlColor3f(float x, float y, float z) { glColor3f(x, y, z); } -void rlColor4f(float x, float y, float z, float w) { glColor4f(x, y, z, w); } -#endif -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Initialize drawing mode (how to organize vertex) -void rlBegin(int mode) -{ - // Draw mode can be RL_LINES, RL_TRIANGLES and RL_QUADS - // NOTE: In all three cases, vertex are accumulated over default internal vertex buffer - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode != mode) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = mode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = RLGL.State.defaultTextureId; - } -} - -// Finish vertex providing -void rlEnd(void) -{ - // NOTE: Depth increment is dependant on rlOrtho(): z-near and z-far values, - // as well as depth buffer bit-depth (16bit or 24bit or 32bit) - // Correct increment formula would be: depthInc = (zfar - znear)/pow(2, bits) - RLGL.currentBatch->currentDepth += (1.0f/20000.0f); -} - -// Define one vertex (position) -// NOTE: Vertex position data is the basic information required for drawing -void rlVertex3f(float x, float y, float z) -{ - float tx = x; - float ty = y; - float tz = z; - - // Transform provided vector if required - if (RLGL.State.transformRequired) - { - tx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z + RLGL.State.transform.m12; - ty = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z + RLGL.State.transform.m13; - tz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z + RLGL.State.transform.m14; - } - - // WARNING: We can't break primitives when launching a new batch - // RL_LINES comes in pairs, RL_TRIANGLES come in groups of 3 vertices and RL_QUADS come in groups of 4 vertices - // We must check current draw.mode when a new vertex is required and finish the batch only if the draw.mode draw.vertexCount is %2, %3 or %4 - if (RLGL.State.vertexCounter > (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4 - 4)) - { - if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%2 == 0)) - { - // Reached the maximum number of vertices for RL_LINES drawing - // Launch a draw call but keep current state for next vertices comming - // NOTE: We add +1 vertex to the check for security - rlCheckRenderBatchLimit(2 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%3 == 0)) - { - rlCheckRenderBatchLimit(3 + 1); - } - else if ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_QUADS) && - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4 == 0)) - { - rlCheckRenderBatchLimit(4 + 1); - } - } - - // Add vertices - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter] = tx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 1] = ty; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].vertices[3*RLGL.State.vertexCounter + 2] = tz; - - // Add current texcoord - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter] = RLGL.State.texcoordx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].texcoords[2*RLGL.State.vertexCounter + 1] = RLGL.State.texcoordy; - - // Add current normal - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter] = RLGL.State.normalx; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 1] = RLGL.State.normaly; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].normals[3*RLGL.State.vertexCounter + 2] = RLGL.State.normalz; - - // Add current color - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter] = RLGL.State.colorr; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 1] = RLGL.State.colorg; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 2] = RLGL.State.colorb; - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].colors[4*RLGL.State.vertexCounter + 3] = RLGL.State.colora; - - RLGL.State.vertexCounter++; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount++; -} - -// Define one vertex (position) -void rlVertex2f(float x, float y) -{ - rlVertex3f(x, y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (position) -void rlVertex2i(int x, int y) -{ - rlVertex3f((float)x, (float)y, RLGL.currentBatch->currentDepth); -} - -// Define one vertex (texture coordinate) -// NOTE: Texture coordinates are limited to QUADS only -void rlTexCoord2f(float x, float y) -{ - RLGL.State.texcoordx = x; - RLGL.State.texcoordy = y; -} - -// Define one vertex (normal) -// NOTE: Normals limited to TRIANGLES only? -void rlNormal3f(float x, float y, float z) -{ - float normalx = x; - float normaly = y; - float normalz = z; - if (RLGL.State.transformRequired) - { - normalx = RLGL.State.transform.m0*x + RLGL.State.transform.m4*y + RLGL.State.transform.m8*z; - normaly = RLGL.State.transform.m1*x + RLGL.State.transform.m5*y + RLGL.State.transform.m9*z; - normalz = RLGL.State.transform.m2*x + RLGL.State.transform.m6*y + RLGL.State.transform.m10*z; - } - float length = sqrtf(normalx*normalx + normaly*normaly + normalz*normalz); - if (length != 0.0f) - { - float ilength = 1.0f/length; - normalx *= ilength; - normaly *= ilength; - normalz *= ilength; - } - RLGL.State.normalx = normalx; - RLGL.State.normaly = normaly; - RLGL.State.normalz = normalz; -} - -// Define one vertex (color) -void rlColor4ub(unsigned char x, unsigned char y, unsigned char z, unsigned char w) -{ - RLGL.State.colorr = x; - RLGL.State.colorg = y; - RLGL.State.colorb = z; - RLGL.State.colora = w; -} - -// Define one vertex (color) -void rlColor4f(float r, float g, float b, float a) -{ - rlColor4ub((unsigned char)(r*255), (unsigned char)(g*255), (unsigned char)(b*255), (unsigned char)(a*255)); -} - -// Define one vertex (color) -void rlColor3f(float x, float y, float z) -{ - rlColor4ub((unsigned char)(x*255), (unsigned char)(y*255), (unsigned char)(z*255), 255); -} - -#endif - -//-------------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL style functions (common to 1.1, 3.3+, ES2) -//-------------------------------------------------------------------------------------- - -// Set current texture to use -void rlSetTexture(unsigned int id) -{ - if (id == 0) - { -#if defined(GRAPHICS_API_OPENGL_11) - rlDisableTexture(); -#else - // NOTE: If quads batch limit is reached, we force a draw call and next batch starts - if (RLGL.State.vertexCounter >= - RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4) - { - rlDrawRenderBatch(RLGL.currentBatch); - } -#endif - } - else - { -#if defined(GRAPHICS_API_OPENGL_11) - rlEnableTexture(id); -#else - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId != id) - { - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount > 0) - { - // Make sure current RLGL.currentBatch->draws[i].vertexCount is aligned a multiple of 4, - // that way, following QUADS drawing will keep aligned with index processing - // It implies adding some extra alignment vertex at the end of the draw, - // those vertex are not processed but they are considered as an additional offset - // for the next set of vertex to be drawn - if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_LINES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount : RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4); - else if (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode == RL_TRIANGLES) RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = ((RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount < 4)? 1 : (4 - (RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount%4))); - else RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment = 0; - - if (!rlCheckRenderBatchLimit(RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment)) - { - RLGL.State.vertexCounter += RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexAlignment; - - RLGL.currentBatch->drawCounter++; - } - } - - if (RLGL.currentBatch->drawCounter >= RL_DEFAULT_BATCH_DRAWCALLS) rlDrawRenderBatch(RLGL.currentBatch); - - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = id; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].vertexCount = 0; - } -#endif - } -} - -// Select and active a texture slot -void rlActiveTextureSlot(int slot) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glActiveTexture(GL_TEXTURE0 + slot); -#endif -} - -// Enable texture -void rlEnableTexture(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, id); -} - -// Disable texture -void rlDisableTexture(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_TEXTURE_2D); -#endif - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Enable texture cubemap -void rlEnableTextureCubemap(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); -#endif -} - -// Disable texture cubemap -void rlDisableTextureCubemap(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Set texture parameters (wrap mode/filter mode) -void rlTextureParameters(unsigned int id, int param, int value) -{ - glBindTexture(GL_TEXTURE_2D, id); - -#if !defined(GRAPHICS_API_OPENGL_11) - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); -#endif - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_2D, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); -#endif - } - else glTexParameteri(GL_TEXTURE_2D, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_2D, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { -#if !defined(GRAPHICS_API_OPENGL_11) - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); -#endif - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_2D, 0); -} - -// Set cubemap parameters (wrap mode/filter mode) -void rlCubemapParameters(unsigned int id, int param, int value) -{ -#if !defined(GRAPHICS_API_OPENGL_11) - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - // Reset anisotropy filter, in case it was set - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, 1.0f); - - switch (param) - { - case RL_TEXTURE_WRAP_S: - case RL_TEXTURE_WRAP_T: - { - if (value == RL_TEXTURE_WRAP_MIRROR_CLAMP) - { - if (RLGL.ExtSupported.texMirrorClamp) glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - else TRACELOG(RL_LOG_WARNING, "GL: Clamp mirror wrap mode not supported (GL_MIRROR_CLAMP_EXT)"); - } - else glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); - - } break; - case RL_TEXTURE_MAG_FILTER: - case RL_TEXTURE_MIN_FILTER: glTexParameteri(GL_TEXTURE_CUBE_MAP, param, value); break; - case RL_TEXTURE_FILTER_ANISOTROPIC: - { - if (value <= RLGL.ExtSupported.maxAnisotropyLevel) glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - else if (RLGL.ExtSupported.maxAnisotropyLevel > 0.0f) - { - TRACELOG(RL_LOG_WARNING, "GL: Maximum anisotropic filter level supported is %iX", id, (int)RLGL.ExtSupported.maxAnisotropyLevel); - glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)value); - } - else TRACELOG(RL_LOG_WARNING, "GL: Anisotropic filtering not supported"); - } break; -#if defined(GRAPHICS_API_OPENGL_33) - case RL_TEXTURE_MIPMAP_BIAS_RATIO: glTexParameterf(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_LOD_BIAS, value/100.0f); -#endif - default: break; - } - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif -} - -// Enable shader program -void rlEnableShader(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(id); -#endif -} - -// Disable shader program -void rlDisableShader(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - glUseProgram(0); -#endif -} - -// Enable rendering to texture (fbo) -void rlEnableFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); -#endif -} - -// return the active render texture (fbo) -unsigned int rlGetActiveFramebuffer(void) -{ - GLint fboId = 0; -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) - glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &fboId); -#endif - return fboId; -} - -// Disable rendering to texture -void rlDisableFramebuffer(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Blit active framebuffer to main framebuffer -void rlBlitFramebuffer(int srcX, int srcY, int srcWidth, int srcHeight, int dstX, int dstY, int dstWidth, int dstHeight, int bufferMask) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBlitFramebuffer(srcX, srcY, srcWidth, srcHeight, dstX, dstY, dstWidth, dstHeight, bufferMask, GL_NEAREST); -#endif -} - -// Bind framebuffer object (fbo) -void rlBindFramebuffer(unsigned int target, unsigned int framebuffer) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(target, framebuffer); -#endif -} - -// Activate multiple draw color buffers -// NOTE: One color buffer is always active by default -void rlActiveDrawBuffers(int count) -{ -#if ((defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES3)) && defined(RLGL_RENDER_TEXTURES_HINT)) - // NOTE: Maximum number of draw buffers supported is implementation dependant, - // it can be queried with glGet*() but it must be at least 8 - //GLint maxDrawBuffers = 0; - //glGetIntegerv(GL_MAX_DRAW_BUFFERS, &maxDrawBuffers); - - if (count > 0) - { - if (count > 8) TRACELOG(LOG_WARNING, "GL: Max color buffers limited to 8"); - else - { - unsigned int buffers[8] = { -#if defined(GRAPHICS_API_OPENGL_ES3) - GL_COLOR_ATTACHMENT0_EXT, - GL_COLOR_ATTACHMENT1_EXT, - GL_COLOR_ATTACHMENT2_EXT, - GL_COLOR_ATTACHMENT3_EXT, - GL_COLOR_ATTACHMENT4_EXT, - GL_COLOR_ATTACHMENT5_EXT, - GL_COLOR_ATTACHMENT6_EXT, - GL_COLOR_ATTACHMENT7_EXT, -#else - GL_COLOR_ATTACHMENT0, - GL_COLOR_ATTACHMENT1, - GL_COLOR_ATTACHMENT2, - GL_COLOR_ATTACHMENT3, - GL_COLOR_ATTACHMENT4, - GL_COLOR_ATTACHMENT5, - GL_COLOR_ATTACHMENT6, - GL_COLOR_ATTACHMENT7, -#endif - }; - -#if defined(GRAPHICS_API_OPENGL_ES3) - glDrawBuffersEXT(count, buffers); -#else - glDrawBuffers(count, buffers); -#endif - } - } - else TRACELOG(LOG_WARNING, "GL: One color buffer active by default"); -#endif -} - -//---------------------------------------------------------------------------------- -// General render state configuration -//---------------------------------------------------------------------------------- - -// Enable color blending -void rlEnableColorBlend(void) { glEnable(GL_BLEND); } - -// Disable color blending -void rlDisableColorBlend(void) { glDisable(GL_BLEND); } - -// Enable depth test -void rlEnableDepthTest(void) { glEnable(GL_DEPTH_TEST); } - -// Disable depth test -void rlDisableDepthTest(void) { glDisable(GL_DEPTH_TEST); } - -// Enable depth write -void rlEnableDepthMask(void) { glDepthMask(GL_TRUE); } - -// Disable depth write -void rlDisableDepthMask(void) { glDepthMask(GL_FALSE); } - -// Enable backface culling -void rlEnableBackfaceCulling(void) { glEnable(GL_CULL_FACE); } - -// Disable backface culling -void rlDisableBackfaceCulling(void) { glDisable(GL_CULL_FACE); } - -// Set color mask active for screen read/draw -void rlColorMask(bool r, bool g, bool b, bool a) { glColorMask(r, g, b, a); } - -// Set face culling mode -void rlSetCullFace(int mode) -{ - switch (mode) - { - case RL_CULL_FACE_BACK: glCullFace(GL_BACK); break; - case RL_CULL_FACE_FRONT: glCullFace(GL_FRONT); break; - default: break; - } -} - -// Enable scissor test -void rlEnableScissorTest(void) { glEnable(GL_SCISSOR_TEST); } - -// Disable scissor test -void rlDisableScissorTest(void) { glDisable(GL_SCISSOR_TEST); } - -// Scissor test -void rlScissor(int x, int y, int width, int height) { glScissor(x, y, width, height); } - -// Enable wire mode -void rlEnableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); -#endif -} - -// Enable point mode -void rlEnablePointMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_POINT); - glEnable(GL_PROGRAM_POINT_SIZE); -#endif -} - -// Disable wire mode -void rlDisableWireMode(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - // NOTE: glPolygonMode() not available on OpenGL ES - glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); -#endif -} - -// Set the line drawing width -void rlSetLineWidth(float width) { glLineWidth(width); } - -// Get the line drawing width -float rlGetLineWidth(void) -{ - float width = 0; - glGetFloatv(GL_LINE_WIDTH, &width); - return width; -} - -// Enable line aliasing -void rlEnableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glEnable(GL_LINE_SMOOTH); -#endif -} - -// Disable line aliasing -void rlDisableSmoothLines(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_11) - glDisable(GL_LINE_SMOOTH); -#endif -} - -// Enable stereo rendering -void rlEnableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = true; -#endif -} - -// Disable stereo rendering -void rlDisableStereoRender(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - RLGL.State.stereoRender = false; -#endif -} - -// Check if stereo render is enabled -bool rlIsStereoRenderEnabled(void) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) - return RLGL.State.stereoRender; -#else - return false; -#endif -} - -// Clear color buffer with color -void rlClearColor(unsigned char r, unsigned char g, unsigned char b, unsigned char a) -{ - // Color values clamp to 0.0f(0) and 1.0f(255) - float cr = (float)r/255; - float cg = (float)g/255; - float cb = (float)b/255; - float ca = (float)a/255; - - glClearColor(cr, cg, cb, ca); -} - -// Clear used screen buffers (color and depth) -void rlClearScreenBuffers(void) -{ - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear used buffers: Color and Depth (Depth is used for 3D) - //glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Stencil buffer not used... -} - -// Check and log OpenGL error codes -void rlCheckErrors(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int check = 1; - while (check) - { - const GLenum err = glGetError(); - switch (err) - { - case GL_NO_ERROR: check = 0; break; - case 0x0500: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_ENUM"); break; - case 0x0501: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_VALUE"); break; - case 0x0502: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_OPERATION"); break; - case 0x0503: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_OVERFLOW"); break; - case 0x0504: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_STACK_UNDERFLOW"); break; - case 0x0505: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_OUT_OF_MEMORY"); break; - case 0x0506: TRACELOG(RL_LOG_WARNING, "GL: Error detected: GL_INVALID_FRAMEBUFFER_OPERATION"); break; - default: TRACELOG(RL_LOG_WARNING, "GL: Error detected: Unknown error code: %x", err); break; - } - } -#endif -} - -// Set blend mode -void rlSetBlendMode(int mode) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.currentBlendMode != mode) || ((mode == RL_BLEND_CUSTOM || mode == RL_BLEND_CUSTOM_SEPARATE) && RLGL.State.glCustomBlendModeModified)) - { - rlDrawRenderBatch(RLGL.currentBatch); - - switch (mode) - { - case RL_BLEND_ALPHA: glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADDITIVE: glBlendFunc(GL_SRC_ALPHA, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_MULTIPLIED: glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_ADD_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_SUBTRACT_COLORS: glBlendFunc(GL_ONE, GL_ONE); glBlendEquation(GL_FUNC_SUBTRACT); break; - case RL_BLEND_ALPHA_PREMULTIPLY: glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glBlendEquation(GL_FUNC_ADD); break; - case RL_BLEND_CUSTOM: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactors() - glBlendFunc(RLGL.State.glBlendSrcFactor, RLGL.State.glBlendDstFactor); glBlendEquation(RLGL.State.glBlendEquation); - - } break; - case RL_BLEND_CUSTOM_SEPARATE: - { - // NOTE: Using GL blend src/dst factors and GL equation configured with rlSetBlendFactorsSeparate() - glBlendFuncSeparate(RLGL.State.glBlendSrcFactorRGB, RLGL.State.glBlendDestFactorRGB, RLGL.State.glBlendSrcFactorAlpha, RLGL.State.glBlendDestFactorAlpha); - glBlendEquationSeparate(RLGL.State.glBlendEquationRGB, RLGL.State.glBlendEquationAlpha); - - } break; - default: break; - } - - RLGL.State.currentBlendMode = mode; - RLGL.State.glCustomBlendModeModified = false; - } -#endif -} - -// Set blending mode factor and equation -void rlSetBlendFactors(int glSrcFactor, int glDstFactor, int glEquation) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactor != glSrcFactor) || - (RLGL.State.glBlendDstFactor != glDstFactor) || - (RLGL.State.glBlendEquation != glEquation)) - { - RLGL.State.glBlendSrcFactor = glSrcFactor; - RLGL.State.glBlendDstFactor = glDstFactor; - RLGL.State.glBlendEquation = glEquation; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -// Set blending mode factor and equation separately for RGB and alpha -void rlSetBlendFactorsSeparate(int glSrcRGB, int glDstRGB, int glSrcAlpha, int glDstAlpha, int glEqRGB, int glEqAlpha) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.glBlendSrcFactorRGB != glSrcRGB) || - (RLGL.State.glBlendDestFactorRGB != glDstRGB) || - (RLGL.State.glBlendSrcFactorAlpha != glSrcAlpha) || - (RLGL.State.glBlendDestFactorAlpha != glDstAlpha) || - (RLGL.State.glBlendEquationRGB != glEqRGB) || - (RLGL.State.glBlendEquationAlpha != glEqAlpha)) - { - RLGL.State.glBlendSrcFactorRGB = glSrcRGB; - RLGL.State.glBlendDestFactorRGB = glDstRGB; - RLGL.State.glBlendSrcFactorAlpha = glSrcAlpha; - RLGL.State.glBlendDestFactorAlpha = glDstAlpha; - RLGL.State.glBlendEquationRGB = glEqRGB; - RLGL.State.glBlendEquationAlpha = glEqAlpha; - - RLGL.State.glCustomBlendModeModified = true; - } -#endif -} - -//---------------------------------------------------------------------------------- -// Module Functions Definition - OpenGL Debug -//---------------------------------------------------------------------------------- -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) -static void GLAPIENTRY rlDebugMessageCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const void *userParam) -{ - // Ignore non-significant error/warning codes (NVidia drivers) - // NOTE: Here there are the details with a sample output: - // - #131169 - Framebuffer detailed info: The driver allocated storage for renderbuffer 2. (severity: low) - // - #131185 - Buffer detailed info: Buffer object 1 (bound to GL_ELEMENT_ARRAY_BUFFER_ARB, usage hint is GL_ENUM_88e4) - // will use VIDEO memory as the source for buffer object operations. (severity: low) - // - #131218 - Program/shader state performance warning: Vertex shader in program 7 is being recompiled based on GL state. (severity: medium) - // - #131204 - Texture state usage warning: The texture object (0) bound to texture image unit 0 does not have - // a defined base level and cannot be used for texture mapping. (severity: low) - if ((id == 131169) || (id == 131185) || (id == 131218) || (id == 131204)) return; - - const char *msgSource = NULL; - switch (source) - { - case GL_DEBUG_SOURCE_API: msgSource = "API"; break; - case GL_DEBUG_SOURCE_WINDOW_SYSTEM: msgSource = "WINDOW_SYSTEM"; break; - case GL_DEBUG_SOURCE_SHADER_COMPILER: msgSource = "SHADER_COMPILER"; break; - case GL_DEBUG_SOURCE_THIRD_PARTY: msgSource = "THIRD_PARTY"; break; - case GL_DEBUG_SOURCE_APPLICATION: msgSource = "APPLICATION"; break; - case GL_DEBUG_SOURCE_OTHER: msgSource = "OTHER"; break; - default: break; - } - - const char *msgType = NULL; - switch (type) - { - case GL_DEBUG_TYPE_ERROR: msgType = "ERROR"; break; - case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: msgType = "DEPRECATED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: msgType = "UNDEFINED_BEHAVIOR"; break; - case GL_DEBUG_TYPE_PORTABILITY: msgType = "PORTABILITY"; break; - case GL_DEBUG_TYPE_PERFORMANCE: msgType = "PERFORMANCE"; break; - case GL_DEBUG_TYPE_MARKER: msgType = "MARKER"; break; - case GL_DEBUG_TYPE_PUSH_GROUP: msgType = "PUSH_GROUP"; break; - case GL_DEBUG_TYPE_POP_GROUP: msgType = "POP_GROUP"; break; - case GL_DEBUG_TYPE_OTHER: msgType = "OTHER"; break; - default: break; - } - - const char *msgSeverity = "DEFAULT"; - switch (severity) - { - case GL_DEBUG_SEVERITY_LOW: msgSeverity = "LOW"; break; - case GL_DEBUG_SEVERITY_MEDIUM: msgSeverity = "MEDIUM"; break; - case GL_DEBUG_SEVERITY_HIGH: msgSeverity = "HIGH"; break; - case GL_DEBUG_SEVERITY_NOTIFICATION: msgSeverity = "NOTIFICATION"; break; - default: break; - } - - TRACELOG(LOG_WARNING, "GL: OpenGL debug message: %s", message); - TRACELOG(LOG_WARNING, " > Type: %s", msgType); - TRACELOG(LOG_WARNING, " > Source = %s", msgSource); - TRACELOG(LOG_WARNING, " > Severity = %s", msgSeverity); -} -#endif - -//---------------------------------------------------------------------------------- -// Module Functions Definition - rlgl functionality -//---------------------------------------------------------------------------------- - -// Initialize rlgl: OpenGL extensions, default buffers/shaders/textures, OpenGL states -void rlglInit(int width, int height) -{ - // Enable OpenGL debug context if required -#if defined(RLGL_ENABLE_OPENGL_DEBUG_CONTEXT) && defined(GRAPHICS_API_OPENGL_43) - if ((glDebugMessageCallback != NULL) && (glDebugMessageControl != NULL)) - { - glDebugMessageCallback(rlDebugMessageCallback, 0); - // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_ERROR, GL_DEBUG_SEVERITY_HIGH, 0, 0, GL_TRUE); - - // Debug context options: - // - GL_DEBUG_OUTPUT - Faster version but not useful for breakpoints - // - GL_DEBUG_OUTPUT_SYNCHRONUS - Callback is in sync with errors, so a breakpoint can be placed on the callback in order to get a stacktrace for the GL error - glEnable(GL_DEBUG_OUTPUT); - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); - } -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Init default white texture - unsigned char pixels[4] = { 255, 255, 255, 255 }; // 1 pixel RGBA (4 bytes) - RLGL.State.defaultTextureId = rlLoadTexture(pixels, 1, 1, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); - - if (RLGL.State.defaultTextureId != 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture loaded successfully", RLGL.State.defaultTextureId); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load default texture"); - - // Init default Shader (customized for GL 3.3 and ES2) - // Loaded: RLGL.State.defaultShaderId + RLGL.State.defaultShaderLocs - rlLoadShaderDefault(); - RLGL.State.currentShaderId = RLGL.State.defaultShaderId; - RLGL.State.currentShaderLocs = RLGL.State.defaultShaderLocs; - - // Init default vertex arrays buffers - // Simulate that the default shader has the location RL_SHADER_LOC_VERTEX_NORMAL to bind the normal buffer for the default render batch - RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL; - RLGL.defaultBatch = rlLoadRenderBatch(RL_DEFAULT_BATCH_BUFFERS, RL_DEFAULT_BATCH_BUFFER_ELEMENTS); - RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL] = -1; - RLGL.currentBatch = &RLGL.defaultBatch; - - // Init stack matrices (emulating OpenGL 1.1) - for (int i = 0; i < RL_MAX_MATRIX_STACK_SIZE; i++) RLGL.State.stack[i] = rlMatrixIdentity(); - - // Init internal matrices - RLGL.State.transform = rlMatrixIdentity(); - RLGL.State.projection = rlMatrixIdentity(); - RLGL.State.modelview = rlMatrixIdentity(); - RLGL.State.currentMatrix = &RLGL.State.modelview; -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - - // Initialize OpenGL default states - //---------------------------------------------------------- - // Init state: Depth test - glDepthFunc(GL_LEQUAL); // Type of depth testing to apply - glDisable(GL_DEPTH_TEST); // Disable depth testing for 2D (only used for 3D) - - // Init state: Blending mode - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Color blending function (how colors are mixed) - glEnable(GL_BLEND); // Enable color blending (required to work with transparencies) - - // Init state: Culling - // NOTE: All shapes/models triangles are drawn CCW - glCullFace(GL_BACK); // Cull the back face (default) - glFrontFace(GL_CCW); // Front face are defined counter clockwise (default) - glEnable(GL_CULL_FACE); // Enable backface culling - - // Init state: Cubemap seamless -#if defined(GRAPHICS_API_OPENGL_33) - glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // Seamless cubemaps (not supported on OpenGL ES 2.0) -#endif - -#if defined(GRAPHICS_API_OPENGL_11) - // Init state: Color hints (deprecated in OpenGL 3.0+) - glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Improve quality of color and texture coordinate interpolation - glShadeModel(GL_SMOOTH); // Smooth shading between vertex (vertex colors interpolation) -#endif - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Store screen size into global variables - RLGL.State.framebufferWidth = width; - RLGL.State.framebufferHeight = height; - - TRACELOG(RL_LOG_INFO, "RLGL: Default OpenGL state initialized successfully"); - //---------------------------------------------------------- -#endif - - // Init state: Color/Depth buffers clear - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set clear color (black) - glClearDepth(1.0f); // Set clear depth value (default) - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear color and depth buffers (depth buffer required for 3D) -} - -// Vertex Buffer Object deinitialization (memory free) -void rlglClose(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlUnloadRenderBatch(RLGL.defaultBatch); - - rlUnloadShaderDefault(); // Unload default shader - - glDeleteTextures(1, &RLGL.State.defaultTextureId); // Unload default texture - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Default texture unloaded successfully", RLGL.State.defaultTextureId); -#endif -} - -// Load OpenGL extensions -// NOTE: External loader function must be provided -void rlLoadExtensions(void *loader) -{ -#if defined(GRAPHICS_API_OPENGL_33) // Also defined for GRAPHICS_API_OPENGL_21 - // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) - if (gladLoadGL((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL extensions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL extensions loaded successfully"); - - // Get number of supported extensions - GLint numExt = 0; - glGetIntegerv(GL_NUM_EXTENSIONS, &numExt); - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Get supported extensions list - // WARNING: glGetStringi() not available on OpenGL 2.1 - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", glGetStringi(GL_EXTENSIONS, i)); -#endif - -#if defined(GRAPHICS_API_OPENGL_21) - // Register supported extensions flags - // Optional OpenGL 2.1 extensions - RLGL.ExtSupported.vao = GLAD_GL_ARB_vertex_array_object; - RLGL.ExtSupported.instancing = (GLAD_GL_EXT_draw_instanced && GLAD_GL_ARB_instanced_arrays); - RLGL.ExtSupported.texNPOT = GLAD_GL_ARB_texture_non_power_of_two; - RLGL.ExtSupported.texFloat32 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texFloat16 = GLAD_GL_ARB_texture_float; - RLGL.ExtSupported.texDepth = GLAD_GL_ARB_depth_texture; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = GLAD_GL_EXT_texture_filter_anisotropic; - RLGL.ExtSupported.texMirrorClamp = GLAD_GL_EXT_texture_mirror_clamp; -#else - // Register supported extensions flags - // OpenGL 3.3 extensions supported by default (core) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.maxDepthBits = 32; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; -#endif - - // Optional OpenGL 3.3 extensions - RLGL.ExtSupported.texCompASTC = GLAD_GL_KHR_texture_compression_astc_hdr && GLAD_GL_KHR_texture_compression_astc_ldr; - RLGL.ExtSupported.texCompDXT = GLAD_GL_EXT_texture_compression_s3tc; // Texture compression: DXT - RLGL.ExtSupported.texCompETC2 = GLAD_GL_ARB_ES3_compatibility; // Texture compression: ETC2/EAC - #if defined(GRAPHICS_API_OPENGL_43) - RLGL.ExtSupported.computeShader = GLAD_GL_ARB_compute_shader; - RLGL.ExtSupported.ssbo = GLAD_GL_ARB_shader_storage_buffer_object; - #endif - -#endif // GRAPHICS_API_OPENGL_33 - -#if defined(GRAPHICS_API_OPENGL_ES3) - // Register supported extensions flags - // OpenGL ES 3.0 extensions supported by default (or it should be) - RLGL.ExtSupported.vao = true; - RLGL.ExtSupported.instancing = true; - RLGL.ExtSupported.texNPOT = true; - RLGL.ExtSupported.texFloat32 = true; - RLGL.ExtSupported.texFloat16 = true; - RLGL.ExtSupported.texDepth = true; - RLGL.ExtSupported.texDepthWebGL = true; - RLGL.ExtSupported.maxDepthBits = 24; - RLGL.ExtSupported.texAnisoFilter = true; - RLGL.ExtSupported.texMirrorClamp = true; - // TODO: Check for additional OpenGL ES 3.0 supported extensions: - //RLGL.ExtSupported.texCompDXT = true; - //RLGL.ExtSupported.texCompETC1 = true; - //RLGL.ExtSupported.texCompETC2 = true; - //RLGL.ExtSupported.texCompPVRT = true; - //RLGL.ExtSupported.texCompASTC = true; - //RLGL.ExtSupported.maxAnisotropyLevel = true; - //RLGL.ExtSupported.computeShader = true; - //RLGL.ExtSupported.ssbo = true; - -#elif defined(GRAPHICS_API_OPENGL_ES2) - - #if defined(PLATFORM_DESKTOP_GLFW) || defined(PLATFORM_DESKTOP_SDL) - // TODO: Support GLAD loader for OpenGL ES 3.0 - if (gladLoadGLES2((GLADloadfunc)loader) == 0) TRACELOG(RL_LOG_WARNING, "GLAD: Cannot load OpenGL ES2.0 functions"); - else TRACELOG(RL_LOG_INFO, "GLAD: OpenGL ES 2.0 loaded successfully"); - #endif - - // Get supported extensions list - GLint numExt = 0; - const char **extList = RL_MALLOC(512*sizeof(const char *)); // Allocate 512 strings pointers (2 KB) - const char *extensions = (const char *)glGetString(GL_EXTENSIONS); // One big const string - - // NOTE: We have to duplicate string because glGetString() returns a const string - int size = strlen(extensions) + 1; // Get extensions string size in bytes - char *extensionsDup = (char *)RL_CALLOC(size, sizeof(char)); - strcpy(extensionsDup, extensions); - extList[numExt] = extensionsDup; - - for (int i = 0; i < size; i++) - { - if (extensionsDup[i] == ' ') - { - extensionsDup[i] = '\0'; - numExt++; - extList[numExt] = &extensionsDup[i + 1]; - } - } - - TRACELOG(RL_LOG_INFO, "GL: Supported extensions count: %i", numExt); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - TRACELOG(RL_LOG_INFO, "GL: OpenGL extensions:"); - for (int i = 0; i < numExt; i++) TRACELOG(RL_LOG_INFO, " %s", extList[i]); -#endif - - // Check required extensions - for (int i = 0; i < numExt; i++) - { - // Check VAO support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has VAO support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_vertex_array_object") == 0) - { - // The extension is supported by our hardware and driver, try to get related functions pointers - // NOTE: emscripten does not support VAOs natively, it uses emulation and it reduces overall performance... - glGenVertexArrays = (PFNGLGENVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glGenVertexArraysOES"); - glBindVertexArray = (PFNGLBINDVERTEXARRAYOESPROC)((rlglLoadProc)loader)("glBindVertexArrayOES"); - glDeleteVertexArrays = (PFNGLDELETEVERTEXARRAYSOESPROC)((rlglLoadProc)loader)("glDeleteVertexArraysOES"); - //glIsVertexArray = (PFNGLISVERTEXARRAYOESPROC)loader("glIsVertexArrayOES"); // NOTE: Fails in WebGL, omitted - - if ((glGenVertexArrays != NULL) && (glBindVertexArray != NULL) && (glDeleteVertexArrays != NULL)) RLGL.ExtSupported.vao = true; - } - - // Check instanced rendering support - if (strstr(extList[i], (const char*)"instanced_arrays") != NULL) // Broad check for instanced_arrays - { - // Specific check - if (strcmp(extList[i], (const char *)"GL_ANGLE_instanced_arrays") == 0) // ANGLE - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedANGLE"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedANGLE"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorANGLE"); - } - else if (strcmp(extList[i], (const char *)"GL_EXT_instanced_arrays") == 0) // EXT - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorEXT"); - } - else if (strcmp(extList[i], (const char *)"GL_NV_instanced_arrays") == 0) // NVIDIA GLES - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedNV"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedNV"); - glVertexAttribDivisor = (PFNGLVERTEXATTRIBDIVISOREXTPROC)((rlglLoadProc)loader)("glVertexAttribDivisorNV"); - } - - // The feature will only be marked as supported if the elements from GL_XXX_instanced_arrays are present - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - else if (strstr(extList[i], (const char *)"draw_instanced") != NULL) - { - // GL_ANGLE_draw_instanced doesn't exist - if (strcmp(extList[i], (const char *)"GL_EXT_draw_instanced") == 0) - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedEXT"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedEXT"); - } - else if (strcmp(extList[i], (const char*)"GL_NV_draw_instanced") == 0) - { - glDrawArraysInstanced = (PFNGLDRAWARRAYSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawArraysInstancedNV"); - glDrawElementsInstanced = (PFNGLDRAWELEMENTSINSTANCEDEXTPROC)((rlglLoadProc)loader)("glDrawElementsInstancedNV"); - } - - // But the functions will at least be loaded if only GL_XX_EXT_draw_instanced exist - if ((glDrawArraysInstanced != NULL) && (glDrawElementsInstanced != NULL) && (glVertexAttribDivisor != NULL)) RLGL.ExtSupported.instancing = true; - } - - // Check NPOT textures support - // NOTE: Only check on OpenGL ES, OpenGL 3.3 has NPOT textures full support as core feature - if (strcmp(extList[i], (const char *)"GL_OES_texture_npot") == 0) RLGL.ExtSupported.texNPOT = true; - - // Check texture float support - if (strcmp(extList[i], (const char *)"GL_OES_texture_float") == 0) RLGL.ExtSupported.texFloat32 = true; - if (strcmp(extList[i], (const char *)"GL_OES_texture_half_float") == 0) RLGL.ExtSupported.texFloat16 = true; - - // Check depth texture support - if (strcmp(extList[i], (const char *)"GL_OES_depth_texture") == 0) RLGL.ExtSupported.texDepth = true; - if (strcmp(extList[i], (const char *)"GL_WEBGL_depth_texture") == 0) RLGL.ExtSupported.texDepthWebGL = true; // WebGL requires unsized internal format - if (RLGL.ExtSupported.texDepthWebGL) RLGL.ExtSupported.texDepth = true; - - if (strcmp(extList[i], (const char *)"GL_OES_depth24") == 0) RLGL.ExtSupported.maxDepthBits = 24; // Not available on WebGL - if (strcmp(extList[i], (const char *)"GL_OES_depth32") == 0) RLGL.ExtSupported.maxDepthBits = 32; // Not available on WebGL - - // Check texture compression support: DXT - if ((strcmp(extList[i], (const char *)"GL_EXT_texture_compression_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_s3tc") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBKIT_WEBGL_compressed_texture_s3tc") == 0)) RLGL.ExtSupported.texCompDXT = true; - - // Check texture compression support: ETC1 - if ((strcmp(extList[i], (const char *)"GL_OES_compressed_ETC1_RGB8_texture") == 0) || - (strcmp(extList[i], (const char *)"GL_WEBGL_compressed_texture_etc1") == 0)) RLGL.ExtSupported.texCompETC1 = true; - - // Check texture compression support: ETC2/EAC - if (strcmp(extList[i], (const char *)"GL_ARB_ES3_compatibility") == 0) RLGL.ExtSupported.texCompETC2 = true; - - // Check texture compression support: PVR - if (strcmp(extList[i], (const char *)"GL_IMG_texture_compression_pvrtc") == 0) RLGL.ExtSupported.texCompPVRT = true; - - // Check texture compression support: ASTC - if (strcmp(extList[i], (const char *)"GL_KHR_texture_compression_astc_hdr") == 0) RLGL.ExtSupported.texCompASTC = true; - - // Check anisotropic texture filter support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_filter_anisotropic") == 0) RLGL.ExtSupported.texAnisoFilter = true; - - // Check clamp mirror wrap mode support - if (strcmp(extList[i], (const char *)"GL_EXT_texture_mirror_clamp") == 0) RLGL.ExtSupported.texMirrorClamp = true; - } - - // Free extensions pointers - RL_FREE(extList); - RL_FREE(extensionsDup); // Duplicated string must be deallocated -#endif // GRAPHICS_API_OPENGL_ES2 - - // Check OpenGL information and capabilities - //------------------------------------------------------------------------------ - // Show current OpenGL and GLSL version - TRACELOG(RL_LOG_INFO, "GL: OpenGL device information:"); - TRACELOG(RL_LOG_INFO, " > Vendor: %s", glGetString(GL_VENDOR)); - TRACELOG(RL_LOG_INFO, " > Renderer: %s", glGetString(GL_RENDERER)); - TRACELOG(RL_LOG_INFO, " > Version: %s", glGetString(GL_VERSION)); - TRACELOG(RL_LOG_INFO, " > GLSL: %s", glGetString(GL_SHADING_LANGUAGE_VERSION)); - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Anisotropy levels capability is an extension - #ifndef GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT - #define GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT 0x84FF - #endif - glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &RLGL.ExtSupported.maxAnisotropyLevel); - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) - // Show some OpenGL GPU capabilities - TRACELOG(RL_LOG_INFO, "GL: OpenGL capabilities:"); - GLint capability = 0; - glGetIntegerv(GL_MAX_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_CUBE_MAP_TEXTURE_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_CUBE_MAP_TEXTURE_SIZE: %i", capability); - glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_IMAGE_UNITS: %i", capability); - glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIBS: %i", capability); - #if !defined(GRAPHICS_API_OPENGL_ES2) - glGetIntegerv(GL_MAX_UNIFORM_BLOCK_SIZE, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_BLOCK_SIZE: %i", capability); - glGetIntegerv(GL_MAX_DRAW_BUFFERS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_DRAW_BUFFERS: %i", capability); - if (RLGL.ExtSupported.texAnisoFilter) TRACELOG(RL_LOG_INFO, " GL_MAX_TEXTURE_MAX_ANISOTROPY: %.0f", RLGL.ExtSupported.maxAnisotropyLevel); - #endif - glGetIntegerv(GL_NUM_COMPRESSED_TEXTURE_FORMATS, &capability); - TRACELOG(RL_LOG_INFO, " GL_NUM_COMPRESSED_TEXTURE_FORMATS: %i", capability); - GLint *compFormats = (GLint *)RL_CALLOC(capability, sizeof(GLint)); - glGetIntegerv(GL_COMPRESSED_TEXTURE_FORMATS, compFormats); - for (int i = 0; i < capability; i++) TRACELOG(RL_LOG_INFO, " %s", rlGetCompressedFormatName(compFormats[i])); - RL_FREE(compFormats); - -#if defined(GRAPHICS_API_OPENGL_43) - glGetIntegerv(GL_MAX_VERTEX_ATTRIB_BINDINGS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_VERTEX_ATTRIB_BINDINGS: %i", capability); - glGetIntegerv(GL_MAX_UNIFORM_LOCATIONS, &capability); - TRACELOG(RL_LOG_INFO, " GL_MAX_UNIFORM_LOCATIONS: %i", capability); -#endif // GRAPHICS_API_OPENGL_43 -#else // RLGL_SHOW_GL_DETAILS_INFO - - // Show some basic info about GL supported features - if (RLGL.ExtSupported.vao) TRACELOG(RL_LOG_INFO, "GL: VAO extension detected, VAO functions loaded successfully"); - else TRACELOG(RL_LOG_WARNING, "GL: VAO extension not found, VAO not supported"); - if (RLGL.ExtSupported.texNPOT) TRACELOG(RL_LOG_INFO, "GL: NPOT textures extension detected, full NPOT textures supported"); - else TRACELOG(RL_LOG_WARNING, "GL: NPOT textures extension not found, limited NPOT support (no-mipmaps, no-repeat)"); - if (RLGL.ExtSupported.texCompDXT) TRACELOG(RL_LOG_INFO, "GL: DXT compressed textures supported"); - if (RLGL.ExtSupported.texCompETC1) TRACELOG(RL_LOG_INFO, "GL: ETC1 compressed textures supported"); - if (RLGL.ExtSupported.texCompETC2) TRACELOG(RL_LOG_INFO, "GL: ETC2/EAC compressed textures supported"); - if (RLGL.ExtSupported.texCompPVRT) TRACELOG(RL_LOG_INFO, "GL: PVRT compressed textures supported"); - if (RLGL.ExtSupported.texCompASTC) TRACELOG(RL_LOG_INFO, "GL: ASTC compressed textures supported"); - if (RLGL.ExtSupported.computeShader) TRACELOG(RL_LOG_INFO, "GL: Compute shaders supported"); - if (RLGL.ExtSupported.ssbo) TRACELOG(RL_LOG_INFO, "GL: Shader storage buffer objects supported"); -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 -} - -// Get current OpenGL version -int rlGetVersion(void) -{ - int glVersion = 0; -#if defined(GRAPHICS_API_OPENGL_11) - glVersion = RL_OPENGL_11; -#endif -#if defined(GRAPHICS_API_OPENGL_21) - glVersion = RL_OPENGL_21; -#elif defined(GRAPHICS_API_OPENGL_43) - glVersion = RL_OPENGL_43; -#elif defined(GRAPHICS_API_OPENGL_33) - glVersion = RL_OPENGL_33; -#endif -#if defined(GRAPHICS_API_OPENGL_ES3) - glVersion = RL_OPENGL_ES_30; -#elif defined(GRAPHICS_API_OPENGL_ES2) - glVersion = RL_OPENGL_ES_20; -#endif - - return glVersion; -} - -// Set current framebuffer width -void rlSetFramebufferWidth(int width) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferWidth = width; -#endif -} - -// Set current framebuffer height -void rlSetFramebufferHeight(int height) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.framebufferHeight = height; -#endif -} - -// Get default framebuffer width -int rlGetFramebufferWidth(void) -{ - int width = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - width = RLGL.State.framebufferWidth; -#endif - return width; -} - -// Get default framebuffer height -int rlGetFramebufferHeight(void) -{ - int height = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - height = RLGL.State.framebufferHeight; -#endif - return height; -} - -// Get default internal texture (white texture) -// NOTE: Default texture is a 1x1 pixel UNCOMPRESSED_R8G8B8A8 -unsigned int rlGetTextureIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultTextureId; -#endif - return id; -} - -// Get default shader id -unsigned int rlGetShaderIdDefault(void) -{ - unsigned int id = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - id = RLGL.State.defaultShaderId; -#endif - return id; -} - -// Get default shader locs -int *rlGetShaderLocsDefault(void) -{ - int *locs = NULL; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - locs = RLGL.State.defaultShaderLocs; -#endif - return locs; -} - -// Render batch management -//------------------------------------------------------------------------------------------------ -// Load render batch -rlRenderBatch rlLoadRenderBatch(int numBuffers, int bufferElements) -{ - rlRenderBatch batch = { 0 }; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Initialize CPU (RAM) vertex buffers (position, texcoord, color data and indexes) - //-------------------------------------------------------------------------------------------- - batch.vertexBuffer = (rlVertexBuffer *)RL_MALLOC(numBuffers*sizeof(rlVertexBuffer)); - - for (int i = 0; i < numBuffers; i++) - { - batch.vertexBuffer[i].elementCount = bufferElements; - - batch.vertexBuffer[i].vertices = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad - batch.vertexBuffer[i].texcoords = (float *)RL_MALLOC(bufferElements*2*4*sizeof(float)); // 2 float by texcoord, 4 texcoord by quad - batch.vertexBuffer[i].normals = (float *)RL_MALLOC(bufferElements*3*4*sizeof(float)); // 3 float by vertex, 4 vertex by quad - batch.vertexBuffer[i].colors = (unsigned char *)RL_MALLOC(bufferElements*4*4*sizeof(unsigned char)); // 4 float by color, 4 colors by quad -#if defined(GRAPHICS_API_OPENGL_33) - batch.vertexBuffer[i].indices = (unsigned int *)RL_MALLOC(bufferElements*6*sizeof(unsigned int)); // 6 int by quad (indices) -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - batch.vertexBuffer[i].indices = (unsigned short *)RL_MALLOC(bufferElements*6*sizeof(unsigned short)); // 6 int by quad (indices) -#endif - - for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].vertices[j] = 0.0f; - for (int j = 0; j < (2*4*bufferElements); j++) batch.vertexBuffer[i].texcoords[j] = 0.0f; - for (int j = 0; j < (3*4*bufferElements); j++) batch.vertexBuffer[i].normals[j] = 0.0f; - for (int j = 0; j < (4*4*bufferElements); j++) batch.vertexBuffer[i].colors[j] = 0; - - int k = 0; - - // Indices can be initialized right now - for (int j = 0; j < (6*bufferElements); j += 6) - { - batch.vertexBuffer[i].indices[j] = 4*k; - batch.vertexBuffer[i].indices[j + 1] = 4*k + 1; - batch.vertexBuffer[i].indices[j + 2] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 3] = 4*k; - batch.vertexBuffer[i].indices[j + 4] = 4*k + 2; - batch.vertexBuffer[i].indices[j + 5] = 4*k + 3; - - k++; - } - - RLGL.State.vertexCounter = 0; - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in RAM (CPU)"); - //-------------------------------------------------------------------------------------------- - - // Upload to GPU (VRAM) vertex data and initialize VAOs/VBOs - //-------------------------------------------------------------------------------------------- - for (int i = 0; i < numBuffers; i++) - { - if (RLGL.ExtSupported.vao) - { - // Initialize Quads VAO - glGenVertexArrays(1, &batch.vertexBuffer[i].vaoId); - glBindVertexArray(batch.vertexBuffer[i].vaoId); - } - - // Quads - Vertex buffers binding and attributes enable - // Vertex position buffer (shader-location = 0) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[0]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].vertices, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - - // Vertex texcoord buffer (shader-location = 1) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[1]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*2*4*sizeof(float), batch.vertexBuffer[i].texcoords, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - - // Vertex normal buffer (shader-location = 2) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[2]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*3*4*sizeof(float), batch.vertexBuffer[i].normals, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); - - // Vertex color buffer (shader-location = 3) - glGenBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glBindBuffer(GL_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[3]); - glBufferData(GL_ARRAY_BUFFER, bufferElements*4*4*sizeof(unsigned char), batch.vertexBuffer[i].colors, GL_DYNAMIC_DRAW); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - - // Fill index buffer - glGenBuffers(1, &batch.vertexBuffer[i].vboId[4]); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch.vertexBuffer[i].vboId[4]); -#if defined(GRAPHICS_API_OPENGL_33) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(int), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif -#if defined(GRAPHICS_API_OPENGL_ES2) - glBufferData(GL_ELEMENT_ARRAY_BUFFER, bufferElements*6*sizeof(short), batch.vertexBuffer[i].indices, GL_STATIC_DRAW); -#endif - } - - TRACELOG(RL_LOG_INFO, "RLGL: Render batch vertex buffers loaded successfully in VRAM (GPU)"); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - //-------------------------------------------------------------------------------------------- - - // Init draw calls tracking system - //-------------------------------------------------------------------------------------------- - batch.draws = (rlDrawCall *)RL_MALLOC(RL_DEFAULT_BATCH_DRAWCALLS*sizeof(rlDrawCall)); - - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch.draws[i].mode = RL_QUADS; - batch.draws[i].vertexCount = 0; - batch.draws[i].vertexAlignment = 0; - //batch.draws[i].vaoId = 0; - //batch.draws[i].shaderId = 0; - batch.draws[i].textureId = RLGL.State.defaultTextureId; - //batch.draws[i].RLGL.State.projection = rlMatrixIdentity(); - //batch.draws[i].RLGL.State.modelview = rlMatrixIdentity(); - } - - batch.bufferCount = numBuffers; // Record buffer count - batch.drawCounter = 1; // Reset draws counter - batch.currentDepth = -1.0f; // Reset depth value - //-------------------------------------------------------------------------------------------- -#endif - - return batch; -} - -// Unload default internal buffers vertex data from CPU and GPU -void rlUnloadRenderBatch(rlRenderBatch batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Unbind everything - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // Unload all vertex buffers data - for (int i = 0; i < batch.bufferCount; i++) - { - // Unbind VAO attribs data - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(batch.vertexBuffer[i].vaoId); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); - glDisableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR); - glBindVertexArray(0); - } - - // Delete VBOs from GPU (VRAM) - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[0]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[1]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[2]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[3]); - glDeleteBuffers(1, &batch.vertexBuffer[i].vboId[4]); - - // Delete VAOs from GPU (VRAM) - if (RLGL.ExtSupported.vao) glDeleteVertexArrays(1, &batch.vertexBuffer[i].vaoId); - - // Free vertex arrays memory from CPU (RAM) - RL_FREE(batch.vertexBuffer[i].vertices); - RL_FREE(batch.vertexBuffer[i].texcoords); - RL_FREE(batch.vertexBuffer[i].normals); - RL_FREE(batch.vertexBuffer[i].colors); - RL_FREE(batch.vertexBuffer[i].indices); - } - - // Unload arrays - RL_FREE(batch.vertexBuffer); - RL_FREE(batch.draws); -#endif -} - -// Draw render batch -// NOTE: We require a pointer to reset batch and increase current buffer (multi-buffer) -void rlDrawRenderBatch(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Update batch vertex buffers - //------------------------------------------------------------------------------------------------------------ - // NOTE: If there is not vertex data, buffers doesn't need to be updated (vertexCount > 0) - // TODO: If no data changed on the CPU arrays --> No need to re-update GPU arrays (use a change detector flag?) - if (RLGL.State.vertexCounter > 0) - { - // Activate elements VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - - // Vertex positions buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].vertices); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].vertices, GL_DYNAMIC_DRAW); // Update all buffer - - // Texture coordinates buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*2*sizeof(float), batch->vertexBuffer[batch->currentBuffer].texcoords); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*2*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].texcoords, GL_DYNAMIC_DRAW); // Update all buffer - - // Normals buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*3*sizeof(float), batch->vertexBuffer[batch->currentBuffer].normals); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*3*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].normals, GL_DYNAMIC_DRAW); // Update all buffer - - // Colors buffer - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); - glBufferSubData(GL_ARRAY_BUFFER, 0, RLGL.State.vertexCounter*4*sizeof(unsigned char), batch->vertexBuffer[batch->currentBuffer].colors); - //glBufferData(GL_ARRAY_BUFFER, sizeof(float)*4*4*batch->vertexBuffer[batch->currentBuffer].elementCount, batch->vertexBuffer[batch->currentBuffer].colors, GL_DYNAMIC_DRAW); // Update all buffer - - // NOTE: glMapBuffer() causes sync issue - // If GPU is working with this buffer, glMapBuffer() will wait(stall) until GPU to finish its job - // To avoid waiting (idle), you can call first glBufferData() with NULL pointer before glMapBuffer() - // If you do that, the previous data in PBO will be discarded and glMapBuffer() returns a new - // allocated pointer immediately even if GPU is still working with the previous data - - // Another option: map the buffer object into client's memory - // Probably this code could be moved somewhere else... - // batch->vertexBuffer[batch->currentBuffer].vertices = (float *)glMapBuffer(GL_ARRAY_BUFFER, GL_READ_WRITE); - // if (batch->vertexBuffer[batch->currentBuffer].vertices) - // { - // Update vertex data - // } - // glUnmapBuffer(GL_ARRAY_BUFFER); - - // Unbind the current VAO - if (RLGL.ExtSupported.vao) glBindVertexArray(0); - } - //------------------------------------------------------------------------------------------------------------ - - // Draw batch vertex buffers (considering VR stereo if required) - //------------------------------------------------------------------------------------------------------------ - Matrix matProjection = RLGL.State.projection; - Matrix matModelView = RLGL.State.modelview; - - int eyeCount = 1; - if (RLGL.State.stereoRender) eyeCount = 2; - - for (int eye = 0; eye < eyeCount; eye++) - { - if (eyeCount == 2) - { - // Setup current eye viewport (half screen width) - rlViewport(eye*RLGL.State.framebufferWidth/2, 0, RLGL.State.framebufferWidth/2, RLGL.State.framebufferHeight); - - // Set current eye view offset to modelview matrix - rlSetMatrixModelview(rlMatrixMultiply(matModelView, RLGL.State.viewOffsetStereo[eye])); - // Set current eye projection matrix - rlSetMatrixProjection(RLGL.State.projectionStereo[eye]); - } - - // Draw buffers - if (RLGL.State.vertexCounter > 0) - { - // Set current shader and upload current MVP matrix - glUseProgram(RLGL.State.currentShaderId); - - // Create modelview-projection matrix and upload to shader - Matrix matMVP = rlMatrixMultiply(RLGL.State.modelview, RLGL.State.projection); - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MVP], 1, false, rlMatrixToFloat(matMVP)); - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_PROJECTION], 1, false, rlMatrixToFloat(RLGL.State.projection)); - } - - // WARNING: For the following setup of the view, model, and normal matrices, it is expected that - // transformations and rendering occur between rlPushMatrix() and rlPopMatrix() - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_VIEW], 1, false, rlMatrixToFloat(RLGL.State.modelview)); - } - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_MODEL], 1, false, rlMatrixToFloat(RLGL.State.transform)); - } - - if (RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL] != -1) - { - glUniformMatrix4fv(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MATRIX_NORMAL], 1, false, rlMatrixToFloat(rlMatrixTranspose(rlMatrixInvert(RLGL.State.transform)))); - } - - if (RLGL.ExtSupported.vao) glBindVertexArray(batch->vertexBuffer[batch->currentBuffer].vaoId); - else - { - // Bind vertex attrib: position (shader-location = 0) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[0]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_POSITION]); - - // Bind vertex attrib: texcoord (shader-location = 1) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[1]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01], 2, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01]); - - // Bind vertex attrib: normal (shader-location = 2) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[2]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL], 3, GL_FLOAT, 0, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_NORMAL]); - - // Bind vertex attrib: color (shader-location = 3) - glBindBuffer(GL_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[3]); - glVertexAttribPointer(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR], 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, 0); - glEnableVertexAttribArray(RLGL.State.currentShaderLocs[RL_SHADER_LOC_VERTEX_COLOR]); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, batch->vertexBuffer[batch->currentBuffer].vboId[4]); - } - - // Setup some default shader values - glUniform4f(RLGL.State.currentShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE], 1.0f, 1.0f, 1.0f, 1.0f); - glUniform1i(RLGL.State.currentShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE], 0); // Active default sampler2D: texture0 - - // Activate additional sampler textures - // Those additional textures will be common for all draw calls of the batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] > 0) - { - glActiveTexture(GL_TEXTURE0 + 1 + i); - glBindTexture(GL_TEXTURE_2D, RLGL.State.activeTextureId[i]); - } - } - - // Activate default sampler2D texture0 (one texture is always active for default batch shader) - // NOTE: Batch system accumulates calls by texture0 changes, additional textures are enabled for all the draw calls - glActiveTexture(GL_TEXTURE0); - - for (int i = 0, vertexOffset = 0; i < batch->drawCounter; i++) - { - // Bind current draw call texture, activated as GL_TEXTURE0 and Bound to sampler2D texture0 by default - glBindTexture(GL_TEXTURE_2D, batch->draws[i].textureId); - - if ((batch->draws[i].mode == RL_LINES) || (batch->draws[i].mode == RL_TRIANGLES)) glDrawArrays(batch->draws[i].mode, vertexOffset, batch->draws[i].vertexCount); - else - { - #if defined(GRAPHICS_API_OPENGL_33) - // We need to define the number of indices to be processed: elementCount*6 - // NOTE: The final parameter tells the GPU the offset in bytes from the - // start of the index buffer to the location of the first index to process - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_INT, (GLvoid *)(vertexOffset/4*6*sizeof(GLuint))); - #endif - #if defined(GRAPHICS_API_OPENGL_ES2) - glDrawElements(GL_TRIANGLES, batch->draws[i].vertexCount/4*6, GL_UNSIGNED_SHORT, (GLvoid *)(vertexOffset/4*6*sizeof(GLushort))); - #endif - } - - vertexOffset += (batch->draws[i].vertexCount + batch->draws[i].vertexAlignment); - } - - if (!RLGL.ExtSupported.vao) - { - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } - - glBindTexture(GL_TEXTURE_2D, 0); // Unbind textures - } - - if (RLGL.ExtSupported.vao) glBindVertexArray(0); // Unbind VAO - - glUseProgram(0); // Unbind shader program - } - - // Restore viewport to default measures - if (eyeCount == 2) rlViewport(0, 0, RLGL.State.framebufferWidth, RLGL.State.framebufferHeight); - //------------------------------------------------------------------------------------------------------------ - - // Reset batch buffers - //------------------------------------------------------------------------------------------------------------ - // Reset vertex counter for next frame - RLGL.State.vertexCounter = 0; - - // Reset depth for next draw - batch->currentDepth = -1.0f; - - // Restore projection/modelview matrices - RLGL.State.projection = matProjection; - RLGL.State.modelview = matModelView; - - // Reset RLGL.currentBatch->draws array - for (int i = 0; i < RL_DEFAULT_BATCH_DRAWCALLS; i++) - { - batch->draws[i].mode = RL_QUADS; - batch->draws[i].vertexCount = 0; - batch->draws[i].textureId = RLGL.State.defaultTextureId; - } - - // Reset active texture units for next batch - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) RLGL.State.activeTextureId[i] = 0; - - // Reset draws counter to one draw for the batch - batch->drawCounter = 1; - //------------------------------------------------------------------------------------------------------------ - - // Change to next buffer in the list (in case of multi-buffering) - batch->currentBuffer++; - if (batch->currentBuffer >= batch->bufferCount) batch->currentBuffer = 0; -#endif -} - -// Set the active render batch for rlgl -void rlSetRenderBatchActive(rlRenderBatch *batch) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); - - if (batch != NULL) RLGL.currentBatch = batch; - else RLGL.currentBatch = &RLGL.defaultBatch; -#endif -} - -// Update and draw internal render batch -void rlDrawRenderBatchActive(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside -#endif -} - -// Check internal buffer overflow for a given number of vertex -// and force a rlRenderBatch draw call if required -bool rlCheckRenderBatchLimit(int vCount) -{ - bool overflow = false; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((RLGL.State.vertexCounter + vCount) >= - (RLGL.currentBatch->vertexBuffer[RLGL.currentBatch->currentBuffer].elementCount*4)) - { - overflow = true; - - // Store current primitive drawing mode and texture id - int currentMode = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode; - int currentTexture = RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId; - - rlDrawRenderBatch(RLGL.currentBatch); // NOTE: Stereo rendering is checked inside - - // Restore state of last batch so we can continue adding vertices - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].mode = currentMode; - RLGL.currentBatch->draws[RLGL.currentBatch->drawCounter - 1].textureId = currentTexture; - } -#endif - - return overflow; -} - -// Textures data management -//----------------------------------------------------------------------------------------- -// Convert image data to OpenGL texture (returns OpenGL valid Id) -unsigned int rlLoadTexture(const void *data, int width, int height, int format, int mipmapCount) -{ - unsigned int id = 0; - - glBindTexture(GL_TEXTURE_2D, 0); // Free any old binding - - // Check texture format support by OpenGL 1.1 (compressed textures not supported) -#if defined(GRAPHICS_API_OPENGL_11) - if (format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - TRACELOG(RL_LOG_WARNING, "GL: OpenGL 1.1 does not support GPU compressed texture formats"); - return id; - } -#else - if ((!RLGL.ExtSupported.texCompDXT) && ((format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA) || - (format == RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: DXT compressed texture format not supported"); - return id; - } -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if ((!RLGL.ExtSupported.texCompETC1) && (format == RL_PIXELFORMAT_COMPRESSED_ETC1_RGB)) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC1 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompETC2) && ((format == RL_PIXELFORMAT_COMPRESSED_ETC2_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ETC2 compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompPVRT) && ((format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGB) || (format == RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: PVRT compressed texture format not supported"); - return id; - } - - if ((!RLGL.ExtSupported.texCompASTC) && ((format == RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA) || (format == RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA))) - { - TRACELOG(RL_LOG_WARNING, "GL: ASTC compressed texture format not supported"); - return id; - } -#endif -#endif // GRAPHICS_API_OPENGL_11 - - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); - - glGenTextures(1, &id); // Generate texture id - - glBindTexture(GL_TEXTURE_2D, id); - - int mipWidth = width; - int mipHeight = height; - int mipOffset = 0; // Mipmap data offset, only used for tracelog - - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned char *dataPtr = NULL; - if (data != NULL) dataPtr = (unsigned char *)data; - - // Load the different mipmap levels - for (int i = 0; i < mipmapCount; i++) - { - unsigned int mipSize = rlGetPixelDataSize(mipWidth, mipHeight, format); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - TRACELOGD("TEXTURE: Load mipmap level %i (%i x %i), size: %i, offset: %i", i, mipWidth, mipHeight, mipSize, mipOffset); - - if (glInternalFormat != 0) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, glFormat, glType, dataPtr); -#if !defined(GRAPHICS_API_OPENGL_11) - else glCompressedTexImage2D(GL_TEXTURE_2D, i, glInternalFormat, mipWidth, mipHeight, 0, mipSize, dataPtr); -#endif - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - } - - mipWidth /= 2; - mipHeight /= 2; - mipOffset += mipSize; // Increment offset position to next mipmap - if (data != NULL) dataPtr += mipSize; // Increment data pointer to next mipmap - - // Security check for NPOT textures - if (mipWidth < 1) mipWidth = 1; - if (mipHeight < 1) mipHeight = 1; - } - - // Texture parameters configuration - // NOTE: glTexParameteri does NOT affect texture uploading, just the way it's used -#if defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: OpenGL ES 2.0 with no GL_OES_texture_npot support (i.e. WebGL) has limited NPOT support, so CLAMP_TO_EDGE must be used - if (RLGL.ExtSupported.texNPOT) - { - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis - } - else - { - // NOTE: If using negative texture coordinates (LoadOBJ()), it does not work! - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture to clamp on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // Set texture to clamp on y-axis - } -#else - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture to repeat on x-axis - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // Set texture to repeat on y-axis -#endif - - // Magnification and minification filters - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // Alternative: GL_LINEAR - -#if defined(GRAPHICS_API_OPENGL_33) - if (mipmapCount > 1) - { - // Activate Trilinear filtering if mipmaps are available - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - } -#endif - - // At this point we have the texture loaded in GPU and texture parameters configured - - // NOTE: If mipmaps were not in data, they are not generated automatically - - // Unbind current texture - glBindTexture(GL_TEXTURE_2D, 0); - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Texture loaded successfully (%ix%i | %s | %i mipmaps)", id, width, height, rlGetPixelFormatName(format), mipmapCount); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load texture"); - - return id; -} - -// Load depth texture/renderbuffer (to be attached to fbo) -// WARNING: OpenGL ES 2.0 requires GL_OES_depth_texture and WebGL requires WEBGL_depth_texture extensions -unsigned int rlLoadTextureDepth(int width, int height, bool useRenderBuffer) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // In case depth textures not supported, we force renderbuffer usage - if (!RLGL.ExtSupported.texDepth) useRenderBuffer = true; - - // NOTE: We let the implementation to choose the best bit-depth - // Possible formats: GL_DEPTH_COMPONENT16, GL_DEPTH_COMPONENT24, GL_DEPTH_COMPONENT32 and GL_DEPTH_COMPONENT32F - unsigned int glInternalFormat = GL_DEPTH_COMPONENT; - -#if (defined(GRAPHICS_API_OPENGL_ES2) || defined(GRAPHICS_API_OPENGL_ES3)) - // WARNING: WebGL platform requires unsized internal format definition (GL_DEPTH_COMPONENT) - // while other platforms using OpenGL ES 2.0 require/support sized internal formats depending on the GPU capabilities - if (!RLGL.ExtSupported.texDepthWebGL || useRenderBuffer) - { - if (RLGL.ExtSupported.maxDepthBits == 32) glInternalFormat = GL_DEPTH_COMPONENT32_OES; - else if (RLGL.ExtSupported.maxDepthBits == 24) glInternalFormat = GL_DEPTH_COMPONENT24_OES; - else glInternalFormat = GL_DEPTH_COMPONENT16; - } -#endif - - if (!useRenderBuffer && RLGL.ExtSupported.texDepth) - { - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_2D, id); - glTexImage2D(GL_TEXTURE_2D, 0, glInternalFormat, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - - glBindTexture(GL_TEXTURE_2D, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: Depth texture loaded successfully"); - } - else - { - // Create the renderbuffer that will serve as the depth attachment for the framebuffer - // NOTE: A renderbuffer is simpler than a texture and could offer better performance on embedded devices - glGenRenderbuffers(1, &id); - glBindRenderbuffer(GL_RENDERBUFFER, id); - glRenderbufferStorage(GL_RENDERBUFFER, glInternalFormat, width, height); - - glBindRenderbuffer(GL_RENDERBUFFER, 0); - - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Depth renderbuffer loaded successfully (%i bits)", id, (RLGL.ExtSupported.maxDepthBits >= 24)? RLGL.ExtSupported.maxDepthBits : 16); - } -#endif - - return id; -} - -// Load texture cubemap -// NOTE: Cubemap data is expected to be 6 images in a single data array (one after the other), -// expected the following convention: +X, -X, +Y, -Y, +Z, -Z -unsigned int rlLoadTextureCubemap(const void *data, int size, int format, int mipmapCount) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int mipSize = size; - - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned char *dataPtr = NULL; - if (data != NULL) dataPtr = (unsigned char *)data; - - unsigned int dataSize = rlGetPixelDataSize(size, size, format); - - glGenTextures(1, &id); - glBindTexture(GL_TEXTURE_CUBE_MAP, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if (glInternalFormat != 0) - { - // Load cubemap faces/mipmaps - for (int i = 0; i < 6*mipmapCount; i++) - { - int mipmapLevel = i/6; - int face = i%6; - - if (data == NULL) - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) - { - if ((format == RL_PIXELFORMAT_UNCOMPRESSED_R32) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R16) || - (format == RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16)) TRACELOG(RL_LOG_WARNING, "TEXTURES: Cubemap requested format not supported"); - else glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, glFormat, glType, NULL); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURES: Empty cubemap creation does not support compressed format"); - } - else - { - if (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, glFormat, glType, (unsigned char *)dataPtr + face*dataSize); - else glCompressedTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, mipmapLevel, glInternalFormat, mipSize, mipSize, 0, dataSize, (unsigned char *)dataPtr + face*dataSize); - } - -#if defined(GRAPHICS_API_OPENGL_33) - if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE) - { - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ONE }; - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } - else if (format == RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA) - { -#if defined(GRAPHICS_API_OPENGL_21) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_ALPHA }; -#elif defined(GRAPHICS_API_OPENGL_33) - GLint swizzleMask[] = { GL_RED, GL_RED, GL_RED, GL_GREEN }; -#endif - glTexParameteriv(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask); - } -#endif - if (face == 5) - { - mipSize /= 2; - if (data != NULL) dataPtr += dataSize*6; // Increment data pointer to next mipmap - - // Security check for NPOT textures - if (mipSize < 1) mipSize = 1; - - dataSize = rlGetPixelDataSize(mipSize, mipSize, format); - } - } - } - - // Set cubemap texture sampling parameters - if (mipmapCount > 1) glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); - else glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); -#if defined(GRAPHICS_API_OPENGL_33) - glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); // Flag not supported on OpenGL ES 2.0 -#endif - - glBindTexture(GL_TEXTURE_CUBE_MAP, 0); -#endif - - if (id > 0) TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Cubemap texture loaded successfully (%ix%i)", id, size, size); - else TRACELOG(RL_LOG_WARNING, "TEXTURE: Failed to load cubemap texture"); - - return id; -} - -// Update already loaded texture in GPU with new data -// NOTE: We don't know safely if internal texture format is the expected one... -void rlUpdateTexture(unsigned int id, int offsetX, int offsetY, int width, int height, int format, const void *data) -{ - glBindTexture(GL_TEXTURE_2D, id); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - glTexSubImage2D(GL_TEXTURE_2D, 0, offsetX, offsetY, width, height, glFormat, glType, data); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to update for current texture format (%i)", id, format); -} - -// Get OpenGL internal formats and data type from raylib PixelFormat -void rlGetGlTextureFormats(int format, unsigned int *glInternalFormat, unsigned int *glFormat, unsigned int *glType) -{ - *glInternalFormat = 0; - *glFormat = 0; - *glType = 0; - - switch (format) - { - #if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: on OpenGL ES 2.0 (WebGL), internalFormat must match format and options allowed are: GL_LUMINANCE, GL_RGB, GL_RGBA - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_LUMINANCE_ALPHA; *glFormat = GL_LUMINANCE_ALPHA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - #if !defined(GRAPHICS_API_OPENGL_11) - #if defined(GRAPHICS_API_OPENGL_ES3) - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F_EXT; *glFormat = GL_RED_EXT; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F_EXT; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F_EXT; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F_EXT; *glFormat = GL_RED_EXT; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F_EXT; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F_EXT; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #else - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; // NOTE: Requires extension OES_texture_float - #if defined(GRAPHICS_API_OPENGL_21) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_ARB; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_ARB; break; - #else // defined(GRAPHICS_API_OPENGL_ES2) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_LUMINANCE; *glFormat = GL_LUMINANCE; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT_OES; break; // NOTE: Requires extension OES_texture_half_float - #endif - #endif - #endif - #elif defined(GRAPHICS_API_OPENGL_33) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: *glInternalFormat = GL_R8; *glFormat = GL_RED; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: *glInternalFormat = GL_RG8; *glFormat = GL_RG; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: *glInternalFormat = GL_RGB565; *glFormat = GL_RGB; *glType = GL_UNSIGNED_SHORT_5_6_5; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: *glInternalFormat = GL_RGB8; *glFormat = GL_RGB; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: *glInternalFormat = GL_RGB5_A1; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_5_5_5_1; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: *glInternalFormat = GL_RGBA4; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_SHORT_4_4_4_4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: *glInternalFormat = GL_RGBA8; *glFormat = GL_RGBA; *glType = GL_UNSIGNED_BYTE; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_R32F; *glFormat = GL_RED; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGB32F; *glFormat = GL_RGB; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: if (RLGL.ExtSupported.texFloat32) *glInternalFormat = GL_RGBA32F; *glFormat = GL_RGBA; *glType = GL_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_R16F; *glFormat = GL_RED; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGB16F; *glFormat = GL_RGB; *glType = GL_HALF_FLOAT; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: if (RLGL.ExtSupported.texFloat16) *glInternalFormat = GL_RGBA16F; *glFormat = GL_RGBA; *glType = GL_HALF_FLOAT; break; - #endif - #if !defined(GRAPHICS_API_OPENGL_11) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGB_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: if (RLGL.ExtSupported.texCompDXT) *glInternalFormat = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; break; - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: if (RLGL.ExtSupported.texCompETC1) *glInternalFormat = GL_ETC1_RGB8_OES; break; // NOTE: Requires OpenGL ES 2.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGB8_ETC2; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: if (RLGL.ExtSupported.texCompETC2) *glInternalFormat = GL_COMPRESSED_RGBA8_ETC2_EAC; break; // NOTE: Requires OpenGL ES 3.0 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: if (RLGL.ExtSupported.texCompPVRT) *glInternalFormat = GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; // NOTE: Requires PowerVR GPU - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_4x4_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: if (RLGL.ExtSupported.texCompASTC) *glInternalFormat = GL_COMPRESSED_RGBA_ASTC_8x8_KHR; break; // NOTE: Requires OpenGL ES 3.1 or OpenGL 4.3 - #endif - default: TRACELOG(RL_LOG_WARNING, "TEXTURE: Current format not supported (%i)", format); break; - } -} - -// Unload texture from GPU memory -void rlUnloadTexture(unsigned int id) -{ - glDeleteTextures(1, &id); -} - -// Generate mipmap data for selected texture -// NOTE: Only supports GPU mipmap generation -void rlGenTextureMipmaps(unsigned int id, int width, int height, int format, int *mipmaps) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindTexture(GL_TEXTURE_2D, id); - - // Check if texture is power-of-two (POT) - bool texIsPOT = false; - - if (((width > 0) && ((width & (width - 1)) == 0)) && - ((height > 0) && ((height & (height - 1)) == 0))) texIsPOT = true; - - if ((texIsPOT) || (RLGL.ExtSupported.texNPOT)) - { - //glHint(GL_GENERATE_MIPMAP_HINT, GL_DONT_CARE); // Hint for mipmaps generation algorithm: GL_FASTEST, GL_NICEST, GL_DONT_CARE - glGenerateMipmap(GL_TEXTURE_2D); // Generate mipmaps automatically - - #define MIN(a,b) (((a)<(b))? (a):(b)) - #define MAX(a,b) (((a)>(b))? (a):(b)) - - *mipmaps = 1 + (int)floor(log(MAX(width, height))/log(2)); - TRACELOG(RL_LOG_INFO, "TEXTURE: [ID %i] Mipmaps generated automatically, total: %i", id, *mipmaps); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Failed to generate mipmaps", id); - - glBindTexture(GL_TEXTURE_2D, 0); -#else - TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] GPU mipmap generation not supported", id); -#endif -} - -// Read texture pixel data -void *rlReadTexturePixels(unsigned int id, int width, int height, int format) -{ - void *pixels = NULL; - -#if defined(GRAPHICS_API_OPENGL_11) || defined(GRAPHICS_API_OPENGL_33) - glBindTexture(GL_TEXTURE_2D, id); - - // NOTE: Using texture id, we can retrieve some texture info (but not on OpenGL ES 2.0) - // Possible texture info: GL_TEXTURE_RED_SIZE, GL_TEXTURE_GREEN_SIZE, GL_TEXTURE_BLUE_SIZE, GL_TEXTURE_ALPHA_SIZE - //int width, height, format; - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height); - //glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &format); - - // NOTE: Each row written to or read from by OpenGL pixel operations like glGetTexImage are aligned to a 4 byte boundary by default, which may add some padding - // Use glPixelStorei to modify padding with the GL_[UN]PACK_ALIGNMENT setting - // GL_PACK_ALIGNMENT affects operations that read from OpenGL memory (glReadPixels, glGetTexImage, etc.) - // GL_UNPACK_ALIGNMENT affects operations that write to OpenGL memory (glTexImage, etc.) - glPixelStorei(GL_PACK_ALIGNMENT, 1); - - unsigned int glInternalFormat, glFormat, glType; - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - unsigned int size = rlGetPixelDataSize(width, height, format); - - if ((glInternalFormat != 0) && (format < RL_PIXELFORMAT_COMPRESSED_DXT1_RGB)) - { - pixels = RL_MALLOC(size); - glGetTexImage(GL_TEXTURE_2D, 0, glFormat, glType, pixels); - } - else TRACELOG(RL_LOG_WARNING, "TEXTURE: [ID %i] Data retrieval not suported for pixel format (%i)", id, format); - - glBindTexture(GL_TEXTURE_2D, 0); -#endif - -#if defined(GRAPHICS_API_OPENGL_ES2) - // glGetTexImage() is not available on OpenGL ES 2.0 - // Texture width and height are required on OpenGL ES 2.0, there is no way to get it from texture id - // Two possible Options: - // 1 - Bind texture to color fbo attachment and glReadPixels() - // 2 - Create an fbo, activate it, render quad with texture, glReadPixels() - // We are using Option 1, just need to care for texture format on retrieval - // NOTE: This behaviour could be conditioned by graphic driver... - unsigned int fboId = rlLoadFramebuffer(); - - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - glBindTexture(GL_TEXTURE_2D, 0); - - // Attach our texture to FBO - glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, id, 0); - - // We read data as RGBA because FBO texture is configured as RGBA, despite binding another texture format - pixels = (unsigned char *)RL_MALLOC(rlGetPixelDataSize(width, height, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8)); - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels); - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - // Clean up temporal fbo - rlUnloadFramebuffer(fboId); -#endif - - return pixels; -} - -// Read screen pixel data (color buffer) -unsigned char *rlReadScreenPixels(int width, int height) -{ - unsigned char *screenData = (unsigned char *)RL_CALLOC(width*height*4, sizeof(unsigned char)); - - // NOTE 1: glReadPixels returns image flipped vertically -> (0,0) is the bottom left corner of the framebuffer - // NOTE 2: We are getting alpha channel! Be careful, it can be transparent if not cleared properly! - glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, screenData); - - // Flip image vertically! - unsigned char *imgData = (unsigned char *)RL_MALLOC(width*height*4*sizeof(unsigned char)); - - for (int y = height - 1; y >= 0; y--) - { - for (int x = 0; x < (width*4); x++) - { - imgData[((height - 1) - y)*width*4 + x] = screenData[(y*width*4) + x]; // Flip line - - // Set alpha component value to 255 (no trasparent image retrieval) - // NOTE: Alpha value has already been applied to RGB in framebuffer, we don't need it! - if (((x + 1)%4) == 0) imgData[((height - 1) - y)*width*4 + x] = 255; - } - } - - RL_FREE(screenData); - - return imgData; // NOTE: image data should be freed -} - -// Framebuffer management (fbo) -//----------------------------------------------------------------------------------------- -// Load a framebuffer to be used for rendering -// NOTE: No textures attached -unsigned int rlLoadFramebuffer(void) -{ - unsigned int fboId = 0; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glGenFramebuffers(1, &fboId); // Create the framebuffer object - glBindFramebuffer(GL_FRAMEBUFFER, 0); // Unbind any framebuffer -#endif - - return fboId; -} - -// Attach color buffer texture to an fbo (unloads previous attachment) -// NOTE: Attach type: 0-Color, 1-Depth renderbuffer, 2-Depth texture -void rlFramebufferAttach(unsigned int fboId, unsigned int texId, int attachType, int texType, int mipLevel) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, fboId); - - switch (attachType) - { - case RL_ATTACHMENT_COLOR_CHANNEL0: - case RL_ATTACHMENT_COLOR_CHANNEL1: - case RL_ATTACHMENT_COLOR_CHANNEL2: - case RL_ATTACHMENT_COLOR_CHANNEL3: - case RL_ATTACHMENT_COLOR_CHANNEL4: - case RL_ATTACHMENT_COLOR_CHANNEL5: - case RL_ATTACHMENT_COLOR_CHANNEL6: - case RL_ATTACHMENT_COLOR_CHANNEL7: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_RENDERBUFFER, texId); - else if (texType >= RL_ATTACHMENT_CUBEMAP_POSITIVE_X) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachType, GL_TEXTURE_CUBE_MAP_POSITIVE_X + texType, texId, mipLevel); - - } break; - case RL_ATTACHMENT_DEPTH: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - case RL_ATTACHMENT_STENCIL: - { - if (texType == RL_ATTACHMENT_TEXTURE2D) glFramebufferTexture2D(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_TEXTURE_2D, texId, mipLevel); - else if (texType == RL_ATTACHMENT_RENDERBUFFER) glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, texId); - - } break; - default: break; - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); -#endif -} - -// Verify render texture is complete -bool rlFramebufferComplete(unsigned int id) -{ - bool result = false; - -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - glBindFramebuffer(GL_FRAMEBUFFER, id); - - GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); - - if (status != GL_FRAMEBUFFER_COMPLETE) - { - switch (status) - { - case GL_FRAMEBUFFER_UNSUPPORTED: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer is unsupported", id); break; - case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete attachment", id); break; -#if defined(GRAPHICS_API_OPENGL_ES2) - case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has incomplete dimensions", id); break; -#endif - case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: TRACELOG(RL_LOG_WARNING, "FBO: [ID %i] Framebuffer has a missing attachment", id); break; - default: break; - } - } - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - - result = (status == GL_FRAMEBUFFER_COMPLETE); -#endif - - return result; -} - -// Unload framebuffer from GPU memory -// NOTE: All attached textures/cubemaps/renderbuffers are also deleted -void rlUnloadFramebuffer(unsigned int id) -{ -#if (defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2)) && defined(RLGL_RENDER_TEXTURES_HINT) - // Query depth attachment to automatically delete texture/renderbuffer - int depthType = 0, depthId = 0; - glBindFramebuffer(GL_FRAMEBUFFER, id); // Bind framebuffer to query depth texture type - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &depthType); - - // TODO: Review warning retrieving object name in WebGL - // WARNING: WebGL: INVALID_ENUM: getFramebufferAttachmentParameter: invalid parameter name - // https://registry.khronos.org/webgl/specs/latest/1.0/ - glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &depthId); - - unsigned int depthIdU = (unsigned int)depthId; - if (depthType == GL_RENDERBUFFER) glDeleteRenderbuffers(1, &depthIdU); - else if (depthType == GL_TEXTURE) glDeleteTextures(1, &depthIdU); - - // NOTE: If a texture object is deleted while its image is attached to the *currently bound* framebuffer, - // the texture image is automatically detached from the currently bound framebuffer - - glBindFramebuffer(GL_FRAMEBUFFER, 0); - glDeleteFramebuffers(1, &id); - - TRACELOG(RL_LOG_INFO, "FBO: [ID %i] Unloaded framebuffer from VRAM (GPU)", id); -#endif -} - -// Vertex data management -//----------------------------------------------------------------------------------------- -// Load a new attributes buffer -unsigned int rlLoadVertexBuffer(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferData(GL_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Load a new attributes element buffer -unsigned int rlLoadVertexBufferElement(const void *buffer, int size, bool dynamic) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glGenBuffers(1, &id); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, buffer, dynamic? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); -#endif - - return id; -} - -// Enable vertex buffer (VBO) -void rlEnableVertexBuffer(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer (VBO) -void rlDisableVertexBuffer(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, 0); -#endif -} - -// Enable vertex buffer element (VBO element) -void rlEnableVertexBufferElement(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); -#endif -} - -// Disable vertex buffer element (VBO element) -void rlDisableVertexBufferElement(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -#endif -} - -// Update vertex buffer with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBuffer(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ARRAY_BUFFER, id); - glBufferSubData(GL_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Update vertex buffer elements with new data -// NOTE: dataSize and offset must be provided in bytes -void rlUpdateVertexBufferElements(unsigned int id, const void *data, int dataSize, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, offset, dataSize, data); -#endif -} - -// Enable vertex array object (VAO) -bool rlEnableVertexArray(unsigned int vaoId) -{ - bool result = false; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(vaoId); - result = true; - } -#endif - return result; -} - -// Disable vertex array object (VAO) -void rlDisableVertexArray(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) glBindVertexArray(0); -#endif -} - -// Enable vertex attribute index -void rlEnableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glEnableVertexAttribArray(index); -#endif -} - -// Disable vertex attribute index -void rlDisableVertexAttribute(unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDisableVertexAttribArray(index); -#endif -} - -// Draw vertex array -void rlDrawVertexArray(int offset, int count) -{ - glDrawArrays(GL_TRIANGLES, offset, count); -} - -// Draw vertex array elements -void rlDrawVertexArrayElements(int offset, int count, const void *buffer) -{ - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr); -} - -// Draw vertex array instanced -void rlDrawVertexArrayInstanced(int offset, int count, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDrawArraysInstanced(GL_TRIANGLES, 0, count, instances); -#endif -} - -// Draw vertex array elements instanced -void rlDrawVertexArrayElementsInstanced(int offset, int count, const void *buffer, int instances) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Added pointer math separately from function to avoid UBSAN complaining - unsigned short *bufferPtr = (unsigned short *)buffer; - if (offset > 0) bufferPtr += offset; - - glDrawElementsInstanced(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, (const unsigned short *)bufferPtr, instances); -#endif -} - -#if defined(GRAPHICS_API_OPENGL_11) -// Enable vertex state pointer -void rlEnableStatePointer(int vertexAttribType, void *buffer) -{ - if (buffer != NULL) glEnableClientState(vertexAttribType); - switch (vertexAttribType) - { - case GL_VERTEX_ARRAY: glVertexPointer(3, GL_FLOAT, 0, buffer); break; - case GL_TEXTURE_COORD_ARRAY: glTexCoordPointer(2, GL_FLOAT, 0, buffer); break; - case GL_NORMAL_ARRAY: if (buffer != NULL) glNormalPointer(GL_FLOAT, 0, buffer); break; - case GL_COLOR_ARRAY: if (buffer != NULL) glColorPointer(4, GL_UNSIGNED_BYTE, 0, buffer); break; - //case GL_INDEX_ARRAY: if (buffer != NULL) glIndexPointer(GL_SHORT, 0, buffer); break; // Indexed colors - default: break; - } -} - -// Disable vertex state pointer -void rlDisableStatePointer(int vertexAttribType) -{ - glDisableClientState(vertexAttribType); -} -#endif - -// Load vertex array object (VAO) -unsigned int rlLoadVertexArray(void) -{ - unsigned int vaoId = 0; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glGenVertexArrays(1, &vaoId); - } -#endif - return vaoId; -} - -// Set vertex attribute -void rlSetVertexAttribute(unsigned int index, int compSize, int type, bool normalized, int stride, int offset) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // NOTE: Data type could be: GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_INT, GL_UNSIGNED_INT - // Additional types (depends on OpenGL version or extensions): - // - GL_HALF_FLOAT, GL_FLOAT, GL_DOUBLE, GL_FIXED, - // - GL_INT_2_10_10_10_REV, GL_UNSIGNED_INT_2_10_10_10_REV, GL_UNSIGNED_INT_10F_11F_11F_REV - - size_t offsetNative = offset; - glVertexAttribPointer(index, compSize, type, normalized, stride, (void *)offsetNative); -#endif -} - -// Set vertex attribute divisor -void rlSetVertexAttributeDivisor(unsigned int index, int divisor) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glVertexAttribDivisor(index, divisor); -#endif -} - -// Unload vertex array object (VAO) -void rlUnloadVertexArray(unsigned int vaoId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.ExtSupported.vao) - { - glBindVertexArray(0); - glDeleteVertexArrays(1, &vaoId); - TRACELOG(RL_LOG_INFO, "VAO: [ID %i] Unloaded vertex array data from VRAM (GPU)", vaoId); - } -#endif -} - -// Unload vertex buffer (VBO) -void rlUnloadVertexBuffer(unsigned int vboId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteBuffers(1, &vboId); - //TRACELOG(RL_LOG_INFO, "VBO: Unloaded vertex data from VRAM (GPU)"); -#endif -} - -// Shaders management -//----------------------------------------------------------------------------------------------- -// Load shader from code strings -// NOTE: If shader string is NULL, using default vertex/fragment shaders -unsigned int rlLoadShaderCode(const char *vsCode, const char *fsCode) -{ - unsigned int id = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int vertexShaderId = 0; - unsigned int fragmentShaderId = 0; - - // Compile vertex shader (if provided) - // NOTE: If not vertex shader is provided, use default one - if (vsCode != NULL) vertexShaderId = rlCompileShader(vsCode, GL_VERTEX_SHADER); - else vertexShaderId = RLGL.State.defaultVShaderId; - - // Compile fragment shader (if provided) - // NOTE: If not vertex shader is provided, use default one - if (fsCode != NULL) fragmentShaderId = rlCompileShader(fsCode, GL_FRAGMENT_SHADER); - else fragmentShaderId = RLGL.State.defaultFShaderId; - - // In case vertex and fragment shader are the default ones, no need to recompile, we can just assign the default shader program id - if ((vertexShaderId == RLGL.State.defaultVShaderId) && (fragmentShaderId == RLGL.State.defaultFShaderId)) id = RLGL.State.defaultShaderId; - else if ((vertexShaderId > 0) && (fragmentShaderId > 0)) - { - // One of or both shader are new, we need to compile a new shader program - id = rlLoadShaderProgram(vertexShaderId, fragmentShaderId); - - // We can detach and delete vertex/fragment shaders (if not default ones) - // NOTE: We detach shader before deletion to make sure memory is freed - if (vertexShaderId != RLGL.State.defaultVShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, vertexShaderId); - glDeleteShader(vertexShaderId); - } - if (fragmentShaderId != RLGL.State.defaultFShaderId) - { - // WARNING: Shader program linkage could fail and returned id is 0 - if (id > 0) glDetachShader(id, fragmentShaderId); - glDeleteShader(fragmentShaderId); - } - - // In case shader program loading failed, we assign default shader - if (id == 0) - { - // In case shader loading fails, we return the default shader - TRACELOG(RL_LOG_WARNING, "SHADER: Failed to load custom shader code, using default shader"); - id = RLGL.State.defaultShaderId; - } - /* - else - { - // Get available shader uniforms - // NOTE: This information is useful for debug... - int uniformCount = -1; - glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &uniformCount); - - for (int i = 0; i < uniformCount; i++) - { - int namelen = -1; - int num = -1; - char name[256] = { 0 }; // Assume no variable names longer than 256 - GLenum type = GL_ZERO; - - // Get the name of the uniforms - glGetActiveUniform(id, i, sizeof(name) - 1, &namelen, &num, &type, name); - - name[namelen] = 0; - TRACELOGD("SHADER: [ID %i] Active uniform (%s) set at location: %i", id, name, glGetUniformLocation(id, name)); - } - } - */ - } -#endif - - return id; -} - -// Compile custom shader and return shader id -unsigned int rlCompileShader(const char *shaderCode, int type) -{ - unsigned int shader = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - shader = glCreateShader(type); - glShaderSource(shader, 1, &shaderCode, NULL); - - GLint success = 0; - glCompileShader(shader); - glGetShaderiv(shader, GL_COMPILE_STATUS, &success); - - if (success == GL_FALSE) - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile vertex shader code", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile fragment shader code", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to compile compute shader code", shader); break; - #elif defined(GRAPHICS_API_OPENGL_33) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43", shader); break; - #endif - default: break; - } - - int maxLength = 0; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetShaderInfoLog(shader, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Compile error: %s", shader, log); - RL_FREE(log); - } - - shader = 0; - } - else - { - switch (type) - { - case GL_VERTEX_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Vertex shader compiled successfully", shader); break; - case GL_FRAGMENT_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Fragment shader compiled successfully", shader); break; - //case GL_GEOMETRY_SHADER: - #if defined(GRAPHICS_API_OPENGL_43) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader compiled successfully", shader); break; - #elif defined(GRAPHICS_API_OPENGL_33) - case GL_COMPUTE_SHADER: TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43", shader); break; - #endif - default: break; - } - } -#endif - - return shader; -} - -// Load custom shader strings and return program id -unsigned int rlLoadShaderProgram(unsigned int vShaderId, unsigned int fShaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - GLint success = 0; - program = glCreateProgram(); - - glAttachShader(program, vShaderId); - glAttachShader(program, fShaderId); - - // NOTE: Default attribute shader locations must be Bound before linking - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, RL_DEFAULT_SHADER_ATTRIB_NAME_NORMAL); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_COLOR, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TANGENT, RL_DEFAULT_SHADER_ATTRIB_NAME_TANGENT); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD2, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD2); - -#ifdef RL_SUPPORT_MESH_GPU_SKINNING - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEIDS, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEIDS); - glBindAttribLocation(program, RL_DEFAULT_SHADER_ATTRIB_LOCATION_BONEWEIGHTS, RL_DEFAULT_SHADER_ATTRIB_NAME_BONEWEIGHTS); -#endif - - // NOTE: If some attrib name is no found on the shader, it locations becomes -1 - - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Program shader loaded successfully", program); - } -#endif - return program; -} - -// Unload shader program -void rlUnloadShaderProgram(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - glDeleteProgram(id); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Unloaded shader program data from VRAM (GPU)", id); -#endif -} - -// Get shader location uniform -int rlGetLocationUniform(unsigned int shaderId, const char *uniformName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetUniformLocation(shaderId, uniformName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader uniform: %s", shaderId, uniformName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader uniform (%s) set at location: %i", shaderId, uniformName, location); -#endif - return location; -} - -// Get shader location attribute -int rlGetLocationAttrib(unsigned int shaderId, const char *attribName) -{ - int location = -1; -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - location = glGetAttribLocation(shaderId, attribName); - - //if (location == -1) TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to find shader attribute: %s", shaderId, attribName); - //else TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Shader attribute (%s) set at location: %i", shaderId, attribName, location); -#endif - return location; -} - -// Set shader value uniform -void rlSetUniform(int locIndex, const void *value, int uniformType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (uniformType) - { - case RL_SHADER_UNIFORM_FLOAT: glUniform1fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC2: glUniform2fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC3: glUniform3fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_VEC4: glUniform4fv(locIndex, count, (float *)value); break; - case RL_SHADER_UNIFORM_INT: glUniform1iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC2: glUniform2iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC3: glUniform3iv(locIndex, count, (int *)value); break; - case RL_SHADER_UNIFORM_IVEC4: glUniform4iv(locIndex, count, (int *)value); break; - #if !defined(GRAPHICS_API_OPENGL_ES2) - case RL_SHADER_UNIFORM_UINT: glUniform1uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC2: glUniform2uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC3: glUniform3uiv(locIndex, count, (unsigned int *)value); break; - case RL_SHADER_UNIFORM_UIVEC4: glUniform4uiv(locIndex, count, (unsigned int *)value); break; - #endif - case RL_SHADER_UNIFORM_SAMPLER2D: glUniform1iv(locIndex, count, (int *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set uniform value, data type not recognized"); - - // TODO: Support glUniform1uiv(), glUniform2uiv(), glUniform3uiv(), glUniform4uiv() - } -#endif -} - -// Set shader value attribute -void rlSetVertexAttributeDefault(int locIndex, const void *value, int attribType, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (attribType) - { - case RL_SHADER_ATTRIB_FLOAT: if (count == 1) glVertexAttrib1fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC2: if (count == 2) glVertexAttrib2fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC3: if (count == 3) glVertexAttrib3fv(locIndex, (float *)value); break; - case RL_SHADER_ATTRIB_VEC4: if (count == 4) glVertexAttrib4fv(locIndex, (float *)value); break; - default: TRACELOG(RL_LOG_WARNING, "SHADER: Failed to set attrib default value, data type not recognized"); - } -#endif -} - -// Set shader value uniform matrix -void rlSetUniformMatrix(int locIndex, Matrix mat) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - float matfloat[16] = { - mat.m0, mat.m1, mat.m2, mat.m3, - mat.m4, mat.m5, mat.m6, mat.m7, - mat.m8, mat.m9, mat.m10, mat.m11, - mat.m12, mat.m13, mat.m14, mat.m15 - }; - glUniformMatrix4fv(locIndex, 1, false, matfloat); -#endif -} - -// Set shader value uniform matrix -void rlSetUniformMatrices(int locIndex, const Matrix *matrices, int count) -{ -#if defined(GRAPHICS_API_OPENGL_33) - glUniformMatrix4fv(locIndex, count, true, (const float *)matrices); -#elif defined(GRAPHICS_API_OPENGL_ES2) - // WARNING: WebGL does not support Matrix transpose ("true" parameter) - // REF: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/uniformMatrix - glUniformMatrix4fv(locIndex, count, false, (const float *)matrices); -#endif -} - -// Set shader value uniform sampler -void rlSetUniformSampler(int locIndex, unsigned int textureId) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // Check if texture is already active - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] == textureId) - { - glUniform1i(locIndex, 1 + i); - return; - } - } - - // Register a new active texture for the internal batch system - // NOTE: Default texture is always activated as GL_TEXTURE0 - for (int i = 0; i < RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS; i++) - { - if (RLGL.State.activeTextureId[i] == 0) - { - glUniform1i(locIndex, 1 + i); // Activate new texture unit - RLGL.State.activeTextureId[i] = textureId; // Save texture id for binding on drawing - break; - } - } -#endif -} - -// Set shader currently active (id and locations) -void rlSetShader(unsigned int id, int *locs) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (RLGL.State.currentShaderId != id) - { - rlDrawRenderBatch(RLGL.currentBatch); - RLGL.State.currentShaderId = id; - RLGL.State.currentShaderLocs = locs; - } -#endif -} - -// Load compute shader program -unsigned int rlLoadComputeShaderProgram(unsigned int shaderId) -{ - unsigned int program = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - GLint success = 0; - program = glCreateProgram(); - glAttachShader(program, shaderId); - glLinkProgram(program); - - // NOTE: All uniform variables are intitialised to 0 when a program links - - glGetProgramiv(program, GL_LINK_STATUS, &success); - - if (success == GL_FALSE) - { - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to link compute shader program", program); - - int maxLength = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &maxLength); - - if (maxLength > 0) - { - int length = 0; - char *log = (char *)RL_CALLOC(maxLength, sizeof(char)); - glGetProgramInfoLog(program, maxLength, &length, log); - TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Link error: %s", program, log); - RL_FREE(log); - } - - glDeleteProgram(program); - - program = 0; - } - else - { - // Get the size of compiled shader program (not available on OpenGL ES 2.0) - // NOTE: If GL_LINK_STATUS is GL_FALSE, program binary length is zero - //GLint binarySize = 0; - //glGetProgramiv(id, GL_PROGRAM_BINARY_LENGTH, &binarySize); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Compute shader program loaded successfully", program); - } -#else - TRACELOG(RL_LOG_WARNING, "SHADER: Compute shaders not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - - return program; -} - -// Dispatch compute shader (equivalent to *draw* for graphics pilepine) -void rlComputeShaderDispatch(unsigned int groupX, unsigned int groupY, unsigned int groupZ) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDispatchCompute(groupX, groupY, groupZ); -#endif -} - -// Load shader storage buffer object (SSBO) -unsigned int rlLoadShaderBuffer(unsigned int size, const void *data, int usageHint) -{ - unsigned int ssbo = 0; - -#if defined(GRAPHICS_API_OPENGL_43) - glGenBuffers(1, &ssbo); - glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo); - glBufferData(GL_SHADER_STORAGE_BUFFER, size, data, usageHint? usageHint : RL_STREAM_COPY); - if (data == NULL) glClearBufferData(GL_SHADER_STORAGE_BUFFER, GL_R8UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, NULL); // Clear buffer data to 0 - glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0); -#else - TRACELOG(RL_LOG_WARNING, "SSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - - return ssbo; -} - -// Unload shader storage buffer object (SSBO) -void rlUnloadShaderBuffer(unsigned int ssboId) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glDeleteBuffers(1, &ssboId); -#else - TRACELOG(RL_LOG_WARNING, "SSBO: SSBO not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif - -} - -// Update SSBO buffer data -void rlUpdateShaderBuffer(unsigned int id, const void *data, unsigned int dataSize, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, dataSize, data); -#endif -} - -// Get SSBO buffer size -unsigned int rlGetShaderBufferSize(unsigned int id) -{ -#if defined(GRAPHICS_API_OPENGL_43) - GLint64 size = 0; - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetBufferParameteri64v(GL_SHADER_STORAGE_BUFFER, GL_BUFFER_SIZE, &size); - return (size > 0)? (unsigned int)size : 0; -#else - return 0; -#endif -} - -// Read SSBO buffer data (GPU->CPU) -void rlReadShaderBuffer(unsigned int id, void *dest, unsigned int count, unsigned int offset) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_SHADER_STORAGE_BUFFER, id); - glGetBufferSubData(GL_SHADER_STORAGE_BUFFER, offset, count, dest); -#endif -} - -// Bind SSBO buffer -void rlBindShaderBuffer(unsigned int id, unsigned int index) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBufferBase(GL_SHADER_STORAGE_BUFFER, index, id); -#endif -} - -// Copy SSBO buffer data -void rlCopyShaderBuffer(unsigned int destId, unsigned int srcId, unsigned int destOffset, unsigned int srcOffset, unsigned int count) -{ -#if defined(GRAPHICS_API_OPENGL_43) - glBindBuffer(GL_COPY_READ_BUFFER, srcId); - glBindBuffer(GL_COPY_WRITE_BUFFER, destId); - glCopyBufferSubData(GL_COPY_READ_BUFFER, GL_COPY_WRITE_BUFFER, srcOffset, destOffset, count); -#endif -} - -// Bind image texture -void rlBindImageTexture(unsigned int id, unsigned int index, int format, bool readonly) -{ -#if defined(GRAPHICS_API_OPENGL_43) - unsigned int glInternalFormat = 0, glFormat = 0, glType = 0; - - rlGetGlTextureFormats(format, &glInternalFormat, &glFormat, &glType); - glBindImageTexture(index, id, 0, 0, 0, readonly? GL_READ_ONLY : GL_READ_WRITE, glInternalFormat); -#else - TRACELOG(RL_LOG_WARNING, "TEXTURE: Image texture binding not enabled. Define GRAPHICS_API_OPENGL_43"); -#endif -} - -// Matrix state management -//----------------------------------------------------------------------------------------- -// Get internal modelview matrix -Matrix rlGetMatrixModelview(void) -{ - Matrix matrix = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_MODELVIEW_MATRIX, mat); - matrix.m0 = mat[0]; - matrix.m1 = mat[1]; - matrix.m2 = mat[2]; - matrix.m3 = mat[3]; - matrix.m4 = mat[4]; - matrix.m5 = mat[5]; - matrix.m6 = mat[6]; - matrix.m7 = mat[7]; - matrix.m8 = mat[8]; - matrix.m9 = mat[9]; - matrix.m10 = mat[10]; - matrix.m11 = mat[11]; - matrix.m12 = mat[12]; - matrix.m13 = mat[13]; - matrix.m14 = mat[14]; - matrix.m15 = mat[15]; -#else - matrix = RLGL.State.modelview; -#endif - return matrix; -} - -// Get internal projection matrix -Matrix rlGetMatrixProjection(void) -{ -#if defined(GRAPHICS_API_OPENGL_11) - float mat[16]; - glGetFloatv(GL_PROJECTION_MATRIX,mat); - Matrix m; - m.m0 = mat[0]; - m.m1 = mat[1]; - m.m2 = mat[2]; - m.m3 = mat[3]; - m.m4 = mat[4]; - m.m5 = mat[5]; - m.m6 = mat[6]; - m.m7 = mat[7]; - m.m8 = mat[8]; - m.m9 = mat[9]; - m.m10 = mat[10]; - m.m11 = mat[11]; - m.m12 = mat[12]; - m.m13 = mat[13]; - m.m14 = mat[14]; - m.m15 = mat[15]; - return m; -#else - return RLGL.State.projection; -#endif -} - -// Get internal accumulated transform matrix -Matrix rlGetMatrixTransform(void) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - // TODO: Consider possible transform matrices in the RLGL.State.stack - // Is this the right order? or should we start with the first stored matrix instead of the last one? - //Matrix matStackTransform = rlMatrixIdentity(); - //for (int i = RLGL.State.stackCounter; i > 0; i--) matStackTransform = rlMatrixMultiply(RLGL.State.stack[i], matStackTransform); - mat = RLGL.State.transform; -#endif - return mat; -} - -// Get internal projection matrix for stereo render (selected eye) -Matrix rlGetMatrixProjectionStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.projectionStereo[eye]; -#endif - return mat; -} - -// Get internal view offset matrix for stereo render (selected eye) -Matrix rlGetMatrixViewOffsetStereo(int eye) -{ - Matrix mat = rlMatrixIdentity(); -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - mat = RLGL.State.viewOffsetStereo[eye]; -#endif - return mat; -} - -// Set a custom modelview matrix (replaces internal modelview matrix) -void rlSetMatrixModelview(Matrix view) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.modelview = view; -#endif -} - -// Set a custom projection matrix (replaces internal projection matrix) -void rlSetMatrixProjection(Matrix projection) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projection = projection; -#endif -} - -// Set eyes projection matrices for stereo rendering -void rlSetMatrixProjectionStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.projectionStereo[0] = right; - RLGL.State.projectionStereo[1] = left; -#endif -} - -// Set eyes view offsets matrices for stereo rendering -void rlSetMatrixViewOffsetStereo(Matrix right, Matrix left) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - RLGL.State.viewOffsetStereo[0] = right; - RLGL.State.viewOffsetStereo[1] = left; -#endif -} - -// Load and draw a quad in NDC -void rlLoadDrawQuad(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int quadVAO = 0; - unsigned int quadVBO = 0; - - float vertices[] = { - // Positions Texcoords - -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, - 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &quadVAO); - glBindVertexArray(quadVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &quadVBO); - glBindBuffer(GL_ARRAY_BUFFER, quadVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), &vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, texcoords) - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 5*sizeof(float), (void *)(3*sizeof(float))); // Texcoords - - // Draw quad - glBindVertexArray(quadVAO); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - glBindVertexArray(0); - - // Delete buffers (VBO and VAO) - glDeleteBuffers(1, &quadVBO); - glDeleteVertexArrays(1, &quadVAO); -#endif -} - -// Load and draw a cube in NDC -void rlLoadDrawCube(void) -{ -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - unsigned int cubeVAO = 0; - unsigned int cubeVBO = 0; - - float vertices[] = { - // Positions Normals Texcoords - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - -1.0f, -1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, 1.0f, 1.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, -1.0f, 1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, - -1.0f, -1.0f, -1.0f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - 1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, - 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, - -1.0f, 1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, - -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f - }; - - // Gen VAO to contain VBO - glGenVertexArrays(1, &cubeVAO); - glBindVertexArray(cubeVAO); - - // Gen and fill vertex buffer (VBO) - glGenBuffers(1, &cubeVBO); - glBindBuffer(GL_ARRAY_BUFFER, cubeVBO); - glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); - - // Bind vertex attributes (position, normals, texcoords) - glBindVertexArray(cubeVAO); - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_POSITION, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)0); // Positions - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_NORMAL, 3, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(3*sizeof(float))); // Normals - glEnableVertexAttribArray(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD); - glVertexAttribPointer(RL_DEFAULT_SHADER_ATTRIB_LOCATION_TEXCOORD, 2, GL_FLOAT, GL_FALSE, 8*sizeof(float), (void *)(6*sizeof(float))); // Texcoords - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindVertexArray(0); - - // Draw cube - glBindVertexArray(cubeVAO); - glDrawArrays(GL_TRIANGLES, 0, 36); - glBindVertexArray(0); - - // Delete VBO and VAO - glDeleteBuffers(1, &cubeVBO); - glDeleteVertexArrays(1, &cubeVAO); -#endif -} - -// Get name string for pixel format -const char *rlGetPixelFormatName(unsigned int format) -{ - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: return "GRAYSCALE"; break; // 8 bit per pixel (no alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: return "GRAY_ALPHA"; break; // 8*2 bpp (2 channels) - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: return "R5G6B5"; break; // 16 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: return "R8G8B8"; break; // 24 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: return "R5G5B5A1"; break; // 16 bpp (1 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: return "R4G4B4A4"; break; // 16 bpp (4 bit alpha) - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: return "R8G8B8A8"; break; // 32 bpp - case RL_PIXELFORMAT_UNCOMPRESSED_R32: return "R32"; break; // 32 bpp (1 channel - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: return "R32G32B32"; break; // 32*3 bpp (3 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: return "R32G32B32A32"; break; // 32*4 bpp (4 channels - float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16: return "R16"; break; // 16 bpp (1 channel - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: return "R16G16B16"; break; // 16*3 bpp (3 channels - half float) - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: return "R16G16B16A16"; break; // 16*4 bpp (4 channels - half float) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: return "DXT1_RGB"; break; // 4 bpp (no alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: return "DXT1_RGBA"; break; // 4 bpp (1 bit alpha) - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: return "DXT3_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: return "DXT5_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: return "ETC1_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: return "ETC2_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: return "ETC2_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: return "PVRT_RGB"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: return "PVRT_RGBA"; break; // 4 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: return "ASTC_4x4_RGBA"; break; // 8 bpp - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: return "ASTC_8x8_RGBA"; break; // 2 bpp - default: return "UNKNOWN"; break; - } -} - -//---------------------------------------------------------------------------------- -// Module specific Functions Definition -//---------------------------------------------------------------------------------- -#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -// Load default shader (just vertex positioning and texture coloring) -// NOTE: This shader program is used for internal buffers -// NOTE: Loaded: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlLoadShaderDefault(void) -{ - RLGL.State.defaultShaderLocs = (int *)RL_CALLOC(RL_MAX_SHADER_LOCATIONS, sizeof(int)); - - // NOTE: All locations must be reseted to -1 (no location) - for (int i = 0; i < RL_MAX_SHADER_LOCATIONS; i++) RLGL.State.defaultShaderLocs[i] = -1; - - // Vertex shader directly defined, no external file required - const char *defaultVShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - "#version 300 es \n" - "precision mediump float; \n" // Precision required for OpenGL ES3 (WebGL 2) (on some browsers) - "in vec3 vertexPosition; \n" - "in vec2 vertexTexCoord; \n" - "in vec4 vertexColor; \n" - "out vec2 fragTexCoord; \n" - "out vec4 fragColor; \n" -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) (on some browsers) - "attribute vec3 vertexPosition; \n" - "attribute vec2 vertexTexCoord; \n" - "attribute vec4 vertexColor; \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" -#endif - - "uniform mat4 mvp; \n" - "void main() \n" - "{ \n" - " fragTexCoord = vertexTexCoord; \n" - " fragColor = vertexColor; \n" - " gl_Position = mvp*vec4(vertexPosition, 1.0); \n" - "} \n"; - - // Fragment shader directly defined, no external file required - const char *defaultFShaderCode = -#if defined(GRAPHICS_API_OPENGL_21) - "#version 120 \n" - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#elif defined(GRAPHICS_API_OPENGL_33) - "#version 330 \n" - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif - -#if defined(GRAPHICS_API_OPENGL_ES3) - "#version 300 es \n" - "precision mediump float; \n" // Precision required for OpenGL ES3 (WebGL 2) - "in vec2 fragTexCoord; \n" - "in vec4 fragColor; \n" - "out vec4 finalColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture(texture0, fragTexCoord); \n" - " finalColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#elif defined(GRAPHICS_API_OPENGL_ES2) - "#version 100 \n" - "precision mediump float; \n" // Precision required for OpenGL ES2 (WebGL) - "varying vec2 fragTexCoord; \n" - "varying vec4 fragColor; \n" - "uniform sampler2D texture0; \n" - "uniform vec4 colDiffuse; \n" - "void main() \n" - "{ \n" - " vec4 texelColor = texture2D(texture0, fragTexCoord); \n" - " gl_FragColor = texelColor*colDiffuse*fragColor; \n" - "} \n"; -#endif - - // NOTE: Compiled vertex/fragment shaders are not deleted, - // they are kept for re-use as default shaders in case some shader loading fails - RLGL.State.defaultVShaderId = rlCompileShader(defaultVShaderCode, GL_VERTEX_SHADER); // Compile default vertex shader - RLGL.State.defaultFShaderId = rlCompileShader(defaultFShaderCode, GL_FRAGMENT_SHADER); // Compile default fragment shader - - RLGL.State.defaultShaderId = rlLoadShaderProgram(RLGL.State.defaultVShaderId, RLGL.State.defaultFShaderId); - - if (RLGL.State.defaultShaderId > 0) - { - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader loaded successfully", RLGL.State.defaultShaderId); - - // Set default shader locations: attributes locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_POSITION] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_POSITION); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_TEXCOORD01] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_TEXCOORD); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_VERTEX_COLOR] = glGetAttribLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_ATTRIB_NAME_COLOR); - - // Set default shader locations: uniform locations - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MATRIX_MVP] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_MVP); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_COLOR_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_UNIFORM_NAME_COLOR); - RLGL.State.defaultShaderLocs[RL_SHADER_LOC_MAP_DIFFUSE] = glGetUniformLocation(RLGL.State.defaultShaderId, RL_DEFAULT_SHADER_SAMPLER2D_NAME_TEXTURE0); - } - else TRACELOG(RL_LOG_WARNING, "SHADER: [ID %i] Failed to load default shader", RLGL.State.defaultShaderId); -} - -// Unload default shader -// NOTE: Unloads: RLGL.State.defaultShaderId, RLGL.State.defaultShaderLocs -static void rlUnloadShaderDefault(void) -{ - glUseProgram(0); - - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultVShaderId); - glDetachShader(RLGL.State.defaultShaderId, RLGL.State.defaultFShaderId); - glDeleteShader(RLGL.State.defaultVShaderId); - glDeleteShader(RLGL.State.defaultFShaderId); - - glDeleteProgram(RLGL.State.defaultShaderId); - - RL_FREE(RLGL.State.defaultShaderLocs); - - TRACELOG(RL_LOG_INFO, "SHADER: [ID %i] Default shader unloaded successfully", RLGL.State.defaultShaderId); -} - -#if defined(RLGL_SHOW_GL_DETAILS_INFO) -// Get compressed format official GL identifier name -static const char *rlGetCompressedFormatName(int format) -{ - switch (format) - { - // GL_EXT_texture_compression_s3tc - case 0x83F0: return "GL_COMPRESSED_RGB_S3TC_DXT1_EXT"; break; - case 0x83F1: return "GL_COMPRESSED_RGBA_S3TC_DXT1_EXT"; break; - case 0x83F2: return "GL_COMPRESSED_RGBA_S3TC_DXT3_EXT"; break; - case 0x83F3: return "GL_COMPRESSED_RGBA_S3TC_DXT5_EXT"; break; - // GL_3DFX_texture_compression_FXT1 - case 0x86B0: return "GL_COMPRESSED_RGB_FXT1_3DFX"; break; - case 0x86B1: return "GL_COMPRESSED_RGBA_FXT1_3DFX"; break; - // GL_IMG_texture_compression_pvrtc - case 0x8C00: return "GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG"; break; - case 0x8C01: return "GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG"; break; - case 0x8C02: return "GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"; break; - case 0x8C03: return "GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"; break; - // GL_OES_compressed_ETC1_RGB8_texture - case 0x8D64: return "GL_ETC1_RGB8_OES"; break; - // GL_ARB_texture_compression_rgtc - case 0x8DBB: return "GL_COMPRESSED_RED_RGTC1"; break; - case 0x8DBC: return "GL_COMPRESSED_SIGNED_RED_RGTC1"; break; - case 0x8DBD: return "GL_COMPRESSED_RG_RGTC2"; break; - case 0x8DBE: return "GL_COMPRESSED_SIGNED_RG_RGTC2"; break; - // GL_ARB_texture_compression_bptc - case 0x8E8C: return "GL_COMPRESSED_RGBA_BPTC_UNORM_ARB"; break; - case 0x8E8D: return "GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB"; break; - case 0x8E8E: return "GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB"; break; - case 0x8E8F: return "GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB"; break; - // GL_ARB_ES3_compatibility - case 0x9274: return "GL_COMPRESSED_RGB8_ETC2"; break; - case 0x9275: return "GL_COMPRESSED_SRGB8_ETC2"; break; - case 0x9276: return "GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9277: return "GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"; break; - case 0x9278: return "GL_COMPRESSED_RGBA8_ETC2_EAC"; break; - case 0x9279: return "GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"; break; - case 0x9270: return "GL_COMPRESSED_R11_EAC"; break; - case 0x9271: return "GL_COMPRESSED_SIGNED_R11_EAC"; break; - case 0x9272: return "GL_COMPRESSED_RG11_EAC"; break; - case 0x9273: return "GL_COMPRESSED_SIGNED_RG11_EAC"; break; - // GL_KHR_texture_compression_astc_hdr - case 0x93B0: return "GL_COMPRESSED_RGBA_ASTC_4x4_KHR"; break; - case 0x93B1: return "GL_COMPRESSED_RGBA_ASTC_5x4_KHR"; break; - case 0x93B2: return "GL_COMPRESSED_RGBA_ASTC_5x5_KHR"; break; - case 0x93B3: return "GL_COMPRESSED_RGBA_ASTC_6x5_KHR"; break; - case 0x93B4: return "GL_COMPRESSED_RGBA_ASTC_6x6_KHR"; break; - case 0x93B5: return "GL_COMPRESSED_RGBA_ASTC_8x5_KHR"; break; - case 0x93B6: return "GL_COMPRESSED_RGBA_ASTC_8x6_KHR"; break; - case 0x93B7: return "GL_COMPRESSED_RGBA_ASTC_8x8_KHR"; break; - case 0x93B8: return "GL_COMPRESSED_RGBA_ASTC_10x5_KHR"; break; - case 0x93B9: return "GL_COMPRESSED_RGBA_ASTC_10x6_KHR"; break; - case 0x93BA: return "GL_COMPRESSED_RGBA_ASTC_10x8_KHR"; break; - case 0x93BB: return "GL_COMPRESSED_RGBA_ASTC_10x10_KHR"; break; - case 0x93BC: return "GL_COMPRESSED_RGBA_ASTC_12x10_KHR"; break; - case 0x93BD: return "GL_COMPRESSED_RGBA_ASTC_12x12_KHR"; break; - case 0x93D0: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR"; break; - case 0x93D1: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR"; break; - case 0x93D2: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR"; break; - case 0x93D3: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR"; break; - case 0x93D4: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR"; break; - case 0x93D5: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR"; break; - case 0x93D6: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR"; break; - case 0x93D7: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR"; break; - case 0x93D8: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR"; break; - case 0x93D9: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR"; break; - case 0x93DA: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR"; break; - case 0x93DB: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR"; break; - case 0x93DC: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR"; break; - case 0x93DD: return "GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR"; break; - default: return "GL_COMPRESSED_UNKNOWN"; break; - } -} -#endif // RLGL_SHOW_GL_DETAILS_INFO - -#endif // GRAPHICS_API_OPENGL_33 || GRAPHICS_API_OPENGL_ES2 - -// Get pixel data size in bytes (image or texture) -// NOTE: Size depends on pixel format -static int rlGetPixelDataSize(int width, int height, int format) -{ - int dataSize = 0; // Size in bytes - int bpp = 0; // Bits per pixel - - switch (format) - { - case RL_PIXELFORMAT_UNCOMPRESSED_GRAYSCALE: bpp = 8; break; - case RL_PIXELFORMAT_UNCOMPRESSED_GRAY_ALPHA: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G6B5: - case RL_PIXELFORMAT_UNCOMPRESSED_R5G5B5A1: - case RL_PIXELFORMAT_UNCOMPRESSED_R4G4B4A4: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8: bpp = 24; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32: bpp = 32; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32: bpp = 32*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R32G32B32A32: bpp = 32*4; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16: bpp = 16; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16: bpp = 16*3; break; - case RL_PIXELFORMAT_UNCOMPRESSED_R16G16B16A16: bpp = 16*4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGB: - case RL_PIXELFORMAT_COMPRESSED_DXT1_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC1_RGB: - case RL_PIXELFORMAT_COMPRESSED_ETC2_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGB: - case RL_PIXELFORMAT_COMPRESSED_PVRT_RGBA: bpp = 4; break; - case RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA: - case RL_PIXELFORMAT_COMPRESSED_DXT5_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ETC2_EAC_RGBA: - case RL_PIXELFORMAT_COMPRESSED_ASTC_4x4_RGBA: bpp = 8; break; - case RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA: bpp = 2; break; - default: break; - } - - double bytesPerPixel = (double)bpp/8.0; - dataSize = (int)(bytesPerPixel*width*height); // Total data size in bytes - - // Most compressed formats works on 4x4 blocks, - // if texture is smaller, minimum dataSize is 8 or 16 - if ((width < 4) && (height < 4)) - { - if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT1_RGB) && (format < RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA)) dataSize = 8; - else if ((format >= RL_PIXELFORMAT_COMPRESSED_DXT3_RGBA) && (format < RL_PIXELFORMAT_COMPRESSED_ASTC_8x8_RGBA)) dataSize = 16; - } - - return dataSize; -} - -// Auxiliar math functions - -// Get float array of matrix data -static rl_float16 rlMatrixToFloatV(Matrix mat) -{ - rl_float16 result = { 0 }; - - result.v[0] = mat.m0; - result.v[1] = mat.m1; - result.v[2] = mat.m2; - result.v[3] = mat.m3; - result.v[4] = mat.m4; - result.v[5] = mat.m5; - result.v[6] = mat.m6; - result.v[7] = mat.m7; - result.v[8] = mat.m8; - result.v[9] = mat.m9; - result.v[10] = mat.m10; - result.v[11] = mat.m11; - result.v[12] = mat.m12; - result.v[13] = mat.m13; - result.v[14] = mat.m14; - result.v[15] = mat.m15; - - return result; -} - -// Get identity matrix -static Matrix rlMatrixIdentity(void) -{ - Matrix result = { - 1.0f, 0.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, 0.0f, - 0.0f, 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 0.0f, 1.0f - }; - - return result; -} - -// Get two matrix multiplication -// NOTE: When multiplying matrices... the order matters! -static Matrix rlMatrixMultiply(Matrix left, Matrix right) -{ - Matrix result = { 0 }; - - result.m0 = left.m0*right.m0 + left.m1*right.m4 + left.m2*right.m8 + left.m3*right.m12; - result.m1 = left.m0*right.m1 + left.m1*right.m5 + left.m2*right.m9 + left.m3*right.m13; - result.m2 = left.m0*right.m2 + left.m1*right.m6 + left.m2*right.m10 + left.m3*right.m14; - result.m3 = left.m0*right.m3 + left.m1*right.m7 + left.m2*right.m11 + left.m3*right.m15; - result.m4 = left.m4*right.m0 + left.m5*right.m4 + left.m6*right.m8 + left.m7*right.m12; - result.m5 = left.m4*right.m1 + left.m5*right.m5 + left.m6*right.m9 + left.m7*right.m13; - result.m6 = left.m4*right.m2 + left.m5*right.m6 + left.m6*right.m10 + left.m7*right.m14; - result.m7 = left.m4*right.m3 + left.m5*right.m7 + left.m6*right.m11 + left.m7*right.m15; - result.m8 = left.m8*right.m0 + left.m9*right.m4 + left.m10*right.m8 + left.m11*right.m12; - result.m9 = left.m8*right.m1 + left.m9*right.m5 + left.m10*right.m9 + left.m11*right.m13; - result.m10 = left.m8*right.m2 + left.m9*right.m6 + left.m10*right.m10 + left.m11*right.m14; - result.m11 = left.m8*right.m3 + left.m9*right.m7 + left.m10*right.m11 + left.m11*right.m15; - result.m12 = left.m12*right.m0 + left.m13*right.m4 + left.m14*right.m8 + left.m15*right.m12; - result.m13 = left.m12*right.m1 + left.m13*right.m5 + left.m14*right.m9 + left.m15*right.m13; - result.m14 = left.m12*right.m2 + left.m13*right.m6 + left.m14*right.m10 + left.m15*right.m14; - result.m15 = left.m12*right.m3 + left.m13*right.m7 + left.m14*right.m11 + left.m15*right.m15; - - return result; -} - -// Transposes provided matrix -static Matrix rlMatrixTranspose(Matrix mat) -{ - Matrix result = { 0 }; - - result.m0 = mat.m0; - result.m1 = mat.m4; - result.m2 = mat.m8; - result.m3 = mat.m12; - result.m4 = mat.m1; - result.m5 = mat.m5; - result.m6 = mat.m9; - result.m7 = mat.m13; - result.m8 = mat.m2; - result.m9 = mat.m6; - result.m10 = mat.m10; - result.m11 = mat.m14; - result.m12 = mat.m3; - result.m13 = mat.m7; - result.m14 = mat.m11; - result.m15 = mat.m15; - - return result; -} - -// Invert provided matrix -static Matrix rlMatrixInvert(Matrix mat) -{ - Matrix result = { 0 }; - - // Cache the matrix values (speed optimization) - float a00 = mat.m0, a01 = mat.m1, a02 = mat.m2, a03 = mat.m3; - float a10 = mat.m4, a11 = mat.m5, a12 = mat.m6, a13 = mat.m7; - float a20 = mat.m8, a21 = mat.m9, a22 = mat.m10, a23 = mat.m11; - float a30 = mat.m12, a31 = mat.m13, a32 = mat.m14, a33 = mat.m15; - - float b00 = a00*a11 - a01*a10; - float b01 = a00*a12 - a02*a10; - float b02 = a00*a13 - a03*a10; - float b03 = a01*a12 - a02*a11; - float b04 = a01*a13 - a03*a11; - float b05 = a02*a13 - a03*a12; - float b06 = a20*a31 - a21*a30; - float b07 = a20*a32 - a22*a30; - float b08 = a20*a33 - a23*a30; - float b09 = a21*a32 - a22*a31; - float b10 = a21*a33 - a23*a31; - float b11 = a22*a33 - a23*a32; - - // Calculate the invert determinant (inlined to avoid double-caching) - float invDet = 1.0f/(b00*b11 - b01*b10 + b02*b09 + b03*b08 - b04*b07 + b05*b06); - - result.m0 = (a11*b11 - a12*b10 + a13*b09)*invDet; - result.m1 = (-a01*b11 + a02*b10 - a03*b09)*invDet; - result.m2 = (a31*b05 - a32*b04 + a33*b03)*invDet; - result.m3 = (-a21*b05 + a22*b04 - a23*b03)*invDet; - result.m4 = (-a10*b11 + a12*b08 - a13*b07)*invDet; - result.m5 = (a00*b11 - a02*b08 + a03*b07)*invDet; - result.m6 = (-a30*b05 + a32*b02 - a33*b01)*invDet; - result.m7 = (a20*b05 - a22*b02 + a23*b01)*invDet; - result.m8 = (a10*b10 - a11*b08 + a13*b06)*invDet; - result.m9 = (-a00*b10 + a01*b08 - a03*b06)*invDet; - result.m10 = (a30*b04 - a31*b02 + a33*b00)*invDet; - result.m11 = (-a20*b04 + a21*b02 - a23*b00)*invDet; - result.m12 = (-a10*b09 + a11*b07 - a12*b06)*invDet; - result.m13 = (a00*b09 - a01*b07 + a02*b06)*invDet; - result.m14 = (-a30*b03 + a31*b01 - a32*b00)*invDet; - result.m15 = (a20*b03 - a21*b01 + a22*b00)*invDet; - - return result; -} - -#endif // RLGL_IMPLEMENTATION diff --git a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.a b/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.a deleted file mode 100644 index 6e2d85c..0000000 Binary files a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.a and /dev/null differ diff --git a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so b/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so deleted file mode 120000 index 6686f51..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so +++ /dev/null @@ -1 +0,0 @@ -libraylib.so.550 \ No newline at end of file diff --git a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.5.5.0 b/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.5.5.0 deleted file mode 100755 index 0771502..0000000 Binary files a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.5.5.0 and /dev/null differ diff --git a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.550 b/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.550 deleted file mode 120000 index 1366041..0000000 --- a/examples/raylib/raylib-5.5_linux_amd64/lib/libraylib.so.550 +++ /dev/null @@ -1 +0,0 @@ -libraylib.so.5.5.0 \ No newline at end of file diff --git a/vscode-lsp/.gitignore b/vscode-lsp/.gitignore deleted file mode 100644 index 0512d1c..0000000 --- a/vscode-lsp/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -node_modules -out -nub-*.vsix -server \ No newline at end of file diff --git a/vscode-lsp/.vscode/launch.json b/vscode-lsp/.vscode/launch.json deleted file mode 100644 index f308c75..0000000 --- a/vscode-lsp/.vscode/launch.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Run Extension", - "type": "extensionHost", - "request": "launch", - "args": [ - "--extensionDevelopmentPath=${workspaceFolder}" - ], - "outFiles": [ - "${workspaceFolder}/out/**/*.js" - ], - "preLaunchTask": "${defaultBuildTask}" - } - ] -} \ No newline at end of file diff --git a/vscode-lsp/.vscode/settings.json b/vscode-lsp/.vscode/settings.json deleted file mode 100644 index e35b3d4..0000000 --- a/vscode-lsp/.vscode/settings.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "files.exclude": {}, - "search.exclude": { - "out": true, - "node_modules": true, - }, - "typescript.tsc.autoDetect": "off" -} \ No newline at end of file diff --git a/vscode-lsp/.vscode/tasks.json b/vscode-lsp/.vscode/tasks.json deleted file mode 100644 index 2f61468..0000000 --- a/vscode-lsp/.vscode/tasks.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - "version": "2.0.0", - "tasks": [ - { - "type": "npm", - "script": "watch", - "problemMatcher": "$tsc-watch", - "isBackground": true, - "presentation": { - "reveal": "never" - }, - "group": { - "kind": "build", - "isDefault": true - } - } - ] -} \ No newline at end of file diff --git a/vscode-lsp/language-configuration.json b/vscode-lsp/language-configuration.json deleted file mode 100644 index 3c18fac..0000000 --- a/vscode-lsp/language-configuration.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "comments": { - "lineComment": { - "comment": "//" - }, - "blockComment": [ - "/*", - "*/" - ] - }, - "brackets": [ - [ - "{", - "}" - ], - [ - "[", - "]" - ], - [ - "(", - ")" - ] - ], - "autoClosingPairs": [ - { - "open": "{", - "close": "}" - }, - { - "open": "[", - "close": "]" - }, - { - "open": "(", - "close": ")" - }, - { - "open": "\"", - "close": "\"" - }, - { - "open": "'", - "close": "'" - } - ], - "surroundingPairs": [ - [ - "{", - "}" - ], - [ - "[", - "]" - ], - [ - "(", - ")" - ], - [ - "\"", - "\"" - ], - [ - "'", - "'" - ] - ] -} \ No newline at end of file diff --git a/vscode-lsp/package-lock.json b/vscode-lsp/package-lock.json deleted file mode 100644 index b86ad24..0000000 --- a/vscode-lsp/package-lock.json +++ /dev/null @@ -1,4811 +0,0 @@ -{ - "name": "nub", - "version": "0.0.1", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "nub", - "version": "0.0.1", - "dependencies": { - "vscode-languageclient": "^9.0.1" - }, - "devDependencies": { - "@types/node": "22.x", - "@types/vscode": "^1.105.0", - "@vscode/vsce": "^3.6.2", - "esbuild": "^0.25.11", - "typescript": "^5.9.3" - }, - "engines": { - "vscode": "^1.105.0" - } - }, - "node_modules/@azu/format-text": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@azu/format-text/-/format-text-1.0.2.tgz", - "integrity": "sha512-Swi4N7Edy1Eqq82GxgEECXSSLyn6GOb5htRFPzBDdUkECGXtlf12ynO5oJSpWKPwCaUssOu7NfhDcCWpIC6Ywg==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/@azu/style-format": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/@azu/style-format/-/style-format-1.0.1.tgz", - "integrity": "sha512-AHcTojlNBdD/3/KxIKlg8sxIWHfOtQszLvOpagLTO+bjC3u7SAszu1lf//u7JJC50aUSH+BVWDD/KvaA6Gfn5g==", - "dev": true, - "license": "WTFPL", - "dependencies": { - "@azu/format-text": "^1.0.1" - } - }, - "node_modules/@azure/abort-controller": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/@azure/abort-controller/-/abort-controller-2.1.2.tgz", - "integrity": "sha512-nBrLsEWm4J2u5LpAPjxADTlq3trDgVZZXHNKabeXZtpq3d3AbN/KGO82R87rdDz5/lYB024rtEf10/q0urNgsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@azure/core-auth": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@azure/core-auth/-/core-auth-1.10.1.tgz", - "integrity": "sha512-ykRMW8PjVAn+RS6ww5cmK9U2CyH9p4Q88YJwvUslfuMmN98w/2rdGRLPqJYObapBCdzBVeDgYWdJnFPFb7qzpg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/abort-controller": "^2.1.2", - "@azure/core-util": "^1.13.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/core-client": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@azure/core-client/-/core-client-1.10.1.tgz", - "integrity": "sha512-Nh5PhEOeY6PrnxNPsEHRr9eimxLwgLlpmguQaHKBinFYA/RU9+kOYVOQqOrTsCL+KSxrLLl1gD8Dk5BFW/7l/w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/abort-controller": "^2.1.2", - "@azure/core-auth": "^1.10.0", - "@azure/core-rest-pipeline": "^1.22.0", - "@azure/core-tracing": "^1.3.0", - "@azure/core-util": "^1.13.0", - "@azure/logger": "^1.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/core-rest-pipeline": { - "version": "1.22.1", - "resolved": "https://registry.npmjs.org/@azure/core-rest-pipeline/-/core-rest-pipeline-1.22.1.tgz", - "integrity": "sha512-UVZlVLfLyz6g3Hy7GNDpooMQonUygH7ghdiSASOOHy97fKj/mPLqgDX7aidOijn+sCMU+WU8NjlPlNTgnvbcGA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/abort-controller": "^2.1.2", - "@azure/core-auth": "^1.10.0", - "@azure/core-tracing": "^1.3.0", - "@azure/core-util": "^1.13.0", - "@azure/logger": "^1.3.0", - "@typespec/ts-http-runtime": "^0.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/core-tracing": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@azure/core-tracing/-/core-tracing-1.3.1.tgz", - "integrity": "sha512-9MWKevR7Hz8kNzzPLfX4EAtGM2b8mr50HPDBvio96bURP/9C+HjdH3sBlLSNNrvRAr5/k/svoH457gB5IKpmwQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/core-util": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/@azure/core-util/-/core-util-1.13.1.tgz", - "integrity": "sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/abort-controller": "^2.1.2", - "@typespec/ts-http-runtime": "^0.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/identity": { - "version": "4.13.0", - "resolved": "https://registry.npmjs.org/@azure/identity/-/identity-4.13.0.tgz", - "integrity": "sha512-uWC0fssc+hs1TGGVkkghiaFkkS7NkTxfnCH+Hdg+yTehTpMcehpok4PgUKKdyCH+9ldu6FhiHRv84Ntqj1vVcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/abort-controller": "^2.0.0", - "@azure/core-auth": "^1.9.0", - "@azure/core-client": "^1.9.2", - "@azure/core-rest-pipeline": "^1.17.0", - "@azure/core-tracing": "^1.0.0", - "@azure/core-util": "^1.11.0", - "@azure/logger": "^1.0.0", - "@azure/msal-browser": "^4.2.0", - "@azure/msal-node": "^3.5.0", - "open": "^10.1.0", - "tslib": "^2.2.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/logger": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@azure/logger/-/logger-1.3.0.tgz", - "integrity": "sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@typespec/ts-http-runtime": "^0.3.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@azure/msal-browser": { - "version": "4.25.1", - "resolved": "https://registry.npmjs.org/@azure/msal-browser/-/msal-browser-4.25.1.tgz", - "integrity": "sha512-kAdOSNjvMbeBmEyd5WnddGmIpKCbAAGj4Gg/1iURtF+nHmIfS0+QUBBO3uaHl7CBB2R1SEAbpOgxycEwrHOkFA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/msal-common": "15.13.0" - }, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@azure/msal-common": { - "version": "15.13.0", - "resolved": "https://registry.npmjs.org/@azure/msal-common/-/msal-common-15.13.0.tgz", - "integrity": "sha512-8oF6nj02qX7eE/6+wFT5NluXRHc05AgdCC3fJnkjiJooq8u7BcLmxaYYSwc2AfEkWRMRi6Eyvvbeqk4U4412Ag==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@azure/msal-node": { - "version": "3.8.0", - "resolved": "https://registry.npmjs.org/@azure/msal-node/-/msal-node-3.8.0.tgz", - "integrity": "sha512-23BXm82Mp5XnRhrcd4mrHa0xuUNRp96ivu3nRatrfdAqjoeWAGyD0eEAafxAOHAEWWmdlyFK4ELFcdziXyw2sA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/msal-common": "15.13.0", - "jsonwebtoken": "^9.0.0", - "uuid": "^8.3.0" - }, - "engines": { - "node": ">=16" - } - }, - "node_modules/@babel/code-frame": { - "version": "7.27.1", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", - "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-validator-identifier": "^7.27.1", - "js-tokens": "^4.0.0", - "picocolors": "^1.1.1" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/helper-validator-identifier": { - "version": "7.28.5", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", - "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@esbuild/aix-ppc64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.11.tgz", - "integrity": "sha512-Xt1dOL13m8u0WE8iplx9Ibbm+hFAO0GsU2P34UNoDGvZYkY8ifSiy6Zuc1lYxfG7svWE2fzqCUmFp5HCn51gJg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "aix" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.11.tgz", - "integrity": "sha512-uoa7dU+Dt3HYsethkJ1k6Z9YdcHjTrSb5NUy66ZfZaSV8hEYGD5ZHbEMXnqLFlbBflLsl89Zke7CAdDJ4JI+Gg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.11.tgz", - "integrity": "sha512-9slpyFBc4FPPz48+f6jyiXOx/Y4v34TUeDDXJpZqAWQn/08lKGeD8aDp9TMn9jDz2CiEuHwfhRmGBvpnd/PWIQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/android-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.11.tgz", - "integrity": "sha512-Sgiab4xBjPU1QoPEIqS3Xx+R2lezu0LKIEcYe6pftr56PqPygbB7+szVnzoShbx64MUupqoE0KyRlN7gezbl8g==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.11.tgz", - "integrity": "sha512-VekY0PBCukppoQrycFxUqkCojnTQhdec0vevUL/EDOCnXd9LKWqD/bHwMPzigIJXPhC59Vd1WFIL57SKs2mg4w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/darwin-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.11.tgz", - "integrity": "sha512-+hfp3yfBalNEpTGp9loYgbknjR695HkqtY3d3/JjSRUyPg/xd6q+mQqIb5qdywnDxRZykIHs3axEqU6l1+oWEQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.11.tgz", - "integrity": "sha512-CmKjrnayyTJF2eVuO//uSjl/K3KsMIeYeyN7FyDBjsR3lnSJHaXlVoAK8DZa7lXWChbuOk7NjAc7ygAwrnPBhA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/freebsd-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.11.tgz", - "integrity": "sha512-Dyq+5oscTJvMaYPvW3x3FLpi2+gSZTCE/1ffdwuM6G1ARang/mb3jvjxs0mw6n3Lsw84ocfo9CrNMqc5lTfGOw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.11.tgz", - "integrity": "sha512-TBMv6B4kCfrGJ8cUPo7vd6NECZH/8hPpBHHlYI3qzoYFvWu2AdTvZNuU/7hsbKWqu/COU7NIK12dHAAqBLLXgw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.11.tgz", - "integrity": "sha512-Qr8AzcplUhGvdyUF08A1kHU3Vr2O88xxP0Tm8GcdVOUm25XYcMPp2YqSVHbLuXzYQMf9Bh/iKx7YPqECs6ffLA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ia32": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.11.tgz", - "integrity": "sha512-TmnJg8BMGPehs5JKrCLqyWTVAvielc615jbkOirATQvWWB1NMXY77oLMzsUjRLa0+ngecEmDGqt5jiDC6bfvOw==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-loong64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.11.tgz", - "integrity": "sha512-DIGXL2+gvDaXlaq8xruNXUJdT5tF+SBbJQKbWy/0J7OhU8gOHOzKmGIlfTTl6nHaCOoipxQbuJi7O++ldrxgMw==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-mips64el": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.11.tgz", - "integrity": "sha512-Osx1nALUJu4pU43o9OyjSCXokFkFbyzjXb6VhGIJZQ5JZi8ylCQ9/LFagolPsHtgw6himDSyb5ETSfmp4rpiKQ==", - "cpu": [ - "mips64el" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-ppc64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.11.tgz", - "integrity": "sha512-nbLFgsQQEsBa8XSgSTSlrnBSrpoWh7ioFDUmwo158gIm5NNP+17IYmNWzaIzWmgCxq56vfr34xGkOcZ7jX6CPw==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-riscv64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.11.tgz", - "integrity": "sha512-HfyAmqZi9uBAbgKYP1yGuI7tSREXwIb438q0nqvlpxAOs3XnZ8RsisRfmVsgV486NdjD7Mw2UrFSw51lzUk1ww==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-s390x": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.11.tgz", - "integrity": "sha512-HjLqVgSSYnVXRisyfmzsH6mXqyvj0SA7pG5g+9W7ESgwA70AXYNpfKBqh1KbTxmQVaYxpzA/SvlB9oclGPbApw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/linux-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.11.tgz", - "integrity": "sha512-HSFAT4+WYjIhrHxKBwGmOOSpphjYkcswF449j6EjsjbinTZbp8PJtjsVK1XFJStdzXdy/jaddAep2FGY+wyFAQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.11.tgz", - "integrity": "sha512-hr9Oxj1Fa4r04dNpWr3P8QKVVsjQhqrMSUzZzf+LZcYjZNqhA3IAfPQdEh1FLVUJSiu6sgAwp3OmwBfbFgG2Xg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/netbsd-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.11.tgz", - "integrity": "sha512-u7tKA+qbzBydyj0vgpu+5h5AeudxOAGncb8N6C9Kh1N4n7wU1Xw1JDApsRjpShRpXRQlJLb9wY28ELpwdPcZ7A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "netbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.11.tgz", - "integrity": "sha512-Qq6YHhayieor3DxFOoYM1q0q1uMFYb7cSpLD2qzDSvK1NAvqFi8Xgivv0cFC6J+hWVw2teCYltyy9/m/14ryHg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openbsd-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.11.tgz", - "integrity": "sha512-CN+7c++kkbrckTOz5hrehxWN7uIhFFlmS/hqziSFVWpAzpWrQoAG4chH+nN3Be+Kzv/uuo7zhX716x3Sn2Jduw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openbsd" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/openharmony-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.11.tgz", - "integrity": "sha512-rOREuNIQgaiR+9QuNkbkxubbp8MSO9rONmwP5nKncnWJ9v5jQ4JxFnLu4zDSRPf3x4u+2VN4pM4RdyIzDty/wQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/sunos-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.11.tgz", - "integrity": "sha512-nq2xdYaWxyg9DcIyXkZhcYulC6pQ2FuCgem3LI92IwMgIZ69KHeY8T4Y88pcwoLIjbed8n36CyKoYRDygNSGhA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "sunos" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-arm64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.11.tgz", - "integrity": "sha512-3XxECOWJq1qMZ3MN8srCJ/QfoLpL+VaxD/WfNRm1O3B4+AZ/BnLVgFbUV3eiRYDMXetciH16dwPbbHqwe1uU0Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-ia32": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.11.tgz", - "integrity": "sha512-3ukss6gb9XZ8TlRyJlgLn17ecsK4NSQTmdIXRASVsiS2sQ6zPPZklNJT5GR5tE/MUarymmy8kCEf5xPCNCqVOA==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@esbuild/win32-x64": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.11.tgz", - "integrity": "sha512-D7Hpz6A2L4hzsRpPaCYkQnGOotdUpDzSGRIv9I+1ITdHROSFUWW95ZPZWQmGka1Fg7W3zFJowyn9WGwMJ0+KPA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">=18" - } - }, - "node_modules/@isaacs/balanced-match": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/@isaacs/balanced-match/-/balanced-match-4.0.1.tgz", - "integrity": "sha512-yzMTt9lEb8Gv7zRioUilSglI0c0smZ9k5D65677DLWLtWJaXIS3CqcGyUFByYKlnUj6TkjLVs54fBl6+TiGQDQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@isaacs/brace-expansion": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/@isaacs/brace-expansion/-/brace-expansion-5.0.0.tgz", - "integrity": "sha512-ZT55BDLV0yv0RBm2czMiZ+SqCGO7AvmOM3G/w2xhVPH+te0aKgFjmBvGlL1dH+ql2tgGO3MVrbb3jCKyvpgnxA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@isaacs/balanced-match": "^4.0.1" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@isaacs/cliui": { - "version": "8.0.2", - "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz", - "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==", - "dev": true, - "license": "ISC", - "dependencies": { - "string-width": "^5.1.2", - "string-width-cjs": "npm:string-width@^4.2.0", - "strip-ansi": "^7.0.1", - "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", - "wrap-ansi": "^8.1.0", - "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" - }, - "engines": { - "node": ">=12" - } - }, - "node_modules/@isaacs/cliui/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@isaacs/cliui/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@nodelib/fs.scandir": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", - "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "2.0.5", - "run-parallel": "^1.1.9" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.stat": { - "version": "2.0.5", - "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", - "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/@nodelib/fs.walk": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", - "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.scandir": "2.1.5", - "fastq": "^1.6.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/@secretlint/config-creator": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/config-creator/-/config-creator-10.2.2.tgz", - "integrity": "sha512-BynOBe7Hn3LJjb3CqCHZjeNB09s/vgf0baBaHVw67w7gHF0d25c3ZsZ5+vv8TgwSchRdUCRrbbcq5i2B1fJ2QQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/types": "^10.2.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/config-loader": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/config-loader/-/config-loader-10.2.2.tgz", - "integrity": "sha512-ndjjQNgLg4DIcMJp4iaRD6xb9ijWQZVbd9694Ol2IszBIbGPPkwZHzJYKICbTBmh6AH/pLr0CiCaWdGJU7RbpQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/profiler": "^10.2.2", - "@secretlint/resolver": "^10.2.2", - "@secretlint/types": "^10.2.2", - "ajv": "^8.17.1", - "debug": "^4.4.1", - "rc-config-loader": "^4.1.3" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/core": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/core/-/core-10.2.2.tgz", - "integrity": "sha512-6rdwBwLP9+TO3rRjMVW1tX+lQeo5gBbxl1I5F8nh8bgGtKwdlCMhMKsBWzWg1ostxx/tIG7OjZI0/BxsP8bUgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/profiler": "^10.2.2", - "@secretlint/types": "^10.2.2", - "debug": "^4.4.1", - "structured-source": "^4.0.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/formatter": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/formatter/-/formatter-10.2.2.tgz", - "integrity": "sha512-10f/eKV+8YdGKNQmoDUD1QnYL7TzhI2kzyx95vsJKbEa8akzLAR5ZrWIZ3LbcMmBLzxlSQMMccRmi05yDQ5YDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/resolver": "^10.2.2", - "@secretlint/types": "^10.2.2", - "@textlint/linter-formatter": "^15.2.0", - "@textlint/module-interop": "^15.2.0", - "@textlint/types": "^15.2.0", - "chalk": "^5.4.1", - "debug": "^4.4.1", - "pluralize": "^8.0.0", - "strip-ansi": "^7.1.0", - "table": "^6.9.0", - "terminal-link": "^4.0.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/formatter/node_modules/chalk": { - "version": "5.6.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", - "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^12.17.0 || ^14.13 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/@secretlint/node": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/node/-/node-10.2.2.tgz", - "integrity": "sha512-eZGJQgcg/3WRBwX1bRnss7RmHHK/YlP/l7zOQsrjexYt6l+JJa5YhUmHbuGXS94yW0++3YkEJp0kQGYhiw1DMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/config-loader": "^10.2.2", - "@secretlint/core": "^10.2.2", - "@secretlint/formatter": "^10.2.2", - "@secretlint/profiler": "^10.2.2", - "@secretlint/source-creator": "^10.2.2", - "@secretlint/types": "^10.2.2", - "debug": "^4.4.1", - "p-map": "^7.0.3" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/profiler": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/profiler/-/profiler-10.2.2.tgz", - "integrity": "sha512-qm9rWfkh/o8OvzMIfY8a5bCmgIniSpltbVlUVl983zDG1bUuQNd1/5lUEeWx5o/WJ99bXxS7yNI4/KIXfHexig==", - "dev": true, - "license": "MIT" - }, - "node_modules/@secretlint/resolver": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/resolver/-/resolver-10.2.2.tgz", - "integrity": "sha512-3md0cp12e+Ae5V+crPQYGd6aaO7ahw95s28OlULGyclyyUtf861UoRGS2prnUrKh7MZb23kdDOyGCYb9br5e4w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@secretlint/secretlint-formatter-sarif": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/secretlint-formatter-sarif/-/secretlint-formatter-sarif-10.2.2.tgz", - "integrity": "sha512-ojiF9TGRKJJw308DnYBucHxkpNovDNu1XvPh7IfUp0A12gzTtxuWDqdpuVezL7/IP8Ua7mp5/VkDMN9OLp1doQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "node-sarif-builder": "^3.2.0" - } - }, - "node_modules/@secretlint/secretlint-rule-no-dotenv": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/secretlint-rule-no-dotenv/-/secretlint-rule-no-dotenv-10.2.2.tgz", - "integrity": "sha512-KJRbIShA9DVc5Va3yArtJ6QDzGjg3PRa1uYp9As4RsyKtKSSZjI64jVca57FZ8gbuk4em0/0Jq+uy6485wxIdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/types": "^10.2.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/secretlint-rule-preset-recommend": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/secretlint-rule-preset-recommend/-/secretlint-rule-preset-recommend-10.2.2.tgz", - "integrity": "sha512-K3jPqjva8bQndDKJqctnGfwuAxU2n9XNCPtbXVI5JvC7FnQiNg/yWlQPbMUlBXtBoBGFYp08A94m6fvtc9v+zA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/source-creator": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/source-creator/-/source-creator-10.2.2.tgz", - "integrity": "sha512-h6I87xJfwfUTgQ7irWq7UTdq/Bm1RuQ/fYhA3dtTIAop5BwSFmZyrchph4WcoEvbN460BWKmk4RYSvPElIIvxw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/types": "^10.2.2", - "istextorbinary": "^9.5.0" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@secretlint/types": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/@secretlint/types/-/types-10.2.2.tgz", - "integrity": "sha512-Nqc90v4lWCXyakD6xNyNACBJNJ0tNCwj2WNk/7ivyacYHxiITVgmLUFXTBOeCdy79iz6HtN9Y31uw/jbLrdOAg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@sindresorhus/merge-streams": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/@sindresorhus/merge-streams/-/merge-streams-2.3.0.tgz", - "integrity": "sha512-LtoMMhxAlorcGhmFYI+LhPgbPZCkgP6ra1YL604EeF6U98pLlQ3iWIGMdWSC+vWmPBWBNgmDBAhnAobLROJmwg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/@textlint/ast-node-types": { - "version": "15.2.3", - "resolved": "https://registry.npmjs.org/@textlint/ast-node-types/-/ast-node-types-15.2.3.tgz", - "integrity": "sha512-GEhoxfmh6TF+xC8TJmAUwOzzh0J6sVDqjKhwTTwetf7YDdhHbIv1PuUb/dTadMVIWs1H0+JD4Y27n6LWMmqn9Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@textlint/linter-formatter": { - "version": "15.2.3", - "resolved": "https://registry.npmjs.org/@textlint/linter-formatter/-/linter-formatter-15.2.3.tgz", - "integrity": "sha512-gnFGl8MejAS4rRDPKV2OYvU0Tb0iJySOPDahf+RCK30b615UqY6CjqWxXw1FvXfT3pHPoRrefVu39j1AKm2ezg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azu/format-text": "^1.0.2", - "@azu/style-format": "^1.0.1", - "@textlint/module-interop": "15.2.3", - "@textlint/resolver": "15.2.3", - "@textlint/types": "15.2.3", - "chalk": "^4.1.2", - "debug": "^4.4.3", - "js-yaml": "^3.14.1", - "lodash": "^4.17.21", - "pluralize": "^2.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "table": "^6.9.0", - "text-table": "^0.2.0" - } - }, - "node_modules/@textlint/linter-formatter/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@textlint/linter-formatter/node_modules/pluralize": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-2.0.0.tgz", - "integrity": "sha512-TqNZzQCD4S42De9IfnnBvILN7HAW7riLqsCyp8lgjXeysyPlX5HhqKAcJHHHb9XskE4/a+7VGC9zzx8Ls0jOAw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@textlint/linter-formatter/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@textlint/module-interop": { - "version": "15.2.3", - "resolved": "https://registry.npmjs.org/@textlint/module-interop/-/module-interop-15.2.3.tgz", - "integrity": "sha512-dV6M3ptOFJjR5bgYUMeVqc8AqFrMtCEFaZEiLAfMufX29asYonI2K8arqivOA69S2Lh6esyij6V7qpQiXeK/cA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@textlint/resolver": { - "version": "15.2.3", - "resolved": "https://registry.npmjs.org/@textlint/resolver/-/resolver-15.2.3.tgz", - "integrity": "sha512-Qd3udqo2sWa3u0sYgDVd9M/iybBVBJLrWGaID6Yzl9GyhdGi0E6ngo3b9r+H6psbJDIaCKi54IxvC9q5didWfA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@textlint/types": { - "version": "15.2.3", - "resolved": "https://registry.npmjs.org/@textlint/types/-/types-15.2.3.tgz", - "integrity": "sha512-i8XVmDHJwykMXcGgkSxZLjdbeqnl+voYAcIr94KIe0STwgkHIhwHJgb/tEVFawGClHo+gPczF12l1C5+TAZEzQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@textlint/ast-node-types": "15.2.3" - } - }, - "node_modules/@types/node": { - "version": "22.18.12", - "resolved": "https://registry.npmjs.org/@types/node/-/node-22.18.12.tgz", - "integrity": "sha512-BICHQ67iqxQGFSzfCFTT7MRQ5XcBjG5aeKh5Ok38UBbPe5fxTyE+aHFxwVrGyr8GNlqFMLKD1D3P2K/1ks8tog==", - "dev": true, - "license": "MIT", - "dependencies": { - "undici-types": "~6.21.0" - } - }, - "node_modules/@types/normalize-package-data": { - "version": "2.4.4", - "resolved": "https://registry.npmjs.org/@types/normalize-package-data/-/normalize-package-data-2.4.4.tgz", - "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/sarif": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/@types/sarif/-/sarif-2.1.7.tgz", - "integrity": "sha512-kRz0VEkJqWLf1LLVN4pT1cg1Z9wAuvI6L97V3m2f5B76Tg8d413ddvLBPTEHAZJlnn4XSvu0FkZtViCQGVyrXQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/vscode": { - "version": "1.105.0", - "resolved": "https://registry.npmjs.org/@types/vscode/-/vscode-1.105.0.tgz", - "integrity": "sha512-Lotk3CTFlGZN8ray4VxJE7axIyLZZETQJVWi/lYoUVQuqfRxlQhVOfoejsD2V3dVXPSbS15ov5ZyowMAzgUqcw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@typespec/ts-http-runtime": { - "version": "0.3.1", - "resolved": "https://registry.npmjs.org/@typespec/ts-http-runtime/-/ts-http-runtime-0.3.1.tgz", - "integrity": "sha512-SnbaqayTVFEA6/tYumdF0UmybY0KHyKwGPBXnyckFlrrKdhWFrL3a2HIPXHjht5ZOElKGcXfD2D63P36btb+ww==", - "dev": true, - "license": "MIT", - "dependencies": { - "http-proxy-agent": "^7.0.0", - "https-proxy-agent": "^7.0.0", - "tslib": "^2.6.2" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/@vscode/vsce": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/@vscode/vsce/-/vsce-3.6.2.tgz", - "integrity": "sha512-gvBfarWF+Ii20ESqjA3dpnPJpQJ8fFJYtcWtjwbRADommCzGg1emtmb34E+DKKhECYvaVyAl+TF9lWS/3GSPvg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@azure/identity": "^4.1.0", - "@secretlint/node": "^10.1.2", - "@secretlint/secretlint-formatter-sarif": "^10.1.2", - "@secretlint/secretlint-rule-no-dotenv": "^10.1.2", - "@secretlint/secretlint-rule-preset-recommend": "^10.1.2", - "@vscode/vsce-sign": "^2.0.0", - "azure-devops-node-api": "^12.5.0", - "chalk": "^4.1.2", - "cheerio": "^1.0.0-rc.9", - "cockatiel": "^3.1.2", - "commander": "^12.1.0", - "form-data": "^4.0.0", - "glob": "^11.0.0", - "hosted-git-info": "^4.0.2", - "jsonc-parser": "^3.2.0", - "leven": "^3.1.0", - "markdown-it": "^14.1.0", - "mime": "^1.3.4", - "minimatch": "^3.0.3", - "parse-semver": "^1.1.1", - "read": "^1.0.7", - "secretlint": "^10.1.2", - "semver": "^7.5.2", - "tmp": "^0.2.3", - "typed-rest-client": "^1.8.4", - "url-join": "^4.0.1", - "xml2js": "^0.5.0", - "yauzl": "^2.3.1", - "yazl": "^2.2.2" - }, - "bin": { - "vsce": "vsce" - }, - "engines": { - "node": ">= 20" - }, - "optionalDependencies": { - "keytar": "^7.7.0" - } - }, - "node_modules/@vscode/vsce-sign": { - "version": "2.0.8", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign/-/vsce-sign-2.0.8.tgz", - "integrity": "sha512-H7p8E11cZMj6mt8xIi3QXZ7dSU/2MH3Y7c+5JfUhHAV4xfaPNc8ozwLVK282c6ah596KoIJIdPUlNHV7Qs/5JA==", - "dev": true, - "hasInstallScript": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optionalDependencies": { - "@vscode/vsce-sign-alpine-arm64": "2.0.6", - "@vscode/vsce-sign-alpine-x64": "2.0.6", - "@vscode/vsce-sign-darwin-arm64": "2.0.2", - "@vscode/vsce-sign-darwin-x64": "2.0.2", - "@vscode/vsce-sign-linux-arm": "2.0.6", - "@vscode/vsce-sign-linux-arm64": "2.0.6", - "@vscode/vsce-sign-linux-x64": "2.0.6", - "@vscode/vsce-sign-win32-arm64": "2.0.6", - "@vscode/vsce-sign-win32-x64": "2.0.6" - } - }, - "node_modules/@vscode/vsce-sign-alpine-arm64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-alpine-arm64/-/vsce-sign-alpine-arm64-2.0.6.tgz", - "integrity": "sha512-wKkJBsvKF+f0GfsUuGT0tSW0kZL87QggEiqNqK6/8hvqsXvpx8OsTEc3mnE1kejkh5r+qUyQ7PtF8jZYN0mo8Q==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "alpine" - ] - }, - "node_modules/@vscode/vsce-sign-alpine-x64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-alpine-x64/-/vsce-sign-alpine-x64-2.0.6.tgz", - "integrity": "sha512-YoAGlmdK39vKi9jA18i4ufBbd95OqGJxRvF3n6ZbCyziwy3O+JgOpIUPxv5tjeO6gQfx29qBivQ8ZZTUF2Ba0w==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "alpine" - ] - }, - "node_modules/@vscode/vsce-sign-darwin-arm64": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-darwin-arm64/-/vsce-sign-darwin-arm64-2.0.2.tgz", - "integrity": "sha512-rz8F4pMcxPj8fjKAJIfkUT8ycG9CjIp888VY/6pq6cuI2qEzQ0+b5p3xb74CJnBbSC0p2eRVoe+WgNCAxCLtzQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@vscode/vsce-sign-darwin-x64": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-darwin-x64/-/vsce-sign-darwin-x64-2.0.2.tgz", - "integrity": "sha512-MCjPrQ5MY/QVoZ6n0D92jcRb7eYvxAujG/AH2yM6lI0BspvJQxp0o9s5oiAM9r32r9tkLpiy5s2icsbwefAQIw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@vscode/vsce-sign-linux-arm": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-arm/-/vsce-sign-linux-arm-2.0.6.tgz", - "integrity": "sha512-UndEc2Xlq4HsuMPnwu7420uqceXjs4yb5W8E2/UkaHBB9OWCwMd3/bRe/1eLe3D8kPpxzcaeTyXiK3RdzS/1CA==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@vscode/vsce-sign-linux-arm64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-arm64/-/vsce-sign-linux-arm64-2.0.6.tgz", - "integrity": "sha512-cfb1qK7lygtMa4NUl2582nP7aliLYuDEVpAbXJMkDq1qE+olIw/es+C8j1LJwvcRq1I2yWGtSn3EkDp9Dq5FdA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@vscode/vsce-sign-linux-x64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-linux-x64/-/vsce-sign-linux-x64-2.0.6.tgz", - "integrity": "sha512-/olerl1A4sOqdP+hjvJ1sbQjKN07Y3DVnxO4gnbn/ahtQvFrdhUi0G1VsZXDNjfqmXw57DmPi5ASnj/8PGZhAA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@vscode/vsce-sign-win32-arm64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-win32-arm64/-/vsce-sign-win32-arm64-2.0.6.tgz", - "integrity": "sha512-ivM/MiGIY0PJNZBoGtlRBM/xDpwbdlCWomUWuLmIxbi1Cxe/1nooYrEQoaHD8ojVRgzdQEUzMsRbyF5cJJgYOg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@vscode/vsce-sign-win32-x64": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@vscode/vsce-sign-win32-x64/-/vsce-sign-win32-x64-2.0.6.tgz", - "integrity": "sha512-mgth9Kvze+u8CruYMmhHw6Zgy3GRX2S+Ed5oSokDEK5vPEwGGKnmuXua9tmFhomeAnhgJnL4DCna3TiNuGrBTQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "SEE LICENSE IN LICENSE.txt", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/ajv": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz", - "integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==", - "dev": true, - "license": "MIT", - "dependencies": { - "fast-deep-equal": "^3.1.3", - "fast-uri": "^3.0.1", - "json-schema-traverse": "^1.0.0", - "require-from-string": "^2.0.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/epoberezkin" - } - }, - "node_modules/ansi-escapes": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.1.1.tgz", - "integrity": "sha512-Zhl0ErHcSRUaVfGUeUdDuLgpkEo8KIFjB4Y9uAc46ScOpdDiU1Dbyplh7qWJeJ/ZHpbyMSM26+X3BySgnIz40Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "environment": "^1.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/ansi-regex": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", - "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-regex?sponsor=1" - } - }, - "node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, - "node_modules/astral-regex": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", - "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/azure-devops-node-api": { - "version": "12.5.0", - "resolved": "https://registry.npmjs.org/azure-devops-node-api/-/azure-devops-node-api-12.5.0.tgz", - "integrity": "sha512-R5eFskGvOm3U/GzeAuxRkUsAl0hrAwGgWn6zAd2KrZmrEhWZVqLew4OOupbQlXUuojUzpGtq62SmdhJ06N88og==", - "dev": true, - "license": "MIT", - "dependencies": { - "tunnel": "0.0.6", - "typed-rest-client": "^1.8.4" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT" - }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true - }, - "node_modules/binaryextensions": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/binaryextensions/-/binaryextensions-6.11.0.tgz", - "integrity": "sha512-sXnYK/Ij80TO3lcqZVV2YgfKN5QjUWIRk/XSm2J/4bd/lPko3lvk0O4ZppH6m+6hB2/GTu+ptNwVFe1xh+QLQw==", - "dev": true, - "license": "Artistic-2.0", - "dependencies": { - "editions": "^6.21.0" - }, - "engines": { - "node": ">=4" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", - "dev": true, - "license": "ISC" - }, - "node_modules/boundary": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/boundary/-/boundary-2.0.0.tgz", - "integrity": "sha512-rJKn5ooC9u8q13IMCrW0RSp31pxBCHE3y9V/tp3TdWSLf8Em3p6Di4NBpfzbJge9YjjFEsD0RtFEjtvHL5VyEA==", - "dev": true, - "license": "BSD-2-Clause" - }, - "node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "node_modules/braces": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", - "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", - "dev": true, - "license": "MIT", - "dependencies": { - "fill-range": "^7.1.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/buffer-crc32": { - "version": "0.2.13", - "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", - "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/buffer-equal-constant-time": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", - "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/bundle-name": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz", - "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "run-applescript": "^7.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/call-bind-apply-helpers": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", - "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/call-bound": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", - "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "get-intrinsic": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/chalk": { - "version": "4.1.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", - "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/chalk?sponsor=1" - } - }, - "node_modules/cheerio": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.1.2.tgz", - "integrity": "sha512-IkxPpb5rS/d1IiLbHMgfPuS0FgiWTtFIm/Nj+2woXDLTZ7fOT2eqzgYbdMlLweqlHbsZjxEChoVK+7iph7jyQg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.2.2", - "encoding-sniffer": "^0.2.1", - "htmlparser2": "^10.0.0", - "parse5": "^7.3.0", - "parse5-htmlparser2-tree-adapter": "^7.1.0", - "parse5-parser-stream": "^7.1.2", - "undici": "^7.12.0", - "whatwg-mimetype": "^4.0.0" - }, - "engines": { - "node": ">=20.18.1" - }, - "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" - } - }, - "node_modules/cheerio-select": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", - "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "dev": true, - "license": "ISC", - "optional": true - }, - "node_modules/cockatiel": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/cockatiel/-/cockatiel-3.2.1.tgz", - "integrity": "sha512-gfrHV6ZPkquExvMh9IOkKsBzNDk6sDuZ6DdBGUBkvFnTCqCxzpuq48RySgP0AnaqQkw2zynOFj9yly6T1Q2G5Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=16" - } - }, - "node_modules/color-convert": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", - "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "color-name": "~1.1.4" - }, - "engines": { - "node": ">=7.0.0" - } - }, - "node_modules/color-name": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", - "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", - "dev": true, - "license": "MIT" - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/css-select": { - "version": "5.2.2", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.2.2.tgz", - "integrity": "sha512-TizTzUddG/xYLA3NXodFM0fSbNizXjOKhqiQQwvhlspadZokn1KDy0NZFS0wuEubIYAV5/c1/lAr0TaaFXEXzw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0", - "css-what": "^6.1.0", - "domhandler": "^5.0.2", - "domutils": "^3.0.1", - "nth-check": "^2.0.1" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/css-what": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.2.2.tgz", - "integrity": "sha512-u/O3vwbptzhMs3L1fQE82ZSLHQQfto5gyZzwteVIEyeaY5Fc7R4dapF/BvRoSYFeqfBk4m0V1Vafq5Pjv25wvA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/default-browser": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.2.1.tgz", - "integrity": "sha512-WY/3TUME0x3KPYdRRxEJJvXRHV4PyPoUsxtZa78lwItwRQRHhd2U9xOscaT/YTf8uCXIAjeJOFBVEh/7FtD8Xg==", - "dev": true, - "license": "MIT", - "dependencies": { - "bundle-name": "^4.1.0", - "default-browser-id": "^5.0.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/default-browser-id": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.0.tgz", - "integrity": "sha512-A6p/pu/6fyBcA1TRz/GqWYPViplrftcW2gZC9q79ngNCKAeR/X3gcEdXQHl4KNXV+3wgIJ1CPkJQ3IHM6lcsyA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/define-lazy-prop": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-3.0.0.tgz", - "integrity": "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/dom-serializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", - "dev": true, - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "entities": "^4.2.0" - }, - "funding": { - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" - } - }, - "node_modules/domelementtype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "BSD-2-Clause" - }, - "node_modules/domhandler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "domelementtype": "^2.3.0" - }, - "engines": { - "node": ">= 4" - }, - "funding": { - "url": "https://github.com/fb55/domhandler?sponsor=1" - } - }, - "node_modules/domutils": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", - "integrity": "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "dom-serializer": "^2.0.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3" - }, - "funding": { - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/dunder-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", - "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "es-errors": "^1.3.0", - "gopd": "^1.2.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/eastasianwidth": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz", - "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==", - "dev": true, - "license": "MIT" - }, - "node_modules/ecdsa-sig-formatter": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", - "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - } - }, - "node_modules/editions": { - "version": "6.22.0", - "resolved": "https://registry.npmjs.org/editions/-/editions-6.22.0.tgz", - "integrity": "sha512-UgGlf8IW75je7HZjNDpJdCv4cGJWIi6yumFdZ0R7A8/CIhQiWUjyGLCxdHpd8bmyD1gnkfUNK0oeOXqUS2cpfQ==", - "dev": true, - "license": "Artistic-2.0", - "dependencies": { - "version-range": "^4.15.0" - }, - "engines": { - "ecmascript": ">= es5", - "node": ">=4" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "dev": true, - "license": "MIT" - }, - "node_modules/encoding-sniffer": { - "version": "0.2.1", - "resolved": "https://registry.npmjs.org/encoding-sniffer/-/encoding-sniffer-0.2.1.tgz", - "integrity": "sha512-5gvq20T6vfpekVtqrYQsSCFZ1wEg5+wW0/QaZMWkFr6BqD3NfKs0rLCx4rrVlSWJeZb5NBJgVLswK/w2MWU+Gw==", - "dev": true, - "license": "MIT", - "dependencies": { - "iconv-lite": "^0.6.3", - "whatwg-encoding": "^3.1.1" - }, - "funding": { - "url": "https://github.com/fb55/encoding-sniffer?sponsor=1" - } - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/entities": { - "version": "4.5.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz", - "integrity": "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/environment": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", - "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/es-define-property": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", - "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-errors": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", - "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/es-set-tostringtag": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", - "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.6", - "has-tostringtag": "^1.0.2", - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/esbuild": { - "version": "0.25.11", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.11.tgz", - "integrity": "sha512-KohQwyzrKTQmhXDW1PjCv3Tyspn9n5GcY2RTDqeORIdIJY8yKIF7sTSopFmn/wpMPW4rdPXI0UE5LJLuq3bx0Q==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "bin": { - "esbuild": "bin/esbuild" - }, - "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "@esbuild/aix-ppc64": "0.25.11", - "@esbuild/android-arm": "0.25.11", - "@esbuild/android-arm64": "0.25.11", - "@esbuild/android-x64": "0.25.11", - "@esbuild/darwin-arm64": "0.25.11", - "@esbuild/darwin-x64": "0.25.11", - "@esbuild/freebsd-arm64": "0.25.11", - "@esbuild/freebsd-x64": "0.25.11", - "@esbuild/linux-arm": "0.25.11", - "@esbuild/linux-arm64": "0.25.11", - "@esbuild/linux-ia32": "0.25.11", - "@esbuild/linux-loong64": "0.25.11", - "@esbuild/linux-mips64el": "0.25.11", - "@esbuild/linux-ppc64": "0.25.11", - "@esbuild/linux-riscv64": "0.25.11", - "@esbuild/linux-s390x": "0.25.11", - "@esbuild/linux-x64": "0.25.11", - "@esbuild/netbsd-arm64": "0.25.11", - "@esbuild/netbsd-x64": "0.25.11", - "@esbuild/openbsd-arm64": "0.25.11", - "@esbuild/openbsd-x64": "0.25.11", - "@esbuild/openharmony-arm64": "0.25.11", - "@esbuild/sunos-x64": "0.25.11", - "@esbuild/win32-arm64": "0.25.11", - "@esbuild/win32-ia32": "0.25.11", - "@esbuild/win32-x64": "0.25.11" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "dev": true, - "license": "(MIT OR WTFPL)", - "optional": true, - "engines": { - "node": ">=6" - } - }, - "node_modules/fast-deep-equal": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", - "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/fast-glob": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", - "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@nodelib/fs.stat": "^2.0.2", - "@nodelib/fs.walk": "^1.2.3", - "glob-parent": "^5.1.2", - "merge2": "^1.3.0", - "micromatch": "^4.0.8" - }, - "engines": { - "node": ">=8.6.0" - } - }, - "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/fastq": { - "version": "1.19.1", - "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.19.1.tgz", - "integrity": "sha512-GwLTyxkCXjXbxqIhTsMI2Nui8huMPtnxg7krajPJAjnEG/iiOS7i+zCtWGZR9G0NBKbXKh6X9m9UIsYX/N6vvQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "reusify": "^1.0.4" - } - }, - "node_modules/fd-slicer": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", - "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "pend": "~1.2.0" - } - }, - "node_modules/fill-range": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", - "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", - "dev": true, - "license": "MIT", - "dependencies": { - "to-regex-range": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/foreground-child": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz", - "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==", - "dev": true, - "license": "ISC", - "dependencies": { - "cross-spawn": "^7.0.6", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/form-data": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.4.tgz", - "integrity": "sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "es-set-tostringtag": "^2.1.0", - "hasown": "^2.0.2", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/fs-extra": { - "version": "11.3.2", - "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-11.3.2.tgz", - "integrity": "sha512-Xr9F6z6up6Ws+NjzMCZc6WXg2YFRlrLP9NQDO3VQrWrfiojdhS56TzueT88ze0uBdCTwEIhQ3ptnmKeWGFAe0A==", - "dev": true, - "license": "MIT", - "dependencies": { - "graceful-fs": "^4.2.0", - "jsonfile": "^6.0.1", - "universalify": "^2.0.0" - }, - "engines": { - "node": ">=14.14" - } - }, - "node_modules/function-bind": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", - "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", - "dev": true, - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-intrinsic": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", - "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bind-apply-helpers": "^1.0.2", - "es-define-property": "^1.0.1", - "es-errors": "^1.3.0", - "es-object-atoms": "^1.1.1", - "function-bind": "^1.1.2", - "get-proto": "^1.0.1", - "gopd": "^1.2.0", - "has-symbols": "^1.1.0", - "hasown": "^2.0.2", - "math-intrinsics": "^1.1.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/get-proto": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", - "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", - "dev": true, - "license": "MIT", - "dependencies": { - "dunder-proto": "^1.0.1", - "es-object-atoms": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/glob": { - "version": "11.0.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-11.0.3.tgz", - "integrity": "sha512-2Nim7dha1KVkaiF4q6Dj+ngPPMdfvLJEOpZk/jKiUAkqKebpGAWQXAq9z1xu9HKu5lWfqw/FASuccEjyznjPaA==", - "dev": true, - "license": "ISC", - "dependencies": { - "foreground-child": "^3.3.1", - "jackspeak": "^4.1.1", - "minimatch": "^10.0.3", - "minipass": "^7.1.2", - "package-json-from-dist": "^1.0.0", - "path-scurry": "^2.0.0" - }, - "bin": { - "glob": "dist/esm/bin.mjs" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/glob/node_modules/minimatch": { - "version": "10.0.3", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.0.3.tgz", - "integrity": "sha512-IPZ167aShDZZUMdRk66cyQAW3qr0WzbHkPdMYa8bzZhlHhO3jALbKdxcaak7W9FfT2rZNpQuUu4Od7ILEpXSaw==", - "dev": true, - "license": "ISC", - "dependencies": { - "@isaacs/brace-expansion": "^5.0.0" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/globby": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/globby/-/globby-14.1.0.tgz", - "integrity": "sha512-0Ia46fDOaT7k4og1PDW4YbodWWr3scS2vAr2lTbsplOt2WkKp0vQbkI9wKis/T5LV/dqPjO3bpS/z6GTJB82LA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sindresorhus/merge-streams": "^2.1.0", - "fast-glob": "^3.3.3", - "ignore": "^7.0.3", - "path-type": "^6.0.0", - "slash": "^5.1.0", - "unicorn-magic": "^0.3.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/gopd": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", - "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/graceful-fs": { - "version": "4.2.11", - "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", - "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/has-symbols": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", - "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", - "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.2" - }, - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/hosted-git-info": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-4.1.0.tgz", - "integrity": "sha512-kyCuEOWjJqZuDbRHzL8V93NzQhwIB71oFWSyzVo+KPZI+pnQPPxucdkrOZvkLRnrf5URsQM+IJ09Dw29cRALIA==", - "dev": true, - "license": "ISC", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/htmlparser2": { - "version": "10.0.0", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-10.0.0.tgz", - "integrity": "sha512-TwAZM+zE5Tq3lrEHvOlvwgj1XLWQCtaaibSN11Q+gGBAS7Y1uZSWwXXRe4iF6OXnaq1riyQAPFOBtYc77Mxq0g==", - "dev": true, - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "license": "MIT", - "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.2.1", - "entities": "^6.0.0" - } - }, - "node_modules/htmlparser2/node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause", - "optional": true - }, - "node_modules/ignore": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", - "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4" - } - }, - "node_modules/index-to-position": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", - "integrity": "sha512-Yg7+ztRkqslMAS2iFaU+Oa4KTSidr63OsFGlOrJoW981kIYO3CGCS3wA95P1mUi/IVSJkn0D479KTJpVpvFNuw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "dev": true, - "license": "ISC", - "optional": true - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "dev": true, - "license": "ISC", - "optional": true - }, - "node_modules/is-docker": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", - "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", - "dev": true, - "license": "MIT", - "bin": { - "is-docker": "cli.js" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-extglob": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", - "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/is-glob": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", - "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-extglob": "^2.1.1" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/is-inside-container": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", - "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-docker": "^3.0.0" - }, - "bin": { - "is-inside-container": "cli.js" - }, - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/is-number": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", - "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.12.0" - } - }, - "node_modules/is-wsl": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz", - "integrity": "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-inside-container": "^1.0.0" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/isexe": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", - "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", - "dev": true, - "license": "ISC" - }, - "node_modules/istextorbinary": { - "version": "9.5.0", - "resolved": "https://registry.npmjs.org/istextorbinary/-/istextorbinary-9.5.0.tgz", - "integrity": "sha512-5mbUj3SiZXCuRf9fT3ibzbSSEWiy63gFfksmGfdOzujPjW3k+z8WvIBxcJHBoQNlaZaiyB25deviif2+osLmLw==", - "dev": true, - "license": "Artistic-2.0", - "dependencies": { - "binaryextensions": "^6.11.0", - "editions": "^6.21.0", - "textextensions": "^6.11.0" - }, - "engines": { - "node": ">=4" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/jackspeak": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.1.1.tgz", - "integrity": "sha512-zptv57P3GpL+O0I7VdMJNBZCu+BPHVQUk55Ft8/QCJjTVxrnJHuVuX/0Bl2A6/+2oyR/ZMEuFKwmzqqZ/U5nPQ==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/cliui": "^8.0.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/js-tokens": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", - "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/js-yaml": { - "version": "3.14.1", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.1.tgz", - "integrity": "sha512-okMH7OXXJ7YrN9Ok3/SXrnu4iX9yOk+25nqX4imS2npuvTYDmo/QEZoqwZkYaIDk3jVvBOTOIEgEhaLOynBS9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/json-schema-traverse": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", - "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", - "dev": true, - "license": "MIT" - }, - "node_modules/json5": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", - "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", - "dev": true, - "license": "MIT", - "bin": { - "json5": "lib/cli.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/jsonc-parser": { - "version": "3.3.1", - "resolved": "https://registry.npmjs.org/jsonc-parser/-/jsonc-parser-3.3.1.tgz", - "integrity": "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/jsonfile": { - "version": "6.2.0", - "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-6.2.0.tgz", - "integrity": "sha512-FGuPw30AdOIUTRMC2OMRtQV+jkVj2cfPqSeWXv1NEAJ1qZ5zb1X6z1mFhbfOB/iy3ssJCD+3KuZ8r8C3uVFlAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "universalify": "^2.0.0" - }, - "optionalDependencies": { - "graceful-fs": "^4.1.6" - } - }, - "node_modules/jsonwebtoken": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", - "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "jws": "^3.2.2", - "lodash.includes": "^4.3.0", - "lodash.isboolean": "^3.0.3", - "lodash.isinteger": "^4.0.4", - "lodash.isnumber": "^3.0.3", - "lodash.isplainobject": "^4.0.6", - "lodash.isstring": "^4.0.1", - "lodash.once": "^4.0.0", - "ms": "^2.1.1", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=12", - "npm": ">=6" - } - }, - "node_modules/jwa": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", - "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-equal-constant-time": "^1.0.1", - "ecdsa-sig-formatter": "1.0.11", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/jws": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", - "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", - "dev": true, - "license": "MIT", - "dependencies": { - "jwa": "^1.4.1", - "safe-buffer": "^5.0.1" - } - }, - "node_modules/keytar": { - "version": "7.9.0", - "resolved": "https://registry.npmjs.org/keytar/-/keytar-7.9.0.tgz", - "integrity": "sha512-VPD8mtVtm5JNtA2AErl6Chp06JBfy7diFQ7TQQhdpWOl6MrCRB+eRbvAZUsbGQS9kiMq0coJsy0W0vHpDCkWsQ==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "dependencies": { - "node-addon-api": "^4.3.0", - "prebuild-install": "^7.0.1" - } - }, - "node_modules/leven": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/leven/-/leven-3.1.0.tgz", - "integrity": "sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/linkify-it": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/linkify-it/-/linkify-it-5.0.0.tgz", - "integrity": "sha512-5aHCbzQRADcdP+ATqnDuhhJ/MRIqDkZX5pyjFHRRysS8vZ5AbqGEoFIb6pYHPZ+L/OC2Lc+xT8uHVVR5CAK/wQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "uc.micro": "^2.0.0" - } - }, - "node_modules/lodash": { - "version": "4.17.21", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", - "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.includes": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", - "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isboolean": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", - "integrity": "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isinteger": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/lodash.isinteger/-/lodash.isinteger-4.0.4.tgz", - "integrity": "sha512-DBwtEWN2caHQ9/imiNeEA5ys1JoRtRfY3d7V9wkqtbycnAmTvRRmbHKDV4a0EYc678/dia0jrte4tjYwVBaZUA==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isnumber": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/lodash.isnumber/-/lodash.isnumber-3.0.3.tgz", - "integrity": "sha512-QYqzpfwO3/CWf3XP+Z+tkQsfaLL/EnUlXWVkIk5FUPc4sBdTehEqZONuyRt2P67PXAk+NXmTBcc97zw9t1FQrw==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isplainobject": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/lodash.isplainobject/-/lodash.isplainobject-4.0.6.tgz", - "integrity": "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.isstring": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/lodash.isstring/-/lodash.isstring-4.0.1.tgz", - "integrity": "sha512-0wJxfxH1wgO3GrbuP+dTTk7op+6L41QCXbGINEmD+ny/G/eCqGzxyCsh7159S+mgDDcoarnBw6PC1PS5+wUGgw==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.once": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/lodash.once/-/lodash.once-4.1.1.tgz", - "integrity": "sha512-Sb487aTOCr9drQVL8pIxOzVhafOjZN9UU54hiN8PU3uAiSV7lx1yYNpbNmex2PK6dSJoNTSJUUswT651yww3Mg==", - "dev": true, - "license": "MIT" - }, - "node_modules/lodash.truncate": { - "version": "4.4.2", - "resolved": "https://registry.npmjs.org/lodash.truncate/-/lodash.truncate-4.4.2.tgz", - "integrity": "sha512-jttmRe7bRse52OsWIMDLaXxWqRAmtIUccAQ3garviCqJjafXOfNMO0yMfNpdD6zbGaTU0P5Nz7e7gAT6cKmJRw==", - "dev": true, - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/markdown-it": { - "version": "14.1.0", - "resolved": "https://registry.npmjs.org/markdown-it/-/markdown-it-14.1.0.tgz", - "integrity": "sha512-a54IwgWPaeBCAAsv13YgmALOF1elABB08FxO9i+r4VFk5Vl4pKokRPeX8u5TCgSsPi6ec1otfLjdOpVcgbpshg==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1", - "entities": "^4.4.0", - "linkify-it": "^5.0.0", - "mdurl": "^2.0.0", - "punycode.js": "^2.3.1", - "uc.micro": "^2.1.0" - }, - "bin": { - "markdown-it": "bin/markdown-it.mjs" - } - }, - "node_modules/markdown-it/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, - "node_modules/math-intrinsics": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", - "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - } - }, - "node_modules/mdurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/mdurl/-/mdurl-2.0.0.tgz", - "integrity": "sha512-Lf+9+2r+Tdp5wXDXC4PcIBjTDtq4UKjCPMQhKIuzpJNW0b96kVqSwW0bT7FhRSfmAiFYgP+SCRvdrDozfh0U5w==", - "dev": true, - "license": "MIT" - }, - "node_modules/merge2": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", - "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 8" - } - }, - "node_modules/micromatch": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", - "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", - "dev": true, - "license": "MIT", - "dependencies": { - "braces": "^3.0.3", - "picomatch": "^2.3.1" - }, - "engines": { - "node": ">=8.6" - } - }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "dev": true, - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimatch": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", - "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", - "dev": true, - "license": "ISC", - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/minimatch/node_modules/brace-expansion": { - "version": "1.1.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", - "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "dev": true, - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/mute-stream": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==", - "dev": true, - "license": "ISC" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/node-abi": { - "version": "3.78.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.78.0.tgz", - "integrity": "sha512-E2wEyrgX/CqvicaQYU3Ze1PFGjc4QYPGsjUrlYkqAE0WjHEZwgOsGMPMzkMse4LjJbDmaEuDX3CM036j5K2DSQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/node-addon-api": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-4.3.0.tgz", - "integrity": "sha512-73sE9+3UaLYYFmDsFZnqCInzPyh3MqIwZO9cw58yIqAZhONrrabrYyYe3TuIqtIiOuTXVhsGau8hcrhhwSsDIQ==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/node-sarif-builder": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/node-sarif-builder/-/node-sarif-builder-3.2.0.tgz", - "integrity": "sha512-kVIOdynrF2CRodHZeP/97Rh1syTUHBNiw17hUCIVhlhEsWlfJm19MuO56s4MdKbr22xWx6mzMnNAgXzVlIYM9Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/sarif": "^2.1.7", - "fs-extra": "^11.1.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/normalize-package-data": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/normalize-package-data/-/normalize-package-data-6.0.2.tgz", - "integrity": "sha512-V6gygoYb/5EmNI+MEGrWkC+e6+Rr7mTmfHrxDbLzxQogBkgzo76rkok0Am6thgSF7Mv2nLOajAJj5vDJZEFn7g==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "hosted-git-info": "^7.0.0", - "semver": "^7.3.5", - "validate-npm-package-license": "^3.0.4" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/normalize-package-data/node_modules/hosted-git-info": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/hosted-git-info/-/hosted-git-info-7.0.2.tgz", - "integrity": "sha512-puUZAUKT5m8Zzvs72XWy3HtvVbTWljRE66cP60bxJzAqf2DgICo7lYTY2IHUmLnNpjYvw5bvmoHvPc0QO2a62w==", - "dev": true, - "license": "ISC", - "dependencies": { - "lru-cache": "^10.0.1" - }, - "engines": { - "node": "^16.14.0 || >=18.0.0" - } - }, - "node_modules/normalize-package-data/node_modules/lru-cache": { - "version": "10.4.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz", - "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/nth-check": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boolbase": "^1.0.0" - }, - "funding": { - "url": "https://github.com/fb55/nth-check?sponsor=1" - } - }, - "node_modules/object-inspect": { - "version": "1.13.4", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", - "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "optional": true, - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/open": { - "version": "10.2.0", - "resolved": "https://registry.npmjs.org/open/-/open-10.2.0.tgz", - "integrity": "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "default-browser": "^5.2.1", - "define-lazy-prop": "^3.0.0", - "is-inside-container": "^1.0.0", - "wsl-utils": "^0.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-map": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/p-map/-/p-map-7.0.3.tgz", - "integrity": "sha512-VkndIv2fIB99swvQoA65bm+fsmt6UNdGeIB0oxBs+WhAhdh08QA04JXpI7rbB9r08/nkbysKoya9rtDERYOYMA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/package-json-from-dist": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz", - "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==", - "dev": true, - "license": "BlueOak-1.0.0" - }, - "node_modules/parse-json": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-8.3.0.tgz", - "integrity": "sha512-ybiGyvspI+fAoRQbIPRddCcSTV9/LsJbf0e/S85VLowVGzRmokfneg2kwVW/KU5rOXrPSbF1qAKPMgNTqqROQQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.26.2", - "index-to-position": "^1.1.0", - "type-fest": "^4.39.1" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/parse-semver": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/parse-semver/-/parse-semver-1.1.1.tgz", - "integrity": "sha512-Eg1OuNntBMH0ojvEKSrvDSnwLmvVuUOSdylH/pSCPNMIspLlweJyIWXCE+k/5hm3cj/EBUYwmWkjhBALNP4LXQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^5.1.0" - } - }, - "node_modules/parse-semver/node_modules/semver": { - "version": "5.7.2", - "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.2.tgz", - "integrity": "sha512-cBznnQ9KjJqU67B52RMC65CMarK2600WFnbkcaiwWq3xy/5haFJlshgnpjovMVJ+Hff49d8GEn0b87C5pDQ10g==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver" - } - }, - "node_modules/parse5": { - "version": "7.3.0", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz", - "integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==", - "dev": true, - "license": "MIT", - "dependencies": { - "entities": "^6.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.1.0.tgz", - "integrity": "sha512-ruw5xyKs6lrpo9x9rCZqZZnIUntICjQAd0Wsmp396Ul9lN/h+ifgVV1x1gZHi8euej6wTfpqX8j+BFQxF0NS/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "domhandler": "^5.0.3", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/parse5-parser-stream": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5-parser-stream/-/parse5-parser-stream-7.1.2.tgz", - "integrity": "sha512-JyeQc9iwFLn5TbvvqACIF/VXG6abODeB3Fwmv/TGdLk2LfbWkaySGY72at4+Ty7EkPZj854u4CrICqNk2qIbow==", - "dev": true, - "license": "MIT", - "dependencies": { - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" - } - }, - "node_modules/parse5/node_modules/entities": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz", - "integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=0.12" - }, - "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" - } - }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-scurry": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.0.tgz", - "integrity": "sha512-ypGJsmGtdXUOeM5u93TyeIEfEhM6s+ljAhrk5vAvSx8uyY/02OvrZnA0YNGUrPXfpJMgI1ODd3nwz8Npx4O4cg==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/path-scurry/node_modules/lru-cache": { - "version": "11.2.2", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.2.tgz", - "integrity": "sha512-F9ODfyqML2coTIsQpSkRHnLSZMtkU8Q+mSfcaIyKwy58u+8k5nvAYeiNhsyMARvzNcXJ9QfWVrcPsC9e9rAxtg==", - "dev": true, - "license": "ISC", - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/path-type": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/path-type/-/path-type-6.0.0.tgz", - "integrity": "sha512-Vj7sf++t5pBD637NSfkxpHSMfWaeig5+DKWLhcqIYx6mWQz5hdJTGDVMQiJcw1ZYkhs7AazKDGpRVji1LJCZUQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/pend": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", - "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", - "dev": true, - "license": "MIT" - }, - "node_modules/picocolors": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", - "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", - "dev": true, - "license": "ISC" - }, - "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.6" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/pluralize": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/pluralize/-/pluralize-8.0.0.tgz", - "integrity": "sha512-Nc3IT5yHzflTfbjgqWcCPpo7DaKy4FnpB0l/zCAW0Tc7jxAiuqSxHasntB3D7887LSrA93kDJ9IXovxJYxyLCA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.3.tgz", - "integrity": "sha512-todwxLMY7/heScKmntwQG8CXVkWUOdYxIvY2s0VWAAMh/nd8SoYiRaKjlr7+iCs984f2P8zvrfWcDDYVb73NfA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/punycode.js": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode.js/-/punycode.js-2.3.1.tgz", - "integrity": "sha512-uxFIHU0YlHYhDQtV4R9J6a52SLx28BCjT+4ieh7IGbgwVJWO+km431c4yRlREUAsAmt/uMjQUyQHNEPf0M39CA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, - "node_modules/qs": { - "version": "6.14.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", - "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.1.0" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/queue-microtask": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", - "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "dev": true, - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "optional": true, - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/rc-config-loader": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/rc-config-loader/-/rc-config-loader-4.1.3.tgz", - "integrity": "sha512-kD7FqML7l800i6pS6pvLyIE2ncbk9Du8Q0gp/4hMPhJU6ZxApkoLcGD8ZeqgiAlfwZ6BlETq6qqe+12DUL207w==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.3.4", - "js-yaml": "^4.1.0", - "json5": "^2.2.2", - "require-from-string": "^2.0.2" - } - }, - "node_modules/rc-config-loader/node_modules/argparse": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", - "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", - "dev": true, - "license": "Python-2.0" - }, - "node_modules/rc-config-loader/node_modules/js-yaml": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", - "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^2.0.1" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, - "node_modules/read": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", - "integrity": "sha512-rSOKNYUmaxy0om1BNjMN4ezNT6VKK+2xF4GBhc81mkH7L60i6dp8qPYrkndNLT3QPphoII3maL9PVC9XmhHwVQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "mute-stream": "~0.0.4" - }, - "engines": { - "node": ">=0.8" - } - }, - "node_modules/read-pkg": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-9.0.1.tgz", - "integrity": "sha512-9viLL4/n1BJUCT1NXVTdS1jtm80yDEgR5T4yCelII49Mbj0v1rZdKqj7zCiYdbB0CuCgdrvHcNogAKTFPBocFA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/normalize-package-data": "^2.4.3", - "normalize-package-data": "^6.0.0", - "parse-json": "^8.0.0", - "type-fest": "^4.6.0", - "unicorn-magic": "^0.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/read-pkg/node_modules/unicorn-magic": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.1.0.tgz", - "integrity": "sha512-lRfVq8fE8gz6QMBuDM6a+LO3IAzTi05H6gCVaUpir2E1Rwpo4ZUog45KpNXKC/Mn3Yb9UDuHumeFTo9iV/D9FQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/require-from-string": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", - "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/reusify": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", - "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">=1.0.0", - "node": ">=0.10.0" - } - }, - "node_modules/run-applescript": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", - "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/run-parallel": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", - "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "queue-microtask": "^1.2.2" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "dev": true, - "license": "MIT" - }, - "node_modules/sax": { - "version": "1.4.1", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.1.tgz", - "integrity": "sha512-+aWOz7yVScEGoKNd4PA10LZ8sk0A/z5+nXQG5giUO5rprX9jgYsTdov9qCchZiPIZezbZH+jRut8nPodFAX4Jg==", - "dev": true, - "license": "ISC" - }, - "node_modules/secretlint": { - "version": "10.2.2", - "resolved": "https://registry.npmjs.org/secretlint/-/secretlint-10.2.2.tgz", - "integrity": "sha512-xVpkeHV/aoWe4vP4TansF622nBEImzCY73y/0042DuJ29iKIaqgoJ8fGxre3rVSHHbxar4FdJobmTnLp9AU0eg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@secretlint/config-creator": "^10.2.2", - "@secretlint/formatter": "^10.2.2", - "@secretlint/node": "^10.2.2", - "@secretlint/profiler": "^10.2.2", - "debug": "^4.4.1", - "globby": "^14.1.0", - "read-pkg": "^9.0.1" - }, - "bin": { - "secretlint": "bin/secretlint.js" - }, - "engines": { - "node": ">=20.0.0" - } - }, - "node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", - "side-channel-map": "^1.0.1", - "side-channel-weakmap": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", - "dev": true, - "license": "MIT", - "dependencies": { - "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-map": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", - "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/side-channel-weakmap": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true, - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/slash": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", - "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/slice-ansi": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", - "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "astral-regex": "^2.0.0", - "is-fullwidth-code-point": "^3.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/slice-ansi?sponsor=1" - } - }, - "node_modules/spdx-correct": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", - "integrity": "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-expression-parse": "^3.0.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/spdx-exceptions": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz", - "integrity": "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w==", - "dev": true, - "license": "CC-BY-3.0" - }, - "node_modules/spdx-expression-parse": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz", - "integrity": "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "spdx-exceptions": "^2.1.0", - "spdx-license-ids": "^3.0.0" - } - }, - "node_modules/spdx-license-ids": { - "version": "3.0.22", - "resolved": "https://registry.npmjs.org/spdx-license-ids/-/spdx-license-ids-3.0.22.tgz", - "integrity": "sha512-4PRT4nh1EImPbt2jASOKHX7PB7I+e4IWNLvkKFDxNhJlfjbYlleYQh285Z/3mPTHSAK/AvdMmw5BNNuYH8ShgQ==", - "dev": true, - "license": "CC0-1.0" - }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs": { - "name": "string-width", - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "dev": true, - "license": "MIT", - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/string-width/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.1.2.tgz", - "integrity": "sha512-gmBGslpoQJtgnMAvOVqGZpEz9dyoKTCzy2nfz/n8aIFhN/jCE/rCmcxabB6jOOHV+0WNnylOxaxBQPSvcWklhA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^6.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/strip-ansi?sponsor=1" - } - }, - "node_modules/strip-ansi-cjs": { - "name": "strip-ansi", - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "dev": true, - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/structured-source": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/structured-source/-/structured-source-4.0.0.tgz", - "integrity": "sha512-qGzRFNJDjFieQkl/sVOI2dUjHKRyL9dAJi2gCPGJLbJHBIkyOHxjuocpIEfbLioX+qSJpvbYdT49/YCdMznKxA==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "boundary": "^2.0.0" - } - }, - "node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/supports-hyperlinks": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/supports-hyperlinks/-/supports-hyperlinks-3.2.0.tgz", - "integrity": "sha512-zFObLMyZeEwzAoKCyu1B91U79K2t7ApXuQfo8OuxwXLDgcKxuwM+YvcbIhm6QWqz7mHUH1TVytR1PwVVjEuMig==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0", - "supports-color": "^7.0.0" - }, - "engines": { - "node": ">=14.18" - }, - "funding": { - "url": "https://github.com/chalk/supports-hyperlinks?sponsor=1" - } - }, - "node_modules/table": { - "version": "6.9.0", - "resolved": "https://registry.npmjs.org/table/-/table-6.9.0.tgz", - "integrity": "sha512-9kY+CygyYM6j02t5YFHbNz2FN5QmYGv9zAjVp4lCDjlCw7amdckXlEt/bjMhUIfj4ThGRE4gCUH5+yGnNuPo5A==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "ajv": "^8.0.1", - "lodash.truncate": "^4.4.2", - "slice-ansi": "^4.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=10.0.0" - } - }, - "node_modules/table/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/table/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/tar-fs": { - "version": "2.1.4", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.4.tgz", - "integrity": "sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/terminal-link": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/terminal-link/-/terminal-link-4.0.0.tgz", - "integrity": "sha512-lk+vH+MccxNqgVqSnkMVKx4VLJfnLjDBGzH16JVZjKE2DoxP57s6/vt6JmXV5I3jBcfGrxNrYtC+mPtU7WJztA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-escapes": "^7.0.0", - "supports-hyperlinks": "^3.2.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/text-table": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", - "integrity": "sha512-N+8UisAXDGk8PFXP4HAzVR9nbfmVJ3zYLAWiTIoqC5v5isinhr+r5uaO8+7r3BMfuNIufIsA7RdpVgacC2cSpw==", - "dev": true, - "license": "MIT" - }, - "node_modules/textextensions": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/textextensions/-/textextensions-6.11.0.tgz", - "integrity": "sha512-tXJwSr9355kFJI3lbCkPpUH5cP8/M0GGy2xLO34aZCjMXBaK3SoPnZwr/oWmo1FdCnELcs4npdCIOFtq9W3ruQ==", - "dev": true, - "license": "Artistic-2.0", - "dependencies": { - "editions": "^6.21.0" - }, - "engines": { - "node": ">=4" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/tmp": { - "version": "0.2.5", - "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.5.tgz", - "integrity": "sha512-voyz6MApa1rQGUxT3E+BK7/ROe8itEx7vD8/HEvt4xwXucvQ5G5oeEiHkmHZJuBO21RpOf+YYm9MOivj709jow==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=14.14" - } - }, - "node_modules/to-regex-range": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", - "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-number": "^7.0.0" - }, - "engines": { - "node": ">=8.0" - } - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD" - }, - "node_modules/tunnel": { - "version": "0.0.6", - "resolved": "https://registry.npmjs.org/tunnel/-/tunnel-0.0.6.tgz", - "integrity": "sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.6.11 <=0.7.0 || >=0.7.3" - } - }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "dev": true, - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, - "node_modules/type-fest": { - "version": "4.41.0", - "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-4.41.0.tgz", - "integrity": "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA==", - "dev": true, - "license": "(MIT OR CC0-1.0)", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/typed-rest-client": { - "version": "1.8.11", - "resolved": "https://registry.npmjs.org/typed-rest-client/-/typed-rest-client-1.8.11.tgz", - "integrity": "sha512-5UvfMpd1oelmUPRbbaVnq+rHP7ng2cE4qoQkQeAqxRL6PklkxsM0g32/HL0yfvruK6ojQ5x8EE+HF4YV6DtuCA==", - "dev": true, - "license": "MIT", - "dependencies": { - "qs": "^6.9.1", - "tunnel": "0.0.6", - "underscore": "^1.12.1" - } - }, - "node_modules/typescript": { - "version": "5.9.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", - "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", - "dev": true, - "license": "Apache-2.0", - "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" - }, - "engines": { - "node": ">=14.17" - } - }, - "node_modules/uc.micro": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/uc.micro/-/uc.micro-2.1.0.tgz", - "integrity": "sha512-ARDJmphmdvUk6Glw7y9DQ2bFkKBHwQHLi2lsaH6PPmz/Ka9sFOBsBluozhDltWmnv9u/cF6Rt87znRTPV+yp/A==", - "dev": true, - "license": "MIT" - }, - "node_modules/underscore": { - "version": "1.13.7", - "resolved": "https://registry.npmjs.org/underscore/-/underscore-1.13.7.tgz", - "integrity": "sha512-GMXzWtsc57XAtguZgaQViUOzs0KTkk8ojr3/xAxXLITqf/3EMwxC0inyETfDFjH/Krbhuep0HNbbjI9i/q3F3g==", - "dev": true, - "license": "MIT" - }, - "node_modules/undici": { - "version": "7.16.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.16.0.tgz", - "integrity": "sha512-QEg3HPMll0o3t2ourKwOeUAZ159Kn9mx5pnzHRQO8+Wixmh88YdZRiIwat0iNzNNXn0yoEtXJqFpyW7eM8BV7g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=20.18.1" - } - }, - "node_modules/undici-types": { - "version": "6.21.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", - "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/unicorn-magic": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/unicorn-magic/-/unicorn-magic-0.3.0.tgz", - "integrity": "sha512-+QBBXBCvifc56fsbuxZQ6Sic3wqqc3WWaqxs58gvJrcOuN83HGTCwz3oS5phzU9LthRNE9VrJCFCLUgHeeFnfA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/universalify": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-2.0.1.tgz", - "integrity": "sha512-gptHNQghINnc/vTGIk0SOFGFNXw7JVrlRUtConJRlvaw6DuX0wO5Jeko9sWrMBhh+PsYAZ7oXAiOnf/UKogyiw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 10.0.0" - } - }, - "node_modules/url-join": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/url-join/-/url-join-4.0.1.tgz", - "integrity": "sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==", - "dev": true, - "license": "MIT" - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "dev": true, - "license": "MIT", - "optional": true - }, - "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "dev": true, - "license": "MIT", - "bin": { - "uuid": "dist/bin/uuid" - } - }, - "node_modules/validate-npm-package-license": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", - "integrity": "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "spdx-correct": "^3.0.0", - "spdx-expression-parse": "^3.0.0" - } - }, - "node_modules/version-range": { - "version": "4.15.0", - "resolved": "https://registry.npmjs.org/version-range/-/version-range-4.15.0.tgz", - "integrity": "sha512-Ck0EJbAGxHwprkzFO966t4/5QkRuzh+/I1RxhLgUKKwEn+Cd8NwM60mE3AqBZg5gYODoXW0EFsQvbZjRlvdqbg==", - "dev": true, - "license": "Artistic-2.0", - "engines": { - "node": ">=4" - }, - "funding": { - "url": "https://bevry.me/fund" - } - }, - "node_modules/vscode-jsonrpc": { - "version": "8.2.0", - "resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz", - "integrity": "sha512-C+r0eKJUIfiDIfwJhria30+TYWPtuHJXHtI7J0YlOmKAo7ogxP20T0zxB7HZQIFhIyvoBPwWskjxrvAtfjyZfA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/vscode-languageclient": { - "version": "9.0.1", - "resolved": "https://registry.npmjs.org/vscode-languageclient/-/vscode-languageclient-9.0.1.tgz", - "integrity": "sha512-JZiimVdvimEuHh5olxhxkht09m3JzUGwggb5eRUkzzJhZ2KjCN0nh55VfiED9oez9DyF8/fz1g1iBV3h+0Z2EA==", - "license": "MIT", - "dependencies": { - "minimatch": "^5.1.0", - "semver": "^7.3.7", - "vscode-languageserver-protocol": "3.17.5" - }, - "engines": { - "vscode": "^1.82.0" - } - }, - "node_modules/vscode-languageclient/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.1" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/vscode-languageserver-protocol": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-protocol/-/vscode-languageserver-protocol-3.17.5.tgz", - "integrity": "sha512-mb1bvRJN8SVznADSGWM9u/b07H7Ecg0I3OgXDuLdn307rl/J3A9YD6/eYOssqhecL27hK1IPZAsaqh00i/Jljg==", - "license": "MIT", - "dependencies": { - "vscode-jsonrpc": "8.2.0", - "vscode-languageserver-types": "3.17.5" - } - }, - "node_modules/vscode-languageserver-types": { - "version": "3.17.5", - "resolved": "https://registry.npmjs.org/vscode-languageserver-types/-/vscode-languageserver-types-3.17.5.tgz", - "integrity": "sha512-Ld1VelNuX9pdF39h2Hgaeb5hEZM2Z3jUrrMgWQAu82jMtZp7p3vJT3BzToKtZI7NgQssZje5o0zryOrhQvzQAg==", - "license": "MIT" - }, - "node_modules/whatwg-encoding": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz", - "integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "iconv-lite": "0.6.3" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/whatwg-mimetype": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz", - "integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18" - } - }, - "node_modules/which": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", - "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", - "dev": true, - "license": "ISC", - "dependencies": { - "isexe": "^2.0.0" - }, - "bin": { - "node-which": "bin/node-which" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/wrap-ansi": { - "version": "8.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz", - "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^6.1.0", - "string-width": "^5.0.1", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs": { - "name": "wrap-ansi", - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", - "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-styles": "^4.0.0", - "string-width": "^4.1.0", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/wrap-ansi?sponsor=1" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "dev": true, - "license": "MIT", - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/wrap-ansi/node_modules/ansi-styles": { - "version": "6.2.3", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", - "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/wrap-ansi/node_modules/emoji-regex": { - "version": "9.2.2", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", - "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", - "dev": true, - "license": "MIT" - }, - "node_modules/wrap-ansi/node_modules/string-width": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", - "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==", - "dev": true, - "license": "MIT", - "dependencies": { - "eastasianwidth": "^0.2.0", - "emoji-regex": "^9.2.2", - "strip-ansi": "^7.0.1" - }, - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC", - "optional": true - }, - "node_modules/wsl-utils": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.1.0.tgz", - "integrity": "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-wsl": "^3.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/xml2js": { - "version": "0.5.0", - "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.5.0.tgz", - "integrity": "sha512-drPFnkQJik/O+uPKpqSgr22mpuFHqKdbS835iAQrUC73L2F5WkboIRd63ai/2Yg6I1jzifPFKH2NTK+cfglkIA==", - "dev": true, - "license": "MIT", - "dependencies": { - "sax": ">=0.6.0", - "xmlbuilder": "~11.0.0" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/xmlbuilder": { - "version": "11.0.1", - "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", - "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true, - "license": "ISC" - }, - "node_modules/yauzl": { - "version": "2.10.0", - "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", - "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-crc32": "~0.2.3", - "fd-slicer": "~1.1.0" - } - }, - "node_modules/yazl": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/yazl/-/yazl-2.5.1.tgz", - "integrity": "sha512-phENi2PLiHnHb6QBVot+dJnaAZ0xosj7p3fWl+znIjBDlnMI2PsZCJZ306BPTFOaHf5qdDEI8x5qFrSOBN5vrw==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-crc32": "~0.2.3" - } - } - } -} diff --git a/vscode-lsp/package.json b/vscode-lsp/package.json deleted file mode 100644 index fff14ae..0000000 --- a/vscode-lsp/package.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "name": "nub", - "displayName": "Nub Language Support", - "description": "Language server client for nub lang", - "version": "0.0.1", - "publisher": "nub31", - "repository": { - "type": "git", - "url": "https://git.oliste.no/nub31/nub-lang" - }, - "engines": { - "vscode": "^1.105.0" - }, - "categories": [ - "Programming Languages" - ], - "main": "./out/extension.js", - "files": [ - "out", - "server", - "syntaxes", - "language-configuration.json" - ], - "contributes": { - "languages": [ - { - "id": "nub", - "extensions": [ - ".nub" - ], - "configuration": "./language-configuration.json" - } - ], - "grammars": [ - { - "language": "nub", - "scopeName": "source.nub", - "path": "./syntaxes/nub.tmLanguage.json" - } - ] - }, - "scripts": { - "build": "esbuild src/extension.ts --bundle --platform=node --outfile=out/extension.js --external:vscode", - "update-lsp": "mkdir -p server && dotnet publish -c Release ../compiler/NubLang.LSP/NubLang.LSP.csproj && cp ../compiler/NubLang.LSP/bin/Release/net9.0/linux-x64/publish/nublsp server/", - "package": "npm run update-lsp && npm run build && vsce package --skip-license" - }, - "devDependencies": { - "@types/node": "22.x", - "@types/vscode": "^1.105.0", - "@vscode/vsce": "^3.6.2", - "esbuild": "^0.25.11", - "typescript": "^5.9.3" - }, - "dependencies": { - "vscode-languageclient": "^9.0.1" - } -} \ No newline at end of file diff --git a/vscode-lsp/src/extension.ts b/vscode-lsp/src/extension.ts deleted file mode 100644 index 065b5cd..0000000 --- a/vscode-lsp/src/extension.ts +++ /dev/null @@ -1,44 +0,0 @@ -import path from 'path'; -import vscode from 'vscode'; -import { LanguageClient, TransportKind } from 'vscode-languageclient/node'; - -let client: LanguageClient; - -export async function activate(context: vscode.ExtensionContext) { - const serverExecutable = path.join(context.asAbsolutePath('server'), "nublsp"); - - client = new LanguageClient( - 'nub', - 'nub lsp client', - { - run: { - command: serverExecutable, - transport: TransportKind.stdio, - }, - debug: { - command: serverExecutable, - transport: TransportKind.stdio, - args: ['--debug'], - } - }, - { - documentSelector: [ - { scheme: 'file', language: 'nub' }, - { scheme: 'file', pattern: '**/*.nub' } - ], - synchronize: { - fileEvents: vscode.workspace.createFileSystemWatcher('**/.clientrc') - } - } - ); - - client.start(); -} - -export function deactivate(): Thenable | undefined { - if (!client) { - return undefined; - } - - return client.stop(); -} \ No newline at end of file diff --git a/vscode-lsp/syntaxes/nub.tmLanguage.json b/vscode-lsp/syntaxes/nub.tmLanguage.json deleted file mode 100644 index 17de754..0000000 --- a/vscode-lsp/syntaxes/nub.tmLanguage.json +++ /dev/null @@ -1,304 +0,0 @@ -{ - "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", - "name": "nub", - "scopeName": "source.nub", - "patterns": [ - { - "include": "#comments" - }, - { - "include": "#keywords" - }, - { - "include": "#modifiers" - }, - { - "include": "#types" - }, - { - "include": "#strings" - }, - { - "include": "#numbers" - }, - { - "include": "#operators" - }, - { - "include": "#function-definition" - }, - { - "include": "#struct-definition" - }, - { - "include": "#function-call" - }, - { - "include": "#identifiers" - } - ], - "repository": { - "comments": { - "patterns": [ - { - "name": "comment.line.double-slash.nub", - "begin": "//", - "end": "$" - }, - { - "name": "comment.block.nub", - "begin": "/\\*", - "end": "\\*/" - } - ] - }, - "keywords": { - "patterns": [ - { - "name": "keyword.control.nub", - "match": "\\b(if|else|while|for|in|break|continue|return|let|defer)\\b" - }, - { - "name": "keyword.other.nub", - "match": "\\b(func|struct|module|import)\\b" - } - ] - }, - "modifiers": { - "patterns": [ - { - "name": "storage.modifier.nub", - "match": "\\b(export|extern)\\b" - } - ] - }, - "types": { - "patterns": [ - { - "include": "#function-type" - }, - { - "name": "storage.type.primitive.nub", - "match": "\\b(i8|i16|i32|i64|u8|u16|u32|u64|f32|f64|bool|string|cstring|void|any)\\b" - }, - { - "name": "storage.type.array.nub", - "match": "\\[\\]" - }, - { - "name": "storage.type.pointer.nub", - "match": "\\^" - } - ] - }, - "function-type": { - "patterns": [ - { - "begin": "\\b(func)\\s*\\(", - "beginCaptures": { - "1": { - "name": "storage.type.function.nub" - } - }, - "end": "(?<=\\))(?:\\s*:\\s*([^\\s,;{}()]+))?", - "endCaptures": { - "1": { - "name": "storage.type.nub" - } - }, - "patterns": [ - { - "include": "#function-type-parameters" - } - ] - } - ] - }, - "function-type-parameters": { - "patterns": [ - { - "match": "\\.\\.\\.", - "name": "keyword.operator.variadic.nub" - }, - { - "include": "#types" - }, - { - "match": ",", - "name": "punctuation.separator.nub" - } - ] - }, - "strings": { - "patterns": [ - { - "name": "string.quoted.double.nub", - "begin": "\"", - "end": "\"", - "patterns": [ - { - "name": "constant.character.escape.nub", - "match": "\\\\(n|t|r|\\\\|\"|')" - }, - { - "name": "constant.character.escape.nub", - "match": "\\\\[0-7]{1,3}" - }, - { - "name": "constant.character.escape.nub", - "match": "\\\\x[0-9A-Fa-f]{1,2}" - } - ] - }, - { - "name": "string.quoted.single.nub", - "begin": "'", - "end": "'", - "patterns": [ - { - "name": "constant.character.escape.nub", - "match": "\\\\(n|t|r|\\\\|\"|')" - } - ] - } - ] - }, - "numbers": { - "patterns": [ - { - "name": "constant.numeric.float.nub", - "match": "\\b\\d+\\.\\d*([eE][+-]?\\d+)?[fF]?\\b" - }, - { - "name": "constant.numeric.integer.decimal.nub", - "match": "\\b\\d+\\b" - }, - { - "name": "constant.numeric.integer.hexadecimal.nub", - "match": "\\b0[xX][0-9A-Fa-f]+\\b" - }, - { - "name": "constant.numeric.integer.binary.nub", - "match": "\\b0[bB][01]+\\b" - } - ] - }, - "operators": { - "patterns": [ - { - "name": "keyword.operator.assignment.nub", - "match": "=" - }, - { - "name": "keyword.operator.comparison.nub", - "match": "(==|!=|<=|>=|<|>)" - }, - { - "name": "keyword.operator.arithmetic.nub", - "match": "(\\+|\\-|\\*|/)" - }, - { - "name": "keyword.operator.logical.nub", - "match": "(&&|\\|\\||!)" - }, - { - "name": "keyword.operator.address.nub", - "match": "&" - }, - { - "name": "keyword.operator.dereference.nub", - "match": "\\^" - }, - { - "name": "keyword.operator.member-access.nub", - "match": "\\." - }, - { - "name": "keyword.operator.module-access.nub", - "match": "::" - } - ] - }, - "function-definition": { - "patterns": [ - { - "begin": "\\b(export\\s+|extern\\s+)?(func)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\(", - "beginCaptures": { - "1": { - "name": "storage.modifier.nub" - }, - "2": { - "name": "keyword.other.nub" - }, - "3": { - "name": "entity.name.function.nub" - } - }, - "end": "\\)", - "patterns": [ - { - "include": "#function-parameters" - } - ] - } - ] - }, - "struct-definition": { - "patterns": [ - { - "match": "\\b(struct)\\s+([a-zA-Z_][a-zA-Z0-9_]*)\\b", - "captures": { - "1": { - "name": "keyword.other.nub" - }, - "2": { - "name": "entity.name.type.struct.nub" - } - } - } - ] - }, - "function-parameters": { - "patterns": [ - { - "match": "\\.\\.\\.", - "name": "keyword.operator.variadic.nub" - }, - { - "match": "([a-zA-Z_][a-zA-Z0-9_]*)\\s*:\\s*", - "captures": { - "1": { - "name": "variable.parameter.nub" - } - } - }, - { - "include": "#types" - }, - { - "include": "#identifiers" - } - ] - }, - "function-call": { - "patterns": [ - { - "match": "([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=\\()", - "captures": { - "1": { - "name": "entity.name.function.call.nub" - } - } - } - ] - }, - "identifiers": { - "patterns": [ - { - "name": "variable.other.nub", - "match": "\\b[a-zA-Z_][a-zA-Z0-9_]*\\b" - } - ] - } - } -} \ No newline at end of file diff --git a/vscode-lsp/tsconfig.json b/vscode-lsp/tsconfig.json deleted file mode 100644 index ebe5970..0000000 --- a/vscode-lsp/tsconfig.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "compilerOptions": { - "module": "Node16", - "target": "ES2022", - "outDir": "out", - "lib": [ - "ES2022" - ], - "sourceMap": true, - "rootDir": "src", - "strict": true, - "noImplicitReturns": true, - "noFallthroughCasesInSwitch": true - } -} \ No newline at end of file