diff --git a/.clang-format b/.clang-format index 5035fb7d..679bbe1d 100644 --- a/.clang-format +++ b/.clang-format @@ -26,8 +26,7 @@ BinPackArguments: true BinPackParameters: true BitFieldColonSpacing: None BreakBeforeBinaryOperators: NonAssignment -BreakBeforeBraces: Custom -BreakBeforeConceptDeclarations: false +BreakBeforeConceptDeclarations: true BreakConstructorInitializers: BeforeComma BreakInheritanceList: AfterComma BreakStringLiterals: true @@ -58,10 +57,11 @@ IndentCaseBlocks: false IndentCaseLabels: true IndentExternBlock: AfterExternBlock IndentGotoLabels: true -IndentPPDirectives: AfterHash +IndentPPDirectives: BeforeHash IndentRequires: true IndentWidth: 4 IndentWrappedFunctionNames: false +InsertBraces: true KeepEmptyLinesAtTheStartOfBlocks: false LambdaBodyIndentation: OuterScope MaxEmptyLinesToKeep: 2 @@ -78,6 +78,7 @@ PenaltyReturnTypeOnItsOwnLine: 200 PointerAlignment: Left ReferenceAlignment: Left ReflowComments: true +RequiresClausePosition: WithPreceding SortIncludes: CaseInsensitive SortUsingDeclarations: true SpaceAfterCStyleCast: false diff --git a/.clang-tidy b/.clang-tidy index 9241f217..da83db9b 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,5 +1,5 @@ --- -Checks: '-*, readability-identifier-naming, clang-analyzer-*, clang-analyzer-cplusplus*, performance-*, bugprone-*, modernize-*, misc-unused-*,-bugprone-macro-parentheses, -modernize-use-trailing-return-type, -modernize-use-nodiscard, -modernize-use-default-member-init, -modernize-use-equals-default, -performance-unnecessary-value-param, -misc-unused-parameters, -bugprone-branch-clone, -modernize-avoid-c-arrays, -bugprone-easily-swappable-parameters' +Checks: '-*, readability-identifier-naming, clang-analyzer-*, clang-analyzer-cplusplus*, performance-*, bugprone-*, modernize-*, misc-unused-*,-bugprone-macro-parentheses, -modernize-use-trailing-return-type, -modernize-use-nodiscard, -modernize-use-default-member-init, -modernize-use-equals-default, -modernize-raw-string-literal -performance-unnecessary-value-param, -misc-unused-parameters, -bugprone-branch-clone, -modernize-avoid-c-arrays, -bugprone-easily-swappable-parameters' WarningsAsErrors: '' HeaderFilterRegex: 'Corresponding Header' FormatStyle: file diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 257a9fba..2ad7e2c8 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,9 +10,6 @@ on: pull_request: workflow_call: -env: - cache-version: 0 - jobs: Build: name: ${{ matrix.os-name }} (${{ matrix.compiler }}, ${{ matrix.config }}) @@ -32,34 +29,33 @@ jobs: - name: windows-clang os: windows-latest os-name: windows - compiler: clang + compiler: clang-16 cxx: clang-cl cc: clang-cl - name: linux-clang os: ubuntu-latest os-name: linux - compiler: clang + compiler: clang-16 cxx: clang++ cc: clang - name: linux-gcc os: ubuntu-latest os-name: linux - compiler: gcc - cxx: g++-10 - cc: gcc-10 + compiler: gcc-13 + cxx: g++ + cc: gcc - name: macos-clang - os: macos-latest + os: macos-14 os-name: macos - compiler: clang + compiler: clang-16 cxx: clang++ cc: clang steps: - name: Checkout repository - uses: actions/checkout@v2 - - - name: Init Submodules - uses: snickerbockers/submodules-init@v4 + uses: actions/checkout@v3 + with: + submodules: 'recursive' - name: Install dependencies if: ${{ matrix.os-name == 'linux'}} @@ -67,49 +63,29 @@ jobs: sudo apt-get update sudo apt-get install -y build-essential xz-utils curl libx11-dev xorg-dev libglu1-mesa-dev - - uses: ilammy/msvc-dev-cmd@v1 - if: ${{ matrix.compiler == 'msvc' }} - - - name: Cache LLVM - if: ${{ matrix.compiler == 'clang' }} - id: cache-llvm - uses: actions/cache@v2 - with: - path: ${{ runner.temp }}/llvm - key: llvm-15.0-${{ matrix.os-name }} - - name: Install LLVM - if: ${{ matrix.compiler == 'clang' }} - uses: KyleMayes/install-llvm-action@v1 + - name: Setup Cpp + uses: aminya/setup-cpp@v1 with: - version: "15.0" - directory: ${{ runner.temp }}/llvm - cached: ${{ steps.cache-llvm.outputs.cache-hit }} - - - - name: Download pre-built development LLVM for Rift - run: | - curl -L -o "${{ runner.temp }}/rift-llvm.zip" https://github.com/piperift/rift-llvm/releases/download/v14.0.5/llvm-${{ matrix.os-name }}-${{ matrix.config }}.zip - 7z x -o"${{ runner.temp }}/rift" "${{ runner.temp }}/rift-llvm.zip" - - - name: Get CMake - uses: lukka/get-cmake@latest - + compiler: ${{ matrix.compiler }} + vcvarsall: ${{ matrix.os-name == 'windows' }} + cmake: true + ninja: true - name: Cache Build - uses: actions/cache@v2 + uses: actions/cache@v3 with: path: Build key: ${{ matrix.os-name }}-${{ matrix.compiler }}-${{ matrix.config }}-build-${{ secrets.VCACHE}} - name: Configure - run: cmake -S . -B Build -DCMAKE_BUILD_TYPE=${{ matrix.config }} -DCMAKE_C_COMPILER=${{ matrix.cc }} -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DRIFT_LLVM_PATH='${{ runner.temp }}/rift/llvm' + run: cmake -GNinja -S . -B Build -DCMAKE_BUILD_TYPE=${{ matrix.config }} -DCMAKE_C_COMPILER=${{ matrix.cc }} -DCMAKE_CXX_COMPILER=${{ matrix.cxx }} -DRIFT_LLVM_PATH='${{ runner.temp }}/rift/llvm' - name: Build run: cmake --build Build --config ${{ matrix.config }} - name: Upload binaries as artifacts - uses: actions/upload-artifact@v2 - if: ${{ matrix.config == 'Release' && matrix.compiler == 'clang' }} # Only clang artifacts are stored + uses: actions/upload-artifact@v3 + if: ${{ matrix.config == 'Release' && contains(matrix.compiler, 'clang') }} # Only clang artifacts are stored with: name: rift-${{ matrix.os-name }} path: Build/Bin diff --git a/.gitignore b/.gitignore index 4d074fe4..6b99fa29 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,6 @@ Build Saved Testing -Extern/rift-llvm .vscode/c_cpp_properties.json /compile_commands.json diff --git a/.vscode/settings.json b/.vscode/settings.json index d2227d01..c2e5bc00 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,6 +3,7 @@ "cmake.configureOnOpen": true, "cmake.buildDirectory": "${workspaceFolder}/Build", "files.associations": { + "*.tmpl": "html", "cmath": "cpp", "algorithm": "cpp", "any": "cpp", @@ -155,7 +156,10 @@ "splines": "cpp", "typeindex": "cpp", "qtalignedmalloc": "cpp", - "*.traits": "cpp" + "*.traits": "cpp", + "span": "cpp", + "stdfloat": "cpp", + "cuchar": "cpp" }, "C_Cpp.default.configurationProvider": "ms-vscode.cmake-tools", "banditTestExplorer.testsuites": [ @@ -232,5 +236,8 @@ "LLVM" ] }, - "dotnet.defaultSolution": "disable" + "dotnet.defaultSolution": "disable", + "search.exclude": { + "**/.git": true + } } \ No newline at end of file diff --git a/Apps/CLI/CMakeLists.txt b/Apps/CLI/CMakeLists.txt index e2da1fb6..cc882cfa 100644 --- a/Apps/CLI/CMakeLists.txt +++ b/Apps/CLI/CMakeLists.txt @@ -1,17 +1,17 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_executable(RiftCLIExe Src/main.cpp) +add_executable(RiftCLI Src/main.cpp) -target_include_directories(RiftCLIExe PUBLIC Include) +target_include_directories(RiftCLI PUBLIC Include) file(GLOB_RECURSE CLI_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) -target_sources(RiftCLIExe PRIVATE ${CLI_SOURCE_FILES}) +target_sources(RiftCLI PRIVATE ${CLI_SOURCE_FILES}) -target_link_libraries(RiftCLIExe PUBLIC +target_link_libraries(RiftCLI PUBLIC CLI11 - RiftAST + RiftASTLib RiftCompilerModules ) -rift_module(RiftCLIExe) -set_target_properties(RiftCLIExe PROPERTIES OUTPUT_NAME "Rift") -set_icon(RiftCLIExe ../../Resources/Icon.ico) +rift_module(RiftCLI) +set_target_properties(RiftCLI PROPERTIES OUTPUT_NAME "Rift") +set_icon(RiftCLI Icon.ico) diff --git a/Apps/CLI/Icon.ico b/Apps/CLI/Icon.ico index 290fdaa5..11b4a077 100644 Binary files a/Apps/CLI/Icon.ico and b/Apps/CLI/Icon.ico differ diff --git a/Apps/CLI/Src/main.cpp b/Apps/CLI/Src/main.cpp index a620b4d5..35673652 100644 --- a/Apps/CLI/Src/main.cpp +++ b/Apps/CLI/Src/main.cpp @@ -1,6 +1,6 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved -#include +#include // Override as first include #include @@ -8,16 +8,16 @@ #include #include #include -#include #include -#include +#include #include -#include +#include +#include #include #include #include - +#include using namespace rift; @@ -45,7 +45,7 @@ namespace rift const Tag def = backends.IsEmpty() ? Tag::None() : backends[0]->GetName(); selected = def.AsString(); - auto stdDesc = Strings::Convert(desc); + auto stdDesc = Strings::Convert(desc); app.add_option("-b,--backend", selected, stdDesc, true); } @@ -65,15 +65,40 @@ namespace rift int main(int argc, char** argv) { - p::Initialize("Saved/Logs"); + p::Logger logger = p::Logger{.infoCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Info] {}\n", msg); + std::cout << text; + }, .warningCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Warning] {}\n", msg); + std::cout << text; + }, .errorCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Error] {}\n", msg); + std::cout << text; + }}; + + p::Initialize(&logger); + p::Info(p::PlatformPaths::GetUserSettingsPath()); EnableModule(); - EnableModule(); EnableModule(); EnableModule(); + CompilerConfig config; + CLI::App app{"Rift compiler"}; String path; app.add_option("-p,--project", path, "Project path")->required(); + app.add_option("-v,--verbose", config.verbose, "Verbose")->required(); + app.add_flag("-O0{0},-O1{1},-O2{2},-O3{3}", config.optimization, "Optimization") + ->expected(0, 3); String selectedBackendStr; @@ -84,18 +109,15 @@ int main(int argc, char** argv) TPtr backend = FindBackendByName(availableBackends, Tag(selectedBackendStr)); - ZoneScopedNC("CLI Execution", 0x459bd1); + ast::Tree ast; + ast::OpenProject(ast, path); - AST::Tree ast; - AST::OpenProject(ast, path); - - if (!AST::HasProject(ast)) + if (!ast::HasProject(ast)) { p::Error("Couldn't open project '{}'", p::ToString(path)); return 1; } - CompilerConfig config; Build(ast, config, backend); while (true) diff --git a/Apps/Editor/CMakeLists.txt b/Apps/Editor/CMakeLists.txt index f0c6150b..adc4a86f 100644 --- a/Apps/Editor/CMakeLists.txt +++ b/Apps/Editor/CMakeLists.txt @@ -1,18 +1,17 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_executable(RiftEditorExe Src/main.cpp) +add_executable(RiftEditor Src/main.cpp) -target_include_directories(RiftEditorExe PUBLIC Include) +target_include_directories(RiftEditor PUBLIC Include) file(GLOB_RECURSE RiftEditor_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) -target_sources(RiftEditorExe PRIVATE ${RiftEditor_SOURCE_FILES}) +target_sources(RiftEditor PRIVATE ${RiftEditor_SOURCE_FILES}) -target_link_libraries(RiftEditorExe PUBLIC +target_link_libraries(RiftEditor PUBLIC RiftCompilerModules - RiftEditor + RiftEditorLib RiftEditorModules ) -target_compile_definitions(RiftEditorExe PUBLIC RIFT_EDITOR=1) +target_compile_definitions(RiftEditor PUBLIC RIFT_EDITOR=1) -rift_module(RiftEditorExe) -set_target_properties(RiftEditorExe PROPERTIES OUTPUT_NAME "RiftEditor") -set_icon(RiftEditorExe Icon.ico) +rift_module(RiftEditor) +set_icon(RiftEditor Icon.ico) diff --git a/Apps/Editor/Icon.ico b/Apps/Editor/Icon.ico index 290fdaa5..11b4a077 100644 Binary files a/Apps/Editor/Icon.ico and b/Apps/Editor/Icon.ico differ diff --git a/Apps/Editor/Src/main.cpp b/Apps/Editor/Src/main.cpp index 82799da6..aafc9486 100644 --- a/Apps/Editor/Src/main.cpp +++ b/Apps/Editor/Src/main.cpp @@ -1,42 +1,59 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved -#include +#include // Override as first include #include #include #include -#include #include -#include +#include +#include #include - using namespace rift; - #ifndef RUN_AS_CLI -# define RUN_AS_CLI 1 + #define RUN_AS_CLI 1 #endif int RunEditor(StringView projectPath) { - p::Initialize("Saved/Logs"); + p::Logger logger = p::Logger{.infoCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Info] {}\n", msg); + std::cout << text; + }, .warningCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Warning] {}\n", msg); + std::cout << text; + }, .errorCallback = [](StringView msg) { + String text; + auto now = p::DateTime::Now(); + now.ToString("[%Y/%m/%d %H:%M:%S]", text); + p::Strings::FormatTo(text, "[Error] {}\n", msg); + std::cout << text; + }}; + + p::Initialize(&logger); EnableModule(); - EnableModule(); EnableModule(); EnableModule(); - const int result = Editor::Editor::Get().Run(projectPath); + const int result = editor::Editor::Get().Run(projectPath); p::Shutdown(); return result; } #if PLATFORM_WINDOWS && !RUN_AS_CLI -# pragma comment(linker, "/subsystem:windows") -# include + #pragma comment(linker, "/subsystem:windows") + #include int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow) { return RunEditor(__argc > 1 ? __argv[1] : StringView{}); diff --git a/CMake/LLVM.cmake b/CMake/LLVM.cmake deleted file mode 100644 index 6f7564fd..00000000 --- a/CMake/LLVM.cmake +++ /dev/null @@ -1,70 +0,0 @@ - -set(RIFT_DEFAULT_TO_INTERNAL_LLVM ${PLATFORM_WINDOWS} CACHE STRING "If true, use internal llvm build path. Default: true in Windows, false in Linux") -set(RIFT_INTERNAL_LLVM_PATH "${CMAKE_CURRENT_SOURCE_DIR}/Extern/rift-llvm") - -set(RIFT_LLVM_PATH_RELEASE "" CACHE STRING "Location of Rift LLVM installation to use on Release. CMake will try to find if this path is not set") -set(RIFT_LLVM_PATH_DEBUG "" CACHE STRING "Location of Rift LLVM installation to use on Debug. CMake will try to find if this path is not set") -set(RIFT_LLVM_PATH_MINSIZEREL "" CACHE STRING "Location of Rift LLVM installation to use on MinSizeRel. CMake will try to find if this path is not set") -set(RIFT_LLVM_PATH_RELWITHDEBINFO "" CACHE STRING "Location of Rift LLVM installation to use on RelWithDebInfo. CMake will try to find if this path is not set") -set(RIFT_LLVM_PATH "" CACHE STRING "Location of an external LLVM installation to use. Used if RIFT_LLVM_PATH_{CONFIG} is not set. If left empty, INTERNAL_RIFT_LLVM_PATH is used.") - -# Check if specific build type path is required -string(TOUPPER ${CMAKE_BUILD_TYPE} CMAKE_BUILD_TYPE_UPPER) -if (RIFT_LLVM_PATH STREQUAL "" AND NOT ${RIFT_LLVM_PATH_${CMAKE_BUILD_TYPE_UPPER}} STREQUAL "") - message(STATUS "Using RIFT_LLVM_PATH_${CMAKE_BUILD_TYPE_UPPER}") - set(RIFT_LLVM_PATH ${RIFT_LLVM_PATH_${CMAKE_BUILD_TYPE_UPPER}}) -endif() - -# Check if RIFT_LLVM_PATH should be used -if (NOT RIFT_LLVM_PATH STREQUAL "") - message(STATUS "Provided explicit LLVM path: ${RIFT_LLVM_PATH}") - set(RIFT_LLVM_BIN_PATH ${RIFT_LLVM_PATH}) -elseif (RIFT_DEFAULT_TO_INTERNAL_LLVM AND NOT RIFT_INTERNAL_LLVM_PATH STREQUAL "") - set(RIFT_LLVM_PATH ${RIFT_INTERNAL_LLVM_PATH}/build) - message(STATUS "Provided internal LLVM path: ${RIFT_LLVM_PATH}") - set(RIFT_LLVM_BIN_PATH ${RIFT_LLVM_PATH}/${CMAKE_BUILD_TYPE}) -else() - message(STATUS "LLVM path not provided. Will be searched in the system") - set(RIFT_LLVM_BIN_PATH ${RIFT_LLVM_PATH}) -endif() - -set(LLVM_DIR "${RIFT_LLVM_PATH}/lib/cmake/llvm") -set(Clang_DIR "${RIFT_LLVM_PATH}/lib/cmake/clang") - -find_package(LLVM REQUIRED CONFIG) -list(APPEND CMAKE_MODULE_PATH "${LLVM_CMAKE_DIR}") -include(AddLLVM) -message(STATUS "Found LLVM ${LLVM_PACKAGE_VERSION}") -message(STATUS "Using LLVMConfig.cmake in: ${LLVM_DIR}") - -find_package(Clang REQUIRED CONFIG) -list(APPEND CMAKE_MODULE_PATH "${CLANG_CMAKE_DIR}") -include(AddClang) -message(STATUS "Found CLANG ${CLANG_PACKAGE_VERSION}") -message(STATUS "Using CLANGConfig.cmake in: ${Clang_DIR}") - -separate_arguments(LLVM_DEFINITIONS_LIST NATIVE_COMMAND ${LLVM_DEFINITIONS}) -message(STATUS "LLVM_LIBS: ${LLVM_AVAILABLE_LIBS}") -message(STATUS "LLVM_INCLUDE_DIRS: ${LLVM_INCLUDE_DIRS}") -# Copyright 2015-2023 Piperift - All rights reserved - -message(STATUS "LLVM_DEFINITIONS: ${LLVM_DEFINITIONS_LIST}") -message(STATUS "CLANG_LIBS: ${CLANG_EXPORTED_TARGETS}") - - -add_library(RiftLLVM INTERFACE) -target_include_directories(RiftLLVM INTERFACE ${LLVM_INCLUDE_DIRS}) -llvm_map_components_to_libnames(llvm_libs core support x86asmparser x86codegen) -target_link_libraries(RiftLLVM INTERFACE ${llvm_libs}) -target_compile_definitions(RiftLLVM INTERFACE ${LLVM_DEFINITIONS_LIST} -DNOMINMAX) -#if(COMPILER_CLANG) - #target_compile_options(RiftLLVM INTERFACE -fms-compatibility-version=14.20) -#endif() -pipe_target_disable_all_warnings(RiftLLVM INTERFACE) - -add_library(RiftClang INTERFACE) -target_include_directories(RiftClang INTERFACE ${CLANG_INCLUDE_DIRS}) -target_link_libraries(RiftClang INTERFACE libclang) -target_compile_definitions(RiftClang INTERFACE ${CLANG_DEFINITIONS_LIST} -DNOMINMAX) -target_link_libraries(RiftClang INTERFACE RiftLLVM) -pipe_target_disable_all_warnings(RiftClang INTERFACE) diff --git a/CMake/Util.cmake b/CMake/Util.cmake index e4d2a97d..0d3cf469 100644 --- a/CMake/Util.cmake +++ b/CMake/Util.cmake @@ -4,6 +4,7 @@ function(rift_module target) pipe_target_define_platform(${target}) pipe_target_shared_output_directory(${target}) pipe_target_enable_CPP20(${target}) + pipe_target_disable_rtti(${target} PRIVATE) set_target_properties(${target} PROPERTIES FOLDER Rift) endfunction(rift_module) diff --git a/CMakeCache.txt b/CMakeCache.txt new file mode 100644 index 00000000..f5e9e7da --- /dev/null +++ b/CMakeCache.txt @@ -0,0 +1,362 @@ +# This is the CMakeCache file. +# For build in directory: /home/deck/Documents/rift +# It was generated by CMake: /home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/bin/cmake +# You can edit this file to change values found and used by cmake. +# If you do not want to change any of the values, simply exit the editor. +# If you do want to change a value, simply edit, save, and exit the editor. +# The syntax for the file is as follows: +# KEY:TYPE=VALUE +# KEY is the name of a variable in the cache. +# TYPE is a hint to GUIs for the type of VALUE, DO NOT EDIT TYPE!. +# VALUE is the current value for the KEY. + +######################## +# EXTERNAL cache entries +######################## + +//Path to a program. +CMAKE_ADDR2LINE:FILEPATH=/usr/bin/addr2line + +//Path to a program. +CMAKE_AR:FILEPATH=/usr/bin/ar + +//Choose the type of build, options are: None Debug Release RelWithDebInfo +// MinSizeRel ... +CMAKE_BUILD_TYPE:STRING= + +//CXX compiler +CMAKE_CXX_COMPILER:FILEPATH=CMAKE_CXX_COMPILER-NOTFOUND + +//Flags used by the CXX compiler during all build types. +CMAKE_CXX_FLAGS:STRING= + +//Flags used by the CXX compiler during DEBUG builds. +CMAKE_CXX_FLAGS_DEBUG:STRING= + +//Flags used by the CXX compiler during MINSIZEREL builds. +CMAKE_CXX_FLAGS_MINSIZEREL:STRING= + +//Flags used by the CXX compiler during RELEASE builds. +CMAKE_CXX_FLAGS_RELEASE:STRING= + +//Flags used by the CXX compiler during RELWITHDEBINFO builds. +CMAKE_CXX_FLAGS_RELWITHDEBINFO:STRING= + +//C compiler +CMAKE_C_COMPILER:FILEPATH=CMAKE_C_COMPILER-NOTFOUND + +//Flags used by the C compiler during all build types. +CMAKE_C_FLAGS:STRING= + +//Flags used by the C compiler during DEBUG builds. +CMAKE_C_FLAGS_DEBUG:STRING= + +//Flags used by the C compiler during MINSIZEREL builds. +CMAKE_C_FLAGS_MINSIZEREL:STRING= + +//Flags used by the C compiler during RELEASE builds. +CMAKE_C_FLAGS_RELEASE:STRING= + +//Flags used by the C compiler during RELWITHDEBINFO builds. +CMAKE_C_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_DLLTOOL:FILEPATH=CMAKE_DLLTOOL-NOTFOUND + +//Flags used by the linker during all build types. +CMAKE_EXE_LINKER_FLAGS:STRING= + +//Flags used by the linker during DEBUG builds. +CMAKE_EXE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during MINSIZEREL builds. +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during RELEASE builds. +CMAKE_EXE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during RELWITHDEBINFO builds. +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Value Computed by CMake. +CMAKE_FIND_PACKAGE_REDIRECTS_DIR:STATIC=/home/deck/Documents/rift/CMakeFiles/pkgRedirects + +//Install path prefix, prepended onto install directories. +CMAKE_INSTALL_PREFIX:PATH=/usr/local + +//Path to a program. +CMAKE_LINKER:FILEPATH=/usr/bin/ld + +//Program used to build from build.ninja files. +CMAKE_MAKE_PROGRAM:FILEPATH=/home/linuxbrew/.linuxbrew/bin/ninja + +//Flags used by the linker during the creation of modules during +// all build types. +CMAKE_MODULE_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of modules during +// DEBUG builds. +CMAKE_MODULE_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of modules during +// MINSIZEREL builds. +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of modules during +// RELEASE builds. +CMAKE_MODULE_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of modules during +// RELWITHDEBINFO builds. +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_NM:FILEPATH=/usr/bin/nm + +//Path to a program. +CMAKE_OBJCOPY:FILEPATH=/usr/bin/objcopy + +//Path to a program. +CMAKE_OBJDUMP:FILEPATH=/usr/bin/objdump + +//Value Computed by CMake +CMAKE_PROJECT_DESCRIPTION:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_HOMEPAGE_URL:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_NAME:STATIC=Rift + +//Value Computed by CMake +CMAKE_PROJECT_VERSION:STATIC=0.1 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_MAJOR:STATIC=0 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_MINOR:STATIC=1 + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_PATCH:STATIC= + +//Value Computed by CMake +CMAKE_PROJECT_VERSION_TWEAK:STATIC= + +//Path to a program. +CMAKE_RANLIB:FILEPATH=/usr/bin/ranlib + +//Path to a program. +CMAKE_READELF:FILEPATH=/usr/bin/readelf + +//Flags used by the linker during the creation of shared libraries +// during all build types. +CMAKE_SHARED_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of shared libraries +// during DEBUG builds. +CMAKE_SHARED_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of shared libraries +// during MINSIZEREL builds. +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELEASE builds. +CMAKE_SHARED_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of shared libraries +// during RELWITHDEBINFO builds. +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//If set, runtime paths are not added when installing shared libraries, +// but are added when building. +CMAKE_SKIP_INSTALL_RPATH:BOOL=NO + +//If set, runtime paths are not added when using shared libraries. +CMAKE_SKIP_RPATH:BOOL=NO + +//Flags used by the linker during the creation of static libraries +// during all build types. +CMAKE_STATIC_LINKER_FLAGS:STRING= + +//Flags used by the linker during the creation of static libraries +// during DEBUG builds. +CMAKE_STATIC_LINKER_FLAGS_DEBUG:STRING= + +//Flags used by the linker during the creation of static libraries +// during MINSIZEREL builds. +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELEASE builds. +CMAKE_STATIC_LINKER_FLAGS_RELEASE:STRING= + +//Flags used by the linker during the creation of static libraries +// during RELWITHDEBINFO builds. +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO:STRING= + +//Path to a program. +CMAKE_STRIP:FILEPATH=/usr/bin/strip + +//Path to a program. +CMAKE_TAPI:FILEPATH=CMAKE_TAPI-NOTFOUND + +//If this value is on, makefiles will be generated without the +// .SILENT directive, and all commands will be echoed to the console +// during the make. This is useful for debugging only. With Visual +// Studio IDE projects all commands are done without /nologo. +CMAKE_VERBOSE_MAKEFILE:BOOL=FALSE + +//Value Computed by CMake +Rift_BINARY_DIR:STATIC=/home/deck/Documents/rift + +//Value Computed by CMake +Rift_IS_TOP_LEVEL:STATIC=ON + +//Value Computed by CMake +Rift_SOURCE_DIR:STATIC=/home/deck/Documents/rift + + +######################## +# INTERNAL cache entries +######################## + +//ADVANCED property for variable: CMAKE_ADDR2LINE +CMAKE_ADDR2LINE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_AR +CMAKE_AR-ADVANCED:INTERNAL=1 +//This is the directory where this CMakeCache.txt was created +CMAKE_CACHEFILE_DIR:INTERNAL=/home/deck/Documents/rift +//Major version of cmake used to create the current loaded cache +CMAKE_CACHE_MAJOR_VERSION:INTERNAL=3 +//Minor version of cmake used to create the current loaded cache +CMAKE_CACHE_MINOR_VERSION:INTERNAL=28 +//Patch version of cmake used to create the current loaded cache +CMAKE_CACHE_PATCH_VERSION:INTERNAL=1 +//Path to CMake executable. +CMAKE_COMMAND:INTERNAL=/home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/bin/cmake +//Path to cpack program executable. +CMAKE_CPACK_COMMAND:INTERNAL=/home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/bin/cpack +//Path to ctest program executable. +CMAKE_CTEST_COMMAND:INTERNAL=/home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/bin/ctest +//ADVANCED property for variable: CMAKE_CXX_COMPILER +CMAKE_CXX_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS +CMAKE_CXX_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_DEBUG +CMAKE_CXX_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_MINSIZEREL +CMAKE_CXX_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELEASE +CMAKE_CXX_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_CXX_FLAGS_RELWITHDEBINFO +CMAKE_CXX_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_COMPILER +CMAKE_C_COMPILER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS +CMAKE_C_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_DEBUG +CMAKE_C_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_MINSIZEREL +CMAKE_C_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELEASE +CMAKE_C_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_C_FLAGS_RELWITHDEBINFO +CMAKE_C_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_DLLTOOL +CMAKE_DLLTOOL-ADVANCED:INTERNAL=1 +//Path to cache edit program executable. +CMAKE_EDIT_COMMAND:INTERNAL=/home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/bin/ccmake +//Executable file format +CMAKE_EXECUTABLE_FORMAT:INTERNAL=Unknown +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS +CMAKE_EXE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_DEBUG +CMAKE_EXE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_MINSIZEREL +CMAKE_EXE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELEASE +CMAKE_EXE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//Name of external makefile project generator. +CMAKE_EXTRA_GENERATOR:INTERNAL= +//Name of generator. +CMAKE_GENERATOR:INTERNAL=Ninja +//Generator instance identifier. +CMAKE_GENERATOR_INSTANCE:INTERNAL= +//Name of generator platform. +CMAKE_GENERATOR_PLATFORM:INTERNAL= +//Name of generator toolset. +CMAKE_GENERATOR_TOOLSET:INTERNAL= +//Source directory with the top level CMakeLists.txt file for this +// project +CMAKE_HOME_DIRECTORY:INTERNAL=/home/deck/Documents/rift +//Install .so files without execute permission. +CMAKE_INSTALL_SO_NO_EXE:INTERNAL=0 +//ADVANCED property for variable: CMAKE_LINKER +CMAKE_LINKER-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MAKE_PROGRAM +CMAKE_MAKE_PROGRAM-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS +CMAKE_MODULE_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_DEBUG +CMAKE_MODULE_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL +CMAKE_MODULE_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELEASE +CMAKE_MODULE_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_MODULE_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_NM +CMAKE_NM-ADVANCED:INTERNAL=1 +//number of local generators +CMAKE_NUMBER_OF_MAKEFILES:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJCOPY +CMAKE_OBJCOPY-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_OBJDUMP +CMAKE_OBJDUMP-ADVANCED:INTERNAL=1 +//Platform information initialized +CMAKE_PLATFORM_INFO_INITIALIZED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_RANLIB +CMAKE_RANLIB-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_READELF +CMAKE_READELF-ADVANCED:INTERNAL=1 +//Path to CMake installation. +CMAKE_ROOT:INTERNAL=/home/linuxbrew/.linuxbrew/Cellar/cmake/3.28.1/share/cmake +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS +CMAKE_SHARED_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_DEBUG +CMAKE_SHARED_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL +CMAKE_SHARED_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELEASE +CMAKE_SHARED_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_INSTALL_RPATH +CMAKE_SKIP_INSTALL_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_SKIP_RPATH +CMAKE_SKIP_RPATH-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS +CMAKE_STATIC_LINKER_FLAGS-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_DEBUG +CMAKE_STATIC_LINKER_FLAGS_DEBUG-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL +CMAKE_STATIC_LINKER_FLAGS_MINSIZEREL-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELEASE +CMAKE_STATIC_LINKER_FLAGS_RELEASE-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO +CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_STRIP +CMAKE_STRIP-ADVANCED:INTERNAL=1 +//ADVANCED property for variable: CMAKE_TAPI +CMAKE_TAPI-ADVANCED:INTERNAL=1 +//uname command +CMAKE_UNAME:INTERNAL=/usr/bin/uname +//ADVANCED property for variable: CMAKE_VERBOSE_MAKEFILE +CMAKE_VERBOSE_MAKEFILE-ADVANCED:INTERNAL=1 +//linker supports push/pop state +_CMAKE_LINKER_PUSHPOP_STATE_SUPPORTED:INTERNAL=TRUE + diff --git a/CMakeLists.txt b/CMakeLists.txt index d3eb20fb..8acc9544 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,6 +26,7 @@ else() endif() option(BUILD_SHARED_LIBS "Build shared libraries" ON) option(BUILD_STATIC_LIBS "Build static libraries" ON) +option(RIFT_BUILD_EDITOR "Build Editor" ON) option(RIFT_BUILD_TESTS "Build Rift and Core tests" ${RIFT_IS_PROJECT}) @@ -36,14 +37,15 @@ include(CMake/Util.cmake) include(CMake/SetIcon.cmake) include(CMake/CheckClangTools.cmake) -include(CMake/LLVM.cmake) add_subdirectory(Extern) add_subdirectory(Libs) # Executables add_subdirectory(Apps/CLI) -add_subdirectory(Apps/Editor) +if (RIFT_BUILD_EDITOR) + add_subdirectory(Apps/Editor) +endif() # Tests if(BUILD_TESTING AND RIFT_BUILD_TESTS) diff --git a/Examples/CodeGuidelines.cpp b/Examples/CodeGuidelines.cpp index f14a37a7..d886e9d8 100644 --- a/Examples/CodeGuidelines.cpp +++ b/Examples/CodeGuidelines.cpp @@ -1,2 +1,2 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved // Coding standards for Rift and Rift-Core diff --git a/Examples/CodeGuidelines.h b/Examples/CodeGuidelines.h index ca2377f0..5800a972 100644 --- a/Examples/CodeGuidelines.h +++ b/Examples/CodeGuidelines.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved // Coding standards for Rift and Rift-Core // [header.format] Use .h for header files and .cpp for source files diff --git a/Examples/Project/Main.rf b/Examples/Project/Main.rf new file mode 100644 index 00000000..a52d1890 --- /dev/null +++ b/Examples/Project/Main.rf @@ -0,0 +1,39 @@ +{ + "type": "Static", + "count": 3, + "components": { + "CChild": { + "0": -1, + "1": 0, + "2": 0 + }, + "CDeclVariable": { + "2": {} + }, + "CDeclFunction": { + "1": {} + }, + "CNodePosition": { + "1": { + "x": 0.0, + "y": 0.0 + } + }, + "CNamespace": { + "0": "Main", + "1": "Main", + "2": "NewVariable" + }, + "CParent": { + "0": [ + 1, + 2 + ], + "1": [], + "2": [] + }, + "CStmtOutput": { + "1": -1 + } + } +} \ No newline at end of file diff --git a/Examples/Project/TestStruct.rf b/Examples/Project/TestStruct.rf index 46464437..ba274ed7 100644 --- a/Examples/Project/TestStruct.rf +++ b/Examples/Project/TestStruct.rf @@ -1,15 +1,15 @@ { "type": "Struct", "count": 1, - "roots": [ - 0 - ], "components": { "CChild": { "0": -1 }, "CNamespace": { "0": "TestStruct" + }, + "CParent": { + "0": [] } } } \ No newline at end of file diff --git a/Examples/Project/Welcome.rf b/Examples/Project/Welcome.rf index 0383c77c..97598d4e 100644 --- a/Examples/Project/Welcome.rf +++ b/Examples/Project/Welcome.rf @@ -118,10 +118,11 @@ "9": [ "U32" ], - "10": [], + "10": [ + "I64" + ], "11": [ - "TestProject", - "TestStruct" + "I64" ] }, "CNodePosition": { @@ -165,8 +166,8 @@ "CNamespace": { "0": "Welcome", "1": "Print", - "10": "class", - "11": "struct" + "10": "in1", + "11": "in2" }, "CParent": { "0": [ diff --git a/Examples/Project/imgui.ini b/Examples/Project/imgui.ini deleted file mode 100644 index 575ebe25..00000000 --- a/Examples/Project/imgui.ini +++ /dev/null @@ -1,12 +0,0 @@ -[Window][Debug##Default] -Pos=60,60 -Size=400,400 -Collapsed=0 - -[Window][Project Manager] -Pos=340,250 -Size=600,400 -Collapsed=0 - -[Docking][Data] - diff --git a/Examples/Project/stdio.rf b/Examples/Project/stdio.rf new file mode 100644 index 00000000..3dae6375 --- /dev/null +++ b/Examples/Project/stdio.rf @@ -0,0 +1,9 @@ +{ + "type": "CStatic", + "count": 1, + "components": { + "CNamespace": { + "0": "stdio" + } + } +} \ No newline at end of file diff --git a/Extern/CMakeLists.txt b/Extern/CMakeLists.txt index ca38d749..8e1f8547 100644 --- a/Extern/CMakeLists.txt +++ b/Extern/CMakeLists.txt @@ -13,36 +13,42 @@ set(CLI11_BUILD_TESTS OFF CACHE BOOL "Build CLI11 tests") set(CMAKE_POLICY_DEFAULT_CMP0054 NEW) add_subdirectory(CLI11) -find_package(OpenGL REQUIRED) -add_library(gl3w STATIC gl3w/GL/gl3w.c) -target_include_directories(gl3w PUBLIC gl3w) -target_link_libraries(gl3w INTERFACE OpenGL::GL OpenGL::GLU) - -set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "Build the GLFW example programs") -set(GLFW_BUILD_TESTS OFF CACHE BOOL "Build the GLFW test programs") -set(GLFW_BUILD_DOCS OFF CACHE BOOL "Build the GLFW documentation") -add_subdirectory(glfw) - -# Imgui -add_library(imgui STATIC) -target_include_directories(imgui PUBLIC imgui) -target_sources(imgui PRIVATE - imgui/imgui.cpp - imgui/imgui_demo.cpp - imgui/imgui_draw.cpp - imgui/imgui_tables.cpp - imgui/imgui_widgets.cpp - imgui/misc/cpp/imgui_stdlib.cpp - imgui/misc/fonts/binary_to_compressed_c.cpp - imgui/backends/imgui_impl_glfw.cpp - imgui/backends/imgui_impl_opengl3.cpp -) -pipe_target_enable_CPP20(imgui) -set_target_properties (imgui PROPERTIES FOLDER Extern) -target_link_libraries(imgui PRIVATE glfw gl3w) - -add_library(IconFontCppHeaders INTERFACE) -target_include_directories(IconFontCppHeaders INTERFACE IconFontCppHeaders) + +if (RIFT_BUILD_EDITOR) + add_library(stb_image INTERFACE) + target_include_directories(stb_image INTERFACE stb) + + + find_package(OpenGL REQUIRED) + add_library(gl3w STATIC gl3w/GL/gl3w.c) + target_include_directories(gl3w PUBLIC gl3w) + target_link_libraries(gl3w INTERFACE OpenGL::GL OpenGL::GLU) + + set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "Build the GLFW example programs") + set(GLFW_BUILD_TESTS OFF CACHE BOOL "Build the GLFW test programs") + set(GLFW_BUILD_DOCS OFF CACHE BOOL "Build the GLFW documentation") + add_subdirectory(glfw) + + # Imgui + add_library(imgui STATIC) + target_include_directories(imgui PUBLIC imgui) + target_sources(imgui PRIVATE + imgui/imgui.cpp + imgui/imgui_demo.cpp + imgui/imgui_draw.cpp + imgui/imgui_tables.cpp + imgui/imgui_widgets.cpp + imgui/misc/fonts/binary_to_compressed_c.cpp + imgui/backends/imgui_impl_glfw.cpp + imgui/backends/imgui_impl_opengl3.cpp + ) + pipe_target_enable_CPP20(imgui) + set_target_properties (imgui PROPERTIES FOLDER Extern) + target_link_libraries(imgui PRIVATE glfw gl3w) + + add_library(IconFontCppHeaders INTERFACE) + target_include_directories(IconFontCppHeaders INTERFACE IconFontCppHeaders) +endif() set(TF_BUILD_TESTS OFF CACHE BOOL "Enables builds of tests") @@ -52,15 +58,16 @@ pipe_target_disable_all_warnings(Taskflow INTERFACE) # MIR +add_library(mir STATIC) +target_sources(mir PRIVATE mir/mir.c mir/mir-gen.c mir/c2mir/c2mir.c) +target_include_directories(mir PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/mir) + include(FindThreads) if(Threads_FOUND) - link_libraries(${CMAKE_THREAD_LIBS_INIT}) -endif() -add_library(mir OBJECT mir/mir.c mir/mir-gen.c mir/c2mir/c2mir.c mir/mir.h mir/mir-gen.h mir/c2mir/c2mir.h) -target_include_directories(mir PUBLIC mir) -if(Threads_FOUND) + target_link_libraries(mir PUBLIC ${CMAKE_THREAD_LIBS_INIT}) target_compile_definitions(mir PUBLIC "MIR_PARALLEL_GEN") endif() + if(NOT WIN32) target_compile_options(mir PRIVATE $<$:-O3> @@ -69,20 +76,14 @@ if(NOT WIN32) target_compile_options(mir PRIVATE -std=gnu11 -Wno-abi -fsigned-char -fPIC) endif() -include(CheckCCompilerFlag) -if(CMAKE_COMPILER_IS_GNUCC) - check_c_compiler_flag(-fno-tree-sra NO_TREE_SRA) - if (NO_TREE_SRA) - target_compile_options(mir PRIVATE -fno-tree-sra) - endif() - check_c_compiler_flag(-fno-ipa-cp-clone NO_IPA_CP_CLONE) - if (NO_IPA_CP_CLONE) - target_compile_options(mir PRIVATE -fno-ipa-cp-clone) - endif() -endif() - -# ------------------ LIBMIR ----------------------- -add_library(mir_static STATIC) -target_link_libraries(mir_static PRIVATE mir) -target_include_directories(mir_static PUBLIC mir) - +#include(CheckCCompilerFlag) +#if(CMAKE_COMPILER_IS_GNUCC) +# check_c_compiler_flag(-fno-tree-sra NO_TREE_SRA) +# if (NO_TREE_SRA) +# target_compile_options(mir PRIVATE -fno-tree-sra) +# endif() +# check_c_compiler_flag(-fno-ipa-cp-clone NO_IPA_CP_CLONE) +# if (NO_IPA_CP_CLONE) +# target_compile_options(mir PRIVATE -fno-ipa-cp-clone) +# endif() +#endif() diff --git a/Extern/IconFontCppHeaders b/Extern/IconFontCppHeaders index 8a7a57fa..96c8d39d 160000 --- a/Extern/IconFontCppHeaders +++ b/Extern/IconFontCppHeaders @@ -1 +1 @@ -Subproject commit 8a7a57fa7b4b39b9f8436e3227ced13624028568 +Subproject commit 96c8d39dee3eb33a64e42eee0d8f3ca40320df78 diff --git a/Extern/Pipe b/Extern/Pipe index 918e8bfe..ff33f777 160000 --- a/Extern/Pipe +++ b/Extern/Pipe @@ -1 +1 @@ -Subproject commit 918e8bfec5c1aef487c7cea81704f31226d1d682 +Subproject commit ff33f777a8260e1b3ba1ad04dc7e43a0b6b8bcb3 diff --git a/Extern/glfw b/Extern/glfw index b43c122d..7b6aead9 160000 --- a/Extern/glfw +++ b/Extern/glfw @@ -1 +1 @@ -Subproject commit b43c122dd194d74996d76c574a46d4bc23d6c7b0 +Subproject commit 7b6aead9fb88b3623e3b3725ebb42670cbe4c579 diff --git a/Extern/imgui b/Extern/imgui index bac748fa..e391fe2e 160000 --- a/Extern/imgui +++ b/Extern/imgui @@ -1 +1 @@ -Subproject commit bac748fa95ac003c7b354139980f8b4b7f6ac5da +Subproject commit e391fe2e66eb1c96b1624ae8444dc64c23146ef4 diff --git a/Extern/stb/stb_image.h b/Extern/stb/stb_image.h new file mode 100644 index 00000000..a632d543 --- /dev/null +++ b/Extern/stb/stb_image.h @@ -0,0 +1,7985 @@ +/* stb_image - v2.29 - public domain image loader - http://nothings.org/stb + no warranty implied; use at your own risk + + Do this: + #define STB_IMAGE_IMPLEMENTATION + before you include this file in *one* C or C++ file to create the implementation. + + // i.e. it should look like this: + #include ... + #include ... + #include ... + #define STB_IMAGE_IMPLEMENTATION + #include "stb_image.h" + + You can #define STBI_ASSERT(x) before the #include to avoid using assert.h. + And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free + + + QUICK NOTES: + Primarily of interest to game developers and other people who can + avoid problematic images and only need the trivial interface + + JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) + PNG 1/2/4/8/16-bit-per-channel + + TGA (not sure what subset, if a subset) + BMP non-1bpp, non-RLE + PSD (composited view only, no extra channels, 8/16 bit-per-channel) + + GIF (*comp always reports as 4-channel) + HDR (radiance rgbE format) + PIC (Softimage PIC) + PNM (PPM and PGM binary only) + + Animated GIF still needs a proper API, but here's one way to do it: + http://gist.github.com/urraka/685d9a6340b26b830d49 + + - decode from memory or through FILE (define STBI_NO_STDIO to remove code) + - decode from arbitrary I/O callbacks + - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON) + + Full documentation under "DOCUMENTATION" below. + + +LICENSE + + See end of file for license information. + +RECENT REVISION HISTORY: + + 2.29 (2023-05-xx) optimizations + 2.28 (2023-01-29) many error fixes, security errors, just tons of stuff + 2.27 (2021-07-11) document stbi_info better, 16-bit PNM support, bug fixes + 2.26 (2020-07-13) many minor fixes + 2.25 (2020-02-02) fix warnings + 2.24 (2020-02-02) fix warnings; thread-local failure_reason and flip_vertically + 2.23 (2019-08-11) fix clang static analysis warning + 2.22 (2019-03-04) gif fixes, fix warnings + 2.21 (2019-02-25) fix typo in comment + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) bugfix, 1-bit BMP, 16-bitness query, fix warnings + 2.16 (2017-07-23) all functions have 16-bit variants; optimizations; bugfixes + 2.15 (2017-03-18) fix png-1,2,4; all Imagenet JPGs; no runtime SSE detection on GCC + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-12-04) experimental 16-bit API, only for PNG so far; fixes + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) 16-bit PNGS; enable SSE2 in non-gcc x64 + RGB-format JPEG; remove white matting in PSD; + allocate large structures on the stack; + correct channel count for PNG & BMP + 2.10 (2016-01-22) avoid warning introduced in 2.09 + 2.09 (2016-01-16) 16-bit TGA; comments in PNM files; STBI_REALLOC_SIZED + + See end of file for full revision history. + + + ============================ Contributors ========================= + + Image formats Extensions, features + Sean Barrett (jpeg, png, bmp) Jetro Lauha (stbi_info) + Nicolas Schulz (hdr, psd) Martin "SpartanJ" Golini (stbi_info) + Jonathan Dummer (tga) James "moose2000" Brown (iPhone PNG) + Jean-Marc Lienher (gif) Ben "Disch" Wenger (io callbacks) + Tom Seddon (pic) Omar Cornut (1/2/4-bit PNG) + Thatcher Ulrich (psd) Nicolas Guillemot (vertical flip) + Ken Miller (pgm, ppm) Richard Mitton (16-bit PSD) + github:urraka (animated gif) Junggon Kim (PNM comments) + Christopher Forseth (animated gif) Daniel Gibson (16-bit TGA) + socks-the-fox (16-bit PNG) + Jeremy Sawicki (handle all ImageNet JPGs) + Optimizations & bugfixes Mikhail Morozov (1-bit BMP) + Fabian "ryg" Giesen Anael Seghezzi (is-16-bit query) + Arseny Kapoulkine Simon Breuss (16-bit PNM) + John-Mark Allen + Carmelo J Fdez-Aguera + + Bug & warning fixes + Marc LeBlanc David Woo Guillaume George Martins Mozeiko + Christpher Lloyd Jerry Jansson Joseph Thomson Blazej Dariusz Roszkowski + Phil Jordan Dave Moore Roy Eltham + Hayaki Saito Nathan Reed Won Chun + Luke Graham Johan Duparc Nick Verigakis the Horde3D community + Thomas Ruf Ronny Chevalier github:rlyeh + Janez Zemva John Bartholomew Michal Cichon github:romigrou + Jonathan Blow Ken Hamada Tero Hanninen github:svdijk + Eugene Golushkov Laurent Gomila Cort Stratton github:snagar + Aruelien Pocheville Sergio Gonzalez Thibault Reuille github:Zelex + Cass Everitt Ryamond Barbiero github:grim210 + Paul Du Bois Engin Manap Aldo Culquicondor github:sammyhw + Philipp Wiesemann Dale Weiler Oriol Ferrer Mesia github:phprus + Josh Tobin Neil Bickford Matthew Gregan github:poppolopoppo + Julian Raschke Gregory Mullen Christian Floisand github:darealshinji + Baldur Karlsson Kevin Schmidt JR Smith github:Michaelangel007 + Brad Weinberger Matvey Cherevko github:mosra + Luca Sas Alexander Veselov Zack Middleton [reserved] + Ryan C. Gordon [reserved] [reserved] + DO NOT ADD YOUR NAME HERE + + Jacko Dirks + + To add your name to the credits, pick a random blank space in the middle and fill it. + 80% of merge conflicts on stb PRs are due to people adding their name at the end + of the credits. +*/ + +#ifndef STBI_INCLUDE_STB_IMAGE_H +#define STBI_INCLUDE_STB_IMAGE_H + +// DOCUMENTATION +// +// Limitations: +// - no 12-bit-per-channel JPEG +// - no JPEGs with arithmetic coding +// - GIF always returns *comp=4 +// +// Basic usage (see HDR discussion below for HDR usage): +// int x,y,n; +// unsigned char *data = stbi_load(filename, &x, &y, &n, 0); +// // ... process data if not NULL ... +// // ... x = width, y = height, n = # 8-bit components per pixel ... +// // ... replace '0' with '1'..'4' to force that many components per pixel +// // ... but 'n' will always be the number that it would have been if you said 0 +// stbi_image_free(data); +// +// Standard parameters: +// int *x -- outputs image width in pixels +// int *y -- outputs image height in pixels +// int *channels_in_file -- outputs # of image components in image file +// int desired_channels -- if non-zero, # of image components requested in result +// +// The return value from an image loader is an 'unsigned char *' which points +// to the pixel data, or NULL on an allocation failure or if the image is +// corrupt or invalid. The pixel data consists of *y scanlines of *x pixels, +// with each pixel consisting of N interleaved 8-bit components; the first +// pixel pointed to is top-left-most in the image. There is no padding between +// image scanlines or between pixels, regardless of format. The number of +// components N is 'desired_channels' if desired_channels is non-zero, or +// *channels_in_file otherwise. If desired_channels is non-zero, +// *channels_in_file has the number of components that _would_ have been +// output otherwise. E.g. if you set desired_channels to 4, you will always +// get RGBA output, but you can check *channels_in_file to see if it's trivially +// opaque because e.g. there were only 3 channels in the source image. +// +// An output image with N components has the following components interleaved +// in this order in each pixel: +// +// N=#comp components +// 1 grey +// 2 grey, alpha +// 3 red, green, blue +// 4 red, green, blue, alpha +// +// If image loading fails for any reason, the return value will be NULL, +// and *x, *y, *channels_in_file will be unchanged. The function +// stbi_failure_reason() can be queried for an extremely brief, end-user +// unfriendly explanation of why the load failed. Define STBI_NO_FAILURE_STRINGS +// to avoid compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly +// more user-friendly ones. +// +// Paletted PNG, BMP, GIF, and PIC images are automatically depalettized. +// +// To query the width, height and component count of an image without having to +// decode the full file, you can use the stbi_info family of functions: +// +// int x,y,n,ok; +// ok = stbi_info(filename, &x, &y, &n); +// // returns ok=1 and sets x, y, n if image is a supported format, +// // 0 otherwise. +// +// Note that stb_image pervasively uses ints in its public API for sizes, +// including sizes of memory buffers. This is now part of the API and thus +// hard to change without causing breakage. As a result, the various image +// loaders all have certain limits on image size; these differ somewhat +// by format but generally boil down to either just under 2GB or just under +// 1GB. When the decoded image would be larger than this, stb_image decoding +// will fail. +// +// Additionally, stb_image will reject image files that have any of their +// dimensions set to a larger value than the configurable STBI_MAX_DIMENSIONS, +// which defaults to 2**24 = 16777216 pixels. Due to the above memory limit, +// the only way to have an image with such dimensions load correctly +// is for it to have a rather extreme aspect ratio. Either way, the +// assumption here is that such larger images are likely to be malformed +// or malicious. If you do need to load an image with individual dimensions +// larger than that, and it still fits in the overall size limit, you can +// #define STBI_MAX_DIMENSIONS on your own to be something larger. +// +// =========================================================================== +// +// UNICODE: +// +// If compiling for Windows and you wish to use Unicode filenames, compile +// with +// #define STBI_WINDOWS_UTF8 +// and pass utf8-encoded filenames. Call stbi_convert_wchar_to_utf8 to convert +// Windows wchar_t filenames to utf8. +// +// =========================================================================== +// +// Philosophy +// +// stb libraries are designed with the following priorities: +// +// 1. easy to use +// 2. easy to maintain +// 3. good performance +// +// Sometimes I let "good performance" creep up in priority over "easy to maintain", +// and for best performance I may provide less-easy-to-use APIs that give higher +// performance, in addition to the easy-to-use ones. Nevertheless, it's important +// to keep in mind that from the standpoint of you, a client of this library, +// all you care about is #1 and #3, and stb libraries DO NOT emphasize #3 above all. +// +// Some secondary priorities arise directly from the first two, some of which +// provide more explicit reasons why performance can't be emphasized. +// +// - Portable ("ease of use") +// - Small source code footprint ("easy to maintain") +// - No dependencies ("ease of use") +// +// =========================================================================== +// +// I/O callbacks +// +// I/O callbacks allow you to read from arbitrary sources, like packaged +// files or some other source. Data read from callbacks are processed +// through a small internal buffer (currently 128 bytes) to try to reduce +// overhead. +// +// The three functions you must define are "read" (reads some bytes of data), +// "skip" (skips some bytes of data), "eof" (reports if the stream is at the end). +// +// =========================================================================== +// +// SIMD support +// +// The JPEG decoder will try to automatically use SIMD kernels on x86 when +// supported by the compiler. For ARM Neon support, you must explicitly +// request it. +// +// (The old do-it-yourself SIMD API is no longer supported in the current +// code.) +// +// On x86, SSE2 will automatically be used when available based on a run-time +// test; if not, the generic C versions are used as a fall-back. On ARM targets, +// the typical path is to have separate builds for NEON and non-NEON devices +// (at least this is true for iOS and Android). Therefore, the NEON support is +// toggled by a build flag: define STBI_NEON to get NEON loops. +// +// If for some reason you do not want to use any of SIMD code, or if +// you have issues compiling it, you can disable it entirely by +// defining STBI_NO_SIMD. +// +// =========================================================================== +// +// HDR image support (disable by defining STBI_NO_HDR) +// +// stb_image supports loading HDR images in general, and currently the Radiance +// .HDR file format specifically. You can still load any file through the existing +// interface; if you attempt to load an HDR file, it will be automatically remapped +// to LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1; +// both of these constants can be reconfigured through this interface: +// +// stbi_hdr_to_ldr_gamma(2.2f); +// stbi_hdr_to_ldr_scale(1.0f); +// +// (note, do not use _inverse_ constants; stbi_image will invert them +// appropriately). +// +// Additionally, there is a new, parallel interface for loading files as +// (linear) floats to preserve the full dynamic range: +// +// float *data = stbi_loadf(filename, &x, &y, &n, 0); +// +// If you load LDR images through this interface, those images will +// be promoted to floating point values, run through the inverse of +// constants corresponding to the above: +// +// stbi_ldr_to_hdr_scale(1.0f); +// stbi_ldr_to_hdr_gamma(2.2f); +// +// Finally, given a filename (or an open file or memory block--see header +// file for details) containing image data, you can query for the "most +// appropriate" interface to use (that is, whether the image is HDR or +// not), using: +// +// stbi_is_hdr(char *filename); +// +// =========================================================================== +// +// iPhone PNG support: +// +// We optionally support converting iPhone-formatted PNGs (which store +// premultiplied BGRA) back to RGB, even though they're internally encoded +// differently. To enable this conversion, call +// stbi_convert_iphone_png_to_rgb(1). +// +// Call stbi_set_unpremultiply_on_load(1) as well to force a divide per +// pixel to remove any premultiplied alpha *only* if the image file explicitly +// says there's premultiplied data (currently only happens in iPhone images, +// and only if iPhone convert-to-rgb processing is on). +// +// =========================================================================== +// +// ADDITIONAL CONFIGURATION +// +// - You can suppress implementation of any of the decoders to reduce +// your code footprint by #defining one or more of the following +// symbols before creating the implementation. +// +// STBI_NO_JPEG +// STBI_NO_PNG +// STBI_NO_BMP +// STBI_NO_PSD +// STBI_NO_TGA +// STBI_NO_GIF +// STBI_NO_HDR +// STBI_NO_PIC +// STBI_NO_PNM (.ppm and .pgm) +// +// - You can request *only* certain decoders and suppress all other ones +// (this will be more forward-compatible, as addition of new decoders +// doesn't require you to disable them explicitly): +// +// STBI_ONLY_JPEG +// STBI_ONLY_PNG +// STBI_ONLY_BMP +// STBI_ONLY_PSD +// STBI_ONLY_TGA +// STBI_ONLY_GIF +// STBI_ONLY_HDR +// STBI_ONLY_PIC +// STBI_ONLY_PNM (.ppm and .pgm) +// +// - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still +// want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB +// +// - If you define STBI_MAX_DIMENSIONS, stb_image will reject images greater +// than that size (in either width or height) without further processing. +// This is to let programs in the wild set an upper bound to prevent +// denial-of-service attacks on untrusted data, as one could generate a +// valid image of gigantic dimensions and force stb_image to allocate a +// huge block of memory and spend disproportionate time decoding it. By +// default this is set to (1 << 24), which is 16777216, but that's still +// very big. + +#ifndef STBI_NO_STDIO +#include +#endif // STBI_NO_STDIO + +#define STBI_VERSION 1 + +enum +{ + STBI_default = 0, // only used for desired_channels + + STBI_grey = 1, + STBI_grey_alpha = 2, + STBI_rgb = 3, + STBI_rgb_alpha = 4 +}; + +#include +typedef unsigned char stbi_uc; +typedef unsigned short stbi_us; + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef STBIDEF +#ifdef STB_IMAGE_STATIC +#define STBIDEF static +#else +#define STBIDEF extern +#endif +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// PRIMARY API - works on images of any type +// + +// +// load image by filename, open file, or memory buffer +// + +typedef struct +{ + int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read + void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative + int (*eof) (void *user); // returns nonzero if we are at end of file/data +} stbi_io_callbacks; + +//////////////////////////////////// +// +// 8-bits-per-channel interface +// + +STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +// for stbi_load_from_file, file pointer is left pointing immediately after image +#endif + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +#endif + +#ifdef STBI_WINDOWS_UTF8 +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input); +#endif + +//////////////////////////////////// +// +// 16-bits-per-channel interface +// + +STBIDEF stbi_us *stbi_load_16_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + +#ifndef STBI_NO_STDIO +STBIDEF stbi_us *stbi_load_16 (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); +STBIDEF stbi_us *stbi_load_from_file_16(FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); +#endif + +//////////////////////////////////// +// +// float-per-channel interface +// +#ifndef STBI_NO_LINEAR + STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels); + + #ifndef STBI_NO_STDIO + STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *channels_in_file, int desired_channels); + STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *channels_in_file, int desired_channels); + #endif +#endif + +#ifndef STBI_NO_HDR + STBIDEF void stbi_hdr_to_ldr_gamma(float gamma); + STBIDEF void stbi_hdr_to_ldr_scale(float scale); +#endif // STBI_NO_HDR + +#ifndef STBI_NO_LINEAR + STBIDEF void stbi_ldr_to_hdr_gamma(float gamma); + STBIDEF void stbi_ldr_to_hdr_scale(float scale); +#endif // STBI_NO_LINEAR + +// stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user); +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len); +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename); +STBIDEF int stbi_is_hdr_from_file(FILE *f); +#endif // STBI_NO_STDIO + + +// get a VERY brief reason for failure +// on most compilers (and ALL modern mainstream compilers) this is threadsafe +STBIDEF const char *stbi_failure_reason (void); + +// free the loaded image -- this is just free() +STBIDEF void stbi_image_free (void *retval_from_stbi_load); + +// get image dimensions & components without fully decoding +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len); +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *clbk, void *user); + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp); +STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp); +STBIDEF int stbi_is_16_bit (char const *filename); +STBIDEF int stbi_is_16_bit_from_file(FILE *f); +#endif + + + +// for image formats that explicitly notate that they have premultiplied alpha, +// we just return the colors as stored in the file. set this flag to force +// unpremultiplication. results are undefined if the unpremultiply overflow. +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply); + +// indicate whether we should process iphone images back to canonical format, +// or just pass them through "as-is" +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert); + +// flip the image vertically, so the first pixel in the output array is the bottom left +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip); + +// as above, but only applies to images loaded on the thread that calls the function +// this function is only available if your compiler supports thread-local variables; +// calling it will fail to link if your compiler doesn't +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply); +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert); +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip); + +// ZLIB client - used by PNG, available for other purposes + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen); +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header); +STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + +STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen); +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen); + + +#ifdef __cplusplus +} +#endif + +// +// +//// end header file ///////////////////////////////////////////////////// +#endif // STBI_INCLUDE_STB_IMAGE_H + +#ifdef STB_IMAGE_IMPLEMENTATION + +#if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \ + || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \ + || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \ + || defined(STBI_ONLY_ZLIB) + #ifndef STBI_ONLY_JPEG + #define STBI_NO_JPEG + #endif + #ifndef STBI_ONLY_PNG + #define STBI_NO_PNG + #endif + #ifndef STBI_ONLY_BMP + #define STBI_NO_BMP + #endif + #ifndef STBI_ONLY_PSD + #define STBI_NO_PSD + #endif + #ifndef STBI_ONLY_TGA + #define STBI_NO_TGA + #endif + #ifndef STBI_ONLY_GIF + #define STBI_NO_GIF + #endif + #ifndef STBI_ONLY_HDR + #define STBI_NO_HDR + #endif + #ifndef STBI_ONLY_PIC + #define STBI_NO_PIC + #endif + #ifndef STBI_ONLY_PNM + #define STBI_NO_PNM + #endif +#endif + +#if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB) +#define STBI_NO_ZLIB +#endif + + +#include +#include // ptrdiff_t on osx +#include +#include +#include + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) +#include // ldexp, pow +#endif + +#ifndef STBI_NO_STDIO +#include +#endif + +#ifndef STBI_ASSERT +#include +#define STBI_ASSERT(x) assert(x) +#endif + +#ifdef __cplusplus +#define STBI_EXTERN extern "C" +#else +#define STBI_EXTERN extern +#endif + + +#ifndef _MSC_VER + #ifdef __cplusplus + #define stbi_inline inline + #else + #define stbi_inline + #endif +#else + #define stbi_inline __forceinline +#endif + +#ifndef STBI_NO_THREAD_LOCALS + #if defined(__cplusplus) && __cplusplus >= 201103L + #define STBI_THREAD_LOCAL thread_local + #elif defined(__GNUC__) && __GNUC__ < 5 + #define STBI_THREAD_LOCAL __thread + #elif defined(_MSC_VER) + #define STBI_THREAD_LOCAL __declspec(thread) + #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__) + #define STBI_THREAD_LOCAL _Thread_local + #endif + + #ifndef STBI_THREAD_LOCAL + #if defined(__GNUC__) + #define STBI_THREAD_LOCAL __thread + #endif + #endif +#endif + +#if defined(_MSC_VER) || defined(__SYMBIAN32__) +typedef unsigned short stbi__uint16; +typedef signed short stbi__int16; +typedef unsigned int stbi__uint32; +typedef signed int stbi__int32; +#else +#include +typedef uint16_t stbi__uint16; +typedef int16_t stbi__int16; +typedef uint32_t stbi__uint32; +typedef int32_t stbi__int32; +#endif + +// should produce compiler error if size is wrong +typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1]; + +#ifdef _MSC_VER +#define STBI_NOTUSED(v) (void)(v) +#else +#define STBI_NOTUSED(v) (void)sizeof(v) +#endif + +#ifdef _MSC_VER +#define STBI_HAS_LROTL +#endif + +#ifdef STBI_HAS_LROTL + #define stbi_lrot(x,y) _lrotl(x,y) +#else + #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (-(y) & 31))) +#endif + +#if defined(STBI_MALLOC) && defined(STBI_FREE) && (defined(STBI_REALLOC) || defined(STBI_REALLOC_SIZED)) +// ok +#elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC) && !defined(STBI_REALLOC_SIZED) +// ok +#else +#error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC (or STBI_REALLOC_SIZED)." +#endif + +#ifndef STBI_MALLOC +#define STBI_MALLOC(sz) malloc(sz) +#define STBI_REALLOC(p,newsz) realloc(p,newsz) +#define STBI_FREE(p) free(p) +#endif + +#ifndef STBI_REALLOC_SIZED +#define STBI_REALLOC_SIZED(p,oldsz,newsz) STBI_REALLOC(p,newsz) +#endif + +// x86/x64 detection +#if defined(__x86_64__) || defined(_M_X64) +#define STBI__X64_TARGET +#elif defined(__i386) || defined(_M_IX86) +#define STBI__X86_TARGET +#endif + +#if defined(__GNUC__) && defined(STBI__X86_TARGET) && !defined(__SSE2__) && !defined(STBI_NO_SIMD) +// gcc doesn't support sse2 intrinsics unless you compile with -msse2, +// which in turn means it gets to use SSE2 everywhere. This is unfortunate, +// but previous attempts to provide the SSE2 functions with runtime +// detection caused numerous issues. The way architecture extensions are +// exposed in GCC/Clang is, sadly, not really suited for one-file libs. +// New behavior: if compiled with -msse2, we use SSE2 without any +// detection; if not, we don't use it at all. +#define STBI_NO_SIMD +#endif + +#if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD) +// Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET +// +// 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the +// Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant. +// As a result, enabling SSE2 on 32-bit MinGW is dangerous when not +// simultaneously enabling "-mstackrealign". +// +// See https://github.com/nothings/stb/issues/81 for more information. +// +// So default to no SSE2 on 32-bit MinGW. If you've read this far and added +// -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2. +#define STBI_NO_SIMD +#endif + +#if !defined(STBI_NO_SIMD) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) +#define STBI_SSE2 +#include + +#ifdef _MSC_VER + +#if _MSC_VER >= 1400 // not VC6 +#include // __cpuid +static int stbi__cpuid3(void) +{ + int info[4]; + __cpuid(info,1); + return info[3]; +} +#else +static int stbi__cpuid3(void) +{ + int res; + __asm { + mov eax,1 + cpuid + mov res,edx + } + return res; +} +#endif + +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + int info3 = stbi__cpuid3(); + return ((info3 >> 26) & 1) != 0; +} +#endif + +#else // assume GCC-style if not VC++ +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) + +#if !defined(STBI_NO_JPEG) && defined(STBI_SSE2) +static int stbi__sse2_available(void) +{ + // If we're even attempting to compile this on GCC/Clang, that means + // -msse2 is on, which means the compiler is allowed to use SSE2 + // instructions at will, and so are we. + return 1; +} +#endif + +#endif +#endif + +// ARM NEON +#if defined(STBI_NO_SIMD) && defined(STBI_NEON) +#undef STBI_NEON +#endif + +#ifdef STBI_NEON +#include +#ifdef _MSC_VER +#define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name +#else +#define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16))) +#endif +#endif + +#ifndef STBI_SIMD_ALIGN +#define STBI_SIMD_ALIGN(type, name) type name +#endif + +#ifndef STBI_MAX_DIMENSIONS +#define STBI_MAX_DIMENSIONS (1 << 24) +#endif + +/////////////////////////////////////////////// +// +// stbi__context struct and start_xxx functions + +// stbi__context structure is our basic context used by all images, so it +// contains all the IO context, plus some basic image information +typedef struct +{ + stbi__uint32 img_x, img_y; + int img_n, img_out_n; + + stbi_io_callbacks io; + void *io_user_data; + + int read_from_callbacks; + int buflen; + stbi_uc buffer_start[128]; + int callback_already_read; + + stbi_uc *img_buffer, *img_buffer_end; + stbi_uc *img_buffer_original, *img_buffer_original_end; +} stbi__context; + + +static void stbi__refill_buffer(stbi__context *s); + +// initialize a memory-decode context +static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len) +{ + s->io.read = NULL; + s->read_from_callbacks = 0; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer; + s->img_buffer_end = s->img_buffer_original_end = (stbi_uc *) buffer+len; +} + +// initialize a callback-based context +static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user) +{ + s->io = *c; + s->io_user_data = user; + s->buflen = sizeof(s->buffer_start); + s->read_from_callbacks = 1; + s->callback_already_read = 0; + s->img_buffer = s->img_buffer_original = s->buffer_start; + stbi__refill_buffer(s); + s->img_buffer_original_end = s->img_buffer_end; +} + +#ifndef STBI_NO_STDIO + +static int stbi__stdio_read(void *user, char *data, int size) +{ + return (int) fread(data,1,size,(FILE*) user); +} + +static void stbi__stdio_skip(void *user, int n) +{ + int ch; + fseek((FILE*) user, n, SEEK_CUR); + ch = fgetc((FILE*) user); /* have to read a byte to reset feof()'s flag */ + if (ch != EOF) { + ungetc(ch, (FILE *) user); /* push byte back onto stream if valid. */ + } +} + +static int stbi__stdio_eof(void *user) +{ + return feof((FILE*) user) || ferror((FILE *) user); +} + +static stbi_io_callbacks stbi__stdio_callbacks = +{ + stbi__stdio_read, + stbi__stdio_skip, + stbi__stdio_eof, +}; + +static void stbi__start_file(stbi__context *s, FILE *f) +{ + stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f); +} + +//static void stop_file(stbi__context *s) { } + +#endif // !STBI_NO_STDIO + +static void stbi__rewind(stbi__context *s) +{ + // conceptually rewind SHOULD rewind to the beginning of the stream, + // but we just rewind to the beginning of the initial buffer, because + // we only use it after doing 'test', which only ever looks at at most 92 bytes + s->img_buffer = s->img_buffer_original; + s->img_buffer_end = s->img_buffer_original_end; +} + +enum +{ + STBI_ORDER_RGB, + STBI_ORDER_BGR +}; + +typedef struct +{ + int bits_per_channel; + int num_channels; + int channel_order; +} stbi__result_info; + +#ifndef STBI_NO_JPEG +static int stbi__jpeg_test(stbi__context *s); +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNG +static int stbi__png_test(stbi__context *s); +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__png_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_BMP +static int stbi__bmp_test(stbi__context *s); +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_TGA +static int stbi__tga_test(stbi__context *s); +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s); +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc); +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__psd_is16(stbi__context *s); +#endif + +#ifndef STBI_NO_HDR +static int stbi__hdr_test(stbi__context *s); +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_test(stbi__context *s); +static void *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_GIF +static int stbi__gif_test(stbi__context *s); +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp); +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp); +#endif + +#ifndef STBI_NO_PNM +static int stbi__pnm_test(stbi__context *s); +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri); +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp); +static int stbi__pnm_is16(stbi__context *s); +#endif + +static +#ifdef STBI_THREAD_LOCAL +STBI_THREAD_LOCAL +#endif +const char *stbi__g_failure_reason; + +STBIDEF const char *stbi_failure_reason(void) +{ + return stbi__g_failure_reason; +} + +#ifndef STBI_NO_FAILURE_STRINGS +static int stbi__err(const char *str) +{ + stbi__g_failure_reason = str; + return 0; +} +#endif + +static void *stbi__malloc(size_t size) +{ + return STBI_MALLOC(size); +} + +// stb_image uses ints pervasively, including for offset calculations. +// therefore the largest decoded image size we can support with the +// current code, even on 64-bit targets, is INT_MAX. this is not a +// significant limitation for the intended use case. +// +// we do, however, need to make sure our size calculations don't +// overflow. hence a few helper functions for size calculations that +// multiply integers together, making sure that they're non-negative +// and no overflow occurs. + +// return 1 if the sum is valid, 0 on overflow. +// negative terms are considered invalid. +static int stbi__addsizes_valid(int a, int b) +{ + if (b < 0) return 0; + // now 0 <= b <= INT_MAX, hence also + // 0 <= INT_MAX - b <= INTMAX. + // And "a + b <= INT_MAX" (which might overflow) is the + // same as a <= INT_MAX - b (no overflow) + return a <= INT_MAX - b; +} + +// returns 1 if the product is valid, 0 on overflow. +// negative factors are considered invalid. +static int stbi__mul2sizes_valid(int a, int b) +{ + if (a < 0 || b < 0) return 0; + if (b == 0) return 1; // mul-by-0 is always safe + // portable way to check for no overflows in a*b + return a <= INT_MAX/b; +} + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// returns 1 if "a*b + add" has no negative terms/factors and doesn't overflow +static int stbi__mad2sizes_valid(int a, int b, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__addsizes_valid(a*b, add); +} +#endif + +// returns 1 if "a*b*c + add" has no negative terms/factors and doesn't overflow +static int stbi__mad3sizes_valid(int a, int b, int c, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__addsizes_valid(a*b*c, add); +} + +// returns 1 if "a*b*c*d + add" has no negative terms/factors and doesn't overflow +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static int stbi__mad4sizes_valid(int a, int b, int c, int d, int add) +{ + return stbi__mul2sizes_valid(a, b) && stbi__mul2sizes_valid(a*b, c) && + stbi__mul2sizes_valid(a*b*c, d) && stbi__addsizes_valid(a*b*c*d, add); +} +#endif + +#if !defined(STBI_NO_JPEG) || !defined(STBI_NO_PNG) || !defined(STBI_NO_TGA) || !defined(STBI_NO_HDR) +// mallocs with size overflow checking +static void *stbi__malloc_mad2(int a, int b, int add) +{ + if (!stbi__mad2sizes_valid(a, b, add)) return NULL; + return stbi__malloc(a*b + add); +} +#endif + +static void *stbi__malloc_mad3(int a, int b, int c, int add) +{ + if (!stbi__mad3sizes_valid(a, b, c, add)) return NULL; + return stbi__malloc(a*b*c + add); +} + +#if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR) || !defined(STBI_NO_PNM) +static void *stbi__malloc_mad4(int a, int b, int c, int d, int add) +{ + if (!stbi__mad4sizes_valid(a, b, c, d, add)) return NULL; + return stbi__malloc(a*b*c*d + add); +} +#endif + +// returns 1 if the sum of two signed ints is valid (between -2^31 and 2^31-1 inclusive), 0 on overflow. +static int stbi__addints_valid(int a, int b) +{ + if ((a >= 0) != (b >= 0)) return 1; // a and b have different signs, so no overflow + if (a < 0 && b < 0) return a >= INT_MIN - b; // same as a + b >= INT_MIN; INT_MIN - b cannot overflow since b < 0. + return a <= INT_MAX - b; +} + +// returns 1 if the product of two ints fits in a signed short, 0 on overflow. +static int stbi__mul2shorts_valid(int a, int b) +{ + if (b == 0 || b == -1) return 1; // multiplication by 0 is always 0; check for -1 so SHRT_MIN/b doesn't overflow + if ((a >= 0) == (b >= 0)) return a <= SHRT_MAX/b; // product is positive, so similar to mul2sizes_valid + if (b < 0) return a <= SHRT_MIN / b; // same as a * b >= SHRT_MIN + return a >= SHRT_MIN / b; +} + +// stbi__err - error +// stbi__errpf - error returning pointer to float +// stbi__errpuc - error returning pointer to unsigned char + +#ifdef STBI_NO_FAILURE_STRINGS + #define stbi__err(x,y) 0 +#elif defined(STBI_FAILURE_USERMSG) + #define stbi__err(x,y) stbi__err(y) +#else + #define stbi__err(x,y) stbi__err(x) +#endif + +#define stbi__errpf(x,y) ((float *)(size_t) (stbi__err(x,y)?NULL:NULL)) +#define stbi__errpuc(x,y) ((unsigned char *)(size_t) (stbi__err(x,y)?NULL:NULL)) + +STBIDEF void stbi_image_free(void *retval_from_stbi_load) +{ + STBI_FREE(retval_from_stbi_load); +} + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp); +#endif + +#ifndef STBI_NO_HDR +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp); +#endif + +static int stbi__vertically_flip_on_load_global = 0; + +STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_global = flag_true_if_should_flip; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__vertically_flip_on_load stbi__vertically_flip_on_load_global +#else +static STBI_THREAD_LOCAL int stbi__vertically_flip_on_load_local, stbi__vertically_flip_on_load_set; + +STBIDEF void stbi_set_flip_vertically_on_load_thread(int flag_true_if_should_flip) +{ + stbi__vertically_flip_on_load_local = flag_true_if_should_flip; + stbi__vertically_flip_on_load_set = 1; +} + +#define stbi__vertically_flip_on_load (stbi__vertically_flip_on_load_set \ + ? stbi__vertically_flip_on_load_local \ + : stbi__vertically_flip_on_load_global) +#endif // STBI_THREAD_LOCAL + +static void *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + memset(ri, 0, sizeof(*ri)); // make sure it's initialized if we add new fields + ri->bits_per_channel = 8; // default is 8 so most paths don't have to be changed + ri->channel_order = STBI_ORDER_RGB; // all current input & output are this, but this is here so we can add BGR order + ri->num_channels = 0; + + // test the formats with a very explicit header first (at least a FOURCC + // or distinctive magic number first) + #ifndef STBI_NO_PNG + if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_BMP + if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_GIF + if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PSD + if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp, ri, bpc); + #else + STBI_NOTUSED(bpc); + #endif + #ifndef STBI_NO_PIC + if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp, ri); + #endif + + // then the formats that can end up attempting to load with just 1 or 2 + // bytes matching expectations; these are prone to false positives, so + // try them later + #ifndef STBI_NO_JPEG + if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp, ri); + #endif + #ifndef STBI_NO_PNM + if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp, ri); + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + float *hdr = stbi__hdr_load(s, x,y,comp,req_comp, ri); + return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp); + } + #endif + + #ifndef STBI_NO_TGA + // test tga last because it's a crappy test! + if (stbi__tga_test(s)) + return stbi__tga_load(s,x,y,comp,req_comp, ri); + #endif + + return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt"); +} + +static stbi_uc *stbi__convert_16_to_8(stbi__uint16 *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi_uc *reduced; + + reduced = (stbi_uc *) stbi__malloc(img_len); + if (reduced == NULL) return stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + reduced[i] = (stbi_uc)((orig[i] >> 8) & 0xFF); // top half of each byte is sufficient approx of 16->8 bit scaling + + STBI_FREE(orig); + return reduced; +} + +static stbi__uint16 *stbi__convert_8_to_16(stbi_uc *orig, int w, int h, int channels) +{ + int i; + int img_len = w * h * channels; + stbi__uint16 *enlarged; + + enlarged = (stbi__uint16 *) stbi__malloc(img_len*2); + if (enlarged == NULL) return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + + for (i = 0; i < img_len; ++i) + enlarged[i] = (stbi__uint16)((orig[i] << 8) + orig[i]); // replicate to high and low byte, maps 0->0, 255->0xffff + + STBI_FREE(orig); + return enlarged; +} + +static void stbi__vertical_flip(void *image, int w, int h, int bytes_per_pixel) +{ + int row; + size_t bytes_per_row = (size_t)w * bytes_per_pixel; + stbi_uc temp[2048]; + stbi_uc *bytes = (stbi_uc *)image; + + for (row = 0; row < (h>>1); row++) { + stbi_uc *row0 = bytes + row*bytes_per_row; + stbi_uc *row1 = bytes + (h - row - 1)*bytes_per_row; + // swap row0 with row1 + size_t bytes_left = bytes_per_row; + while (bytes_left) { + size_t bytes_copy = (bytes_left < sizeof(temp)) ? bytes_left : sizeof(temp); + memcpy(temp, row0, bytes_copy); + memcpy(row0, row1, bytes_copy); + memcpy(row1, temp, bytes_copy); + row0 += bytes_copy; + row1 += bytes_copy; + bytes_left -= bytes_copy; + } + } +} + +#ifndef STBI_NO_GIF +static void stbi__vertical_flip_slices(void *image, int w, int h, int z, int bytes_per_pixel) +{ + int slice; + int slice_size = w * h * bytes_per_pixel; + + stbi_uc *bytes = (stbi_uc *)image; + for (slice = 0; slice < z; ++slice) { + stbi__vertical_flip(bytes, w, h, bytes_per_pixel); + bytes += slice_size; + } +} +#endif + +static unsigned char *stbi__load_and_postprocess_8bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 8); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 8) { + result = stbi__convert_16_to_8((stbi__uint16 *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 8; + } + + // @TODO: move stbi__convert_format to here + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi_uc)); + } + + return (unsigned char *) result; +} + +static stbi__uint16 *stbi__load_and_postprocess_16bit(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + stbi__result_info ri; + void *result = stbi__load_main(s, x, y, comp, req_comp, &ri, 16); + + if (result == NULL) + return NULL; + + // it is the responsibility of the loaders to make sure we get either 8 or 16 bit. + STBI_ASSERT(ri.bits_per_channel == 8 || ri.bits_per_channel == 16); + + if (ri.bits_per_channel != 16) { + result = stbi__convert_8_to_16((stbi_uc *) result, *x, *y, req_comp == 0 ? *comp : req_comp); + ri.bits_per_channel = 16; + } + + // @TODO: move stbi__convert_format16 to here + // @TODO: special case RGB-to-Y (and RGBA-to-YA) for 8-bit-to-16-bit case to keep more precision + + if (stbi__vertically_flip_on_load) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(stbi__uint16)); + } + + return (stbi__uint16 *) result; +} + +#if !defined(STBI_NO_HDR) && !defined(STBI_NO_LINEAR) +static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp) +{ + if (stbi__vertically_flip_on_load && result != NULL) { + int channels = req_comp ? req_comp : *comp; + stbi__vertical_flip(result, *x, *y, channels * sizeof(float)); + } +} +#endif + +#ifndef STBI_NO_STDIO + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBI_EXTERN __declspec(dllimport) int __stdcall MultiByteToWideChar(unsigned int cp, unsigned long flags, const char *str, int cbmb, wchar_t *widestr, int cchwide); +STBI_EXTERN __declspec(dllimport) int __stdcall WideCharToMultiByte(unsigned int cp, unsigned long flags, const wchar_t *widestr, int cchwide, char *str, int cbmb, const char *defchar, int *used_default); +#endif + +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) +STBIDEF int stbi_convert_wchar_to_utf8(char *buffer, size_t bufferlen, const wchar_t* input) +{ + return WideCharToMultiByte(65001 /* UTF8 */, 0, input, -1, buffer, (int) bufferlen, NULL, NULL); +} +#endif + +static FILE *stbi__fopen(char const *filename, char const *mode) +{ + FILE *f; +#if defined(_WIN32) && defined(STBI_WINDOWS_UTF8) + wchar_t wMode[64]; + wchar_t wFilename[1024]; + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, filename, -1, wFilename, sizeof(wFilename)/sizeof(*wFilename))) + return 0; + + if (0 == MultiByteToWideChar(65001 /* UTF8 */, 0, mode, -1, wMode, sizeof(wMode)/sizeof(*wMode))) + return 0; + +#if defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != _wfopen_s(&f, wFilename, wMode)) + f = 0; +#else + f = _wfopen(wFilename, wMode); +#endif + +#elif defined(_MSC_VER) && _MSC_VER >= 1400 + if (0 != fopen_s(&f, filename, mode)) + f=0; +#else + f = fopen(filename, mode); +#endif + return f; +} + + +STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + unsigned char *result; + if (!f) return stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi__uint16 *stbi_load_from_file_16(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__uint16 *result; + stbi__context s; + stbi__start_file(&s,f); + result = stbi__load_and_postprocess_16bit(&s,x,y,comp,req_comp); + if (result) { + // need to 'unget' all the characters in the IO buffer + fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR); + } + return result; +} + +STBIDEF stbi_us *stbi_load_16(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + stbi__uint16 *result; + if (!f) return (stbi_us *) stbi__errpuc("can't fopen", "Unable to open file"); + result = stbi_load_from_file_16(f,x,y,comp,req_comp); + fclose(f); + return result; +} + + +#endif //!STBI_NO_STDIO + +STBIDEF stbi_us *stbi_load_16_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_us *stbi_load_16_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *channels_in_file, int desired_channels) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *)clbk, user); + return stbi__load_and_postprocess_16bit(&s,x,y,channels_in_file,desired_channels); +} + +STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__load_and_postprocess_8bit(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_GIF +STBIDEF stbi_uc *stbi_load_gif_from_memory(stbi_uc const *buffer, int len, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + unsigned char *result; + stbi__context s; + stbi__start_mem(&s,buffer,len); + + result = (unsigned char*) stbi__load_gif_main(&s, delays, x, y, z, comp, req_comp); + if (stbi__vertically_flip_on_load) { + stbi__vertical_flip_slices( result, *x, *y, *z, *comp ); + } + + return result; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp) +{ + unsigned char *data; + #ifndef STBI_NO_HDR + if (stbi__hdr_test(s)) { + stbi__result_info ri; + float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp, &ri); + if (hdr_data) + stbi__float_postprocess(hdr_data,x,y,comp,req_comp); + return hdr_data; + } + #endif + data = stbi__load_and_postprocess_8bit(s, x, y, comp, req_comp); + if (data) + return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp); + return stbi__errpf("unknown image type", "Image not of any known type, or corrupt"); +} + +STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} + +#ifndef STBI_NO_STDIO +STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp) +{ + float *result; + FILE *f = stbi__fopen(filename, "rb"); + if (!f) return stbi__errpf("can't fopen", "Unable to open file"); + result = stbi_loadf_from_file(f,x,y,comp,req_comp); + fclose(f); + return result; +} + +STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp) +{ + stbi__context s; + stbi__start_file(&s,f); + return stbi__loadf_main(&s,x,y,comp,req_comp); +} +#endif // !STBI_NO_STDIO + +#endif // !STBI_NO_LINEAR + +// these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is +// defined, for API simplicity; if STBI_NO_LINEAR is defined, it always +// reports false! + +STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(buffer); + STBI_NOTUSED(len); + return 0; + #endif +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_is_hdr (char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result=0; + if (f) { + result = stbi_is_hdr_from_file(f); + fclose(f); + } + return result; +} + +STBIDEF int stbi_is_hdr_from_file(FILE *f) +{ + #ifndef STBI_NO_HDR + long pos = ftell(f); + int res; + stbi__context s; + stbi__start_file(&s,f); + res = stbi__hdr_test(&s); + fseek(f, pos, SEEK_SET); + return res; + #else + STBI_NOTUSED(f); + return 0; + #endif +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user) +{ + #ifndef STBI_NO_HDR + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user); + return stbi__hdr_test(&s); + #else + STBI_NOTUSED(clbk); + STBI_NOTUSED(user); + return 0; + #endif +} + +#ifndef STBI_NO_LINEAR +static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f; + +STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; } +STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; } +#endif + +static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f; + +STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; } +STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; } + + +////////////////////////////////////////////////////////////////////////////// +// +// Common code used by all image loaders +// + +enum +{ + STBI__SCAN_load=0, + STBI__SCAN_type, + STBI__SCAN_header +}; + +static void stbi__refill_buffer(stbi__context *s) +{ + int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen); + s->callback_already_read += (int) (s->img_buffer - s->img_buffer_original); + if (n == 0) { + // at end of file, treat same as if from memory, but need to handle case + // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file + s->read_from_callbacks = 0; + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start+1; + *s->img_buffer = 0; + } else { + s->img_buffer = s->buffer_start; + s->img_buffer_end = s->buffer_start + n; + } +} + +stbi_inline static stbi_uc stbi__get8(stbi__context *s) +{ + if (s->img_buffer < s->img_buffer_end) + return *s->img_buffer++; + if (s->read_from_callbacks) { + stbi__refill_buffer(s); + return *s->img_buffer++; + } + return 0; +} + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_HDR) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +stbi_inline static int stbi__at_eof(stbi__context *s) +{ + if (s->io.read) { + if (!(s->io.eof)(s->io_user_data)) return 0; + // if feof() is true, check if buffer = end + // special case: we've only got the special 0 character at the end + if (s->read_from_callbacks == 0) return 1; + } + + return s->img_buffer >= s->img_buffer_end; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) +// nothing +#else +static void stbi__skip(stbi__context *s, int n) +{ + if (n == 0) return; // already there! + if (n < 0) { + s->img_buffer = s->img_buffer_end; + return; + } + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + s->img_buffer = s->img_buffer_end; + (s->io.skip)(s->io_user_data, n - blen); + return; + } + } + s->img_buffer += n; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_TGA) && defined(STBI_NO_HDR) && defined(STBI_NO_PNM) +// nothing +#else +static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n) +{ + if (s->io.read) { + int blen = (int) (s->img_buffer_end - s->img_buffer); + if (blen < n) { + int res, count; + + memcpy(buffer, s->img_buffer, blen); + + count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen); + res = (count == (n-blen)); + s->img_buffer = s->img_buffer_end; + return res; + } + } + + if (s->img_buffer+n <= s->img_buffer_end) { + memcpy(buffer, s->img_buffer, n); + s->img_buffer += n; + return 1; + } else + return 0; +} +#endif + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static int stbi__get16be(stbi__context *s) +{ + int z = stbi__get8(s); + return (z << 8) + stbi__get8(s); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) && defined(STBI_NO_PIC) +// nothing +#else +static stbi__uint32 stbi__get32be(stbi__context *s) +{ + stbi__uint32 z = stbi__get16be(s); + return (z << 16) + stbi__get16be(s); +} +#endif + +#if defined(STBI_NO_BMP) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) +// nothing +#else +static int stbi__get16le(stbi__context *s) +{ + int z = stbi__get8(s); + return z + (stbi__get8(s) << 8); +} +#endif + +#ifndef STBI_NO_BMP +static stbi__uint32 stbi__get32le(stbi__context *s) +{ + stbi__uint32 z = stbi__get16le(s); + z += (stbi__uint32)stbi__get16le(s) << 16; + return z; +} +#endif + +#define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings + +#if defined(STBI_NO_JPEG) && defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +////////////////////////////////////////////////////////////////////////////// +// +// generic converter from built-in img_n to req_comp +// individual types do this automatically as much as possible (e.g. jpeg +// does all cases internally since it needs to colorspace convert anyway, +// and it never has alpha, so very few cases ). png can automatically +// interleave an alpha=255 channel, but falls back to this for other cases +// +// assume data buffer is malloced, so malloc a new one and free that one +// only failure mode is malloc failing + +static stbi_uc stbi__compute_y(int r, int g, int b) +{ + return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_BMP) && defined(STBI_NO_PSD) && defined(STBI_NO_TGA) && defined(STBI_NO_GIF) && defined(STBI_NO_PIC) && defined(STBI_NO_PNM) +// nothing +#else +static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + unsigned char *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (unsigned char *) stbi__malloc_mad3(req_comp, x, y, 0); + if (good == NULL) { + STBI_FREE(data); + return stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + unsigned char *src = data + j * x * img_n ; + unsigned char *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=255; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=255; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=255; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = 255; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 stbi__compute_y_16(int r, int g, int b) +{ + return (stbi__uint16) (((r*77) + (g*150) + (29*b)) >> 8); +} +#endif + +#if defined(STBI_NO_PNG) && defined(STBI_NO_PSD) +// nothing +#else +static stbi__uint16 *stbi__convert_format16(stbi__uint16 *data, int img_n, int req_comp, unsigned int x, unsigned int y) +{ + int i,j; + stbi__uint16 *good; + + if (req_comp == img_n) return data; + STBI_ASSERT(req_comp >= 1 && req_comp <= 4); + + good = (stbi__uint16 *) stbi__malloc(req_comp * x * y * 2); + if (good == NULL) { + STBI_FREE(data); + return (stbi__uint16 *) stbi__errpuc("outofmem", "Out of memory"); + } + + for (j=0; j < (int) y; ++j) { + stbi__uint16 *src = data + j * x * img_n ; + stbi__uint16 *dest = good + j * x * req_comp; + + #define STBI__COMBO(a,b) ((a)*8+(b)) + #define STBI__CASE(a,b) case STBI__COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b) + // convert source image with img_n components to one with req_comp components; + // avoid switch per pixel, so use switch per scanline and massive macros + switch (STBI__COMBO(img_n, req_comp)) { + STBI__CASE(1,2) { dest[0]=src[0]; dest[1]=0xffff; } break; + STBI__CASE(1,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(1,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=0xffff; } break; + STBI__CASE(2,1) { dest[0]=src[0]; } break; + STBI__CASE(2,3) { dest[0]=dest[1]=dest[2]=src[0]; } break; + STBI__CASE(2,4) { dest[0]=dest[1]=dest[2]=src[0]; dest[3]=src[1]; } break; + STBI__CASE(3,4) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2];dest[3]=0xffff; } break; + STBI__CASE(3,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(3,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = 0xffff; } break; + STBI__CASE(4,1) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); } break; + STBI__CASE(4,2) { dest[0]=stbi__compute_y_16(src[0],src[1],src[2]); dest[1] = src[3]; } break; + STBI__CASE(4,3) { dest[0]=src[0];dest[1]=src[1];dest[2]=src[2]; } break; + default: STBI_ASSERT(0); STBI_FREE(data); STBI_FREE(good); return (stbi__uint16*) stbi__errpuc("unsupported", "Unsupported format conversion"); + } + #undef STBI__CASE + } + + STBI_FREE(data); + return good; +} +#endif + +#ifndef STBI_NO_LINEAR +static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp) +{ + int i,k,n; + float *output; + if (!data) return NULL; + output = (float *) stbi__malloc_mad4(x, y, comp, sizeof(float), 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale); + } + } + if (n < comp) { + for (i=0; i < x*y; ++i) { + output[i*comp + n] = data[i*comp + n]/255.0f; + } + } + STBI_FREE(data); + return output; +} +#endif + +#ifndef STBI_NO_HDR +#define stbi__float2int(x) ((int) (x)) +static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp) +{ + int i,k,n; + stbi_uc *output; + if (!data) return NULL; + output = (stbi_uc *) stbi__malloc_mad3(x, y, comp, 0); + if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); } + // compute number of non-alpha components + if (comp & 1) n = comp; else n = comp-1; + for (i=0; i < x*y; ++i) { + for (k=0; k < n; ++k) { + float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + if (k < comp) { + float z = data[i*comp+k] * 255 + 0.5f; + if (z < 0) z = 0; + if (z > 255) z = 255; + output[i*comp + k] = (stbi_uc) stbi__float2int(z); + } + } + STBI_FREE(data); + return output; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// "baseline" JPEG/JFIF decoder +// +// simple implementation +// - doesn't support delayed output of y-dimension +// - simple interface (only one output format: 8-bit interleaved RGB) +// - doesn't try to recover corrupt jpegs +// - doesn't allow partial loading, loading multiple at once +// - still fast on x86 (copying globals into locals doesn't help x86) +// - allocates lots of intermediate memory (full size of all components) +// - non-interleaved case requires this anyway +// - allows good upsampling (see next) +// high-quality +// - upsampled channels are bilinearly interpolated, even across blocks +// - quality integer IDCT derived from IJG's 'slow' +// performance +// - fast huffman; reasonable integer IDCT +// - some SIMD kernels for common paths on targets with SSE2/NEON +// - uses a lot of intermediate memory, could cache poorly + +#ifndef STBI_NO_JPEG + +// huffman decoding acceleration +#define FAST_BITS 9 // larger handles more cases; smaller stomps less cache + +typedef struct +{ + stbi_uc fast[1 << FAST_BITS]; + // weirdly, repacking this into AoS is a 10% speed loss, instead of a win + stbi__uint16 code[256]; + stbi_uc values[256]; + stbi_uc size[257]; + unsigned int maxcode[18]; + int delta[17]; // old 'firstsymbol' - old 'firstcode' +} stbi__huffman; + +typedef struct +{ + stbi__context *s; + stbi__huffman huff_dc[4]; + stbi__huffman huff_ac[4]; + stbi__uint16 dequant[4][64]; + stbi__int16 fast_ac[4][1 << FAST_BITS]; + +// sizes for components, interleaved MCUs + int img_h_max, img_v_max; + int img_mcu_x, img_mcu_y; + int img_mcu_w, img_mcu_h; + +// definition of jpeg image component + struct + { + int id; + int h,v; + int tq; + int hd,ha; + int dc_pred; + + int x,y,w2,h2; + stbi_uc *data; + void *raw_data, *raw_coeff; + stbi_uc *linebuf; + short *coeff; // progressive only + int coeff_w, coeff_h; // number of 8x8 coefficient blocks + } img_comp[4]; + + stbi__uint32 code_buffer; // jpeg entropy-coded buffer + int code_bits; // number of valid bits + unsigned char marker; // marker seen while filling entropy buffer + int nomore; // flag if we saw a marker so must stop + + int progressive; + int spec_start; + int spec_end; + int succ_high; + int succ_low; + int eob_run; + int jfif; + int app14_color_transform; // Adobe APP14 tag + int rgb; + + int scan_n, order[4]; + int restart_interval, todo; + +// kernels + void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]); + void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step); + stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs); +} stbi__jpeg; + +static int stbi__build_huffman(stbi__huffman *h, int *count) +{ + int i,j,k=0; + unsigned int code; + // build size list for each symbol (from JPEG spec) + for (i=0; i < 16; ++i) { + for (j=0; j < count[i]; ++j) { + h->size[k++] = (stbi_uc) (i+1); + if(k >= 257) return stbi__err("bad size list","Corrupt JPEG"); + } + } + h->size[k] = 0; + + // compute actual symbols (from jpeg spec) + code = 0; + k = 0; + for(j=1; j <= 16; ++j) { + // compute delta to add to code to compute symbol id + h->delta[j] = k - code; + if (h->size[k] == j) { + while (h->size[k] == j) + h->code[k++] = (stbi__uint16) (code++); + if (code-1 >= (1u << j)) return stbi__err("bad code lengths","Corrupt JPEG"); + } + // compute largest code + 1 for this size, preshifted as needed later + h->maxcode[j] = code << (16-j); + code <<= 1; + } + h->maxcode[j] = 0xffffffff; + + // build non-spec acceleration table; 255 is flag for not-accelerated + memset(h->fast, 255, 1 << FAST_BITS); + for (i=0; i < k; ++i) { + int s = h->size[i]; + if (s <= FAST_BITS) { + int c = h->code[i] << (FAST_BITS-s); + int m = 1 << (FAST_BITS-s); + for (j=0; j < m; ++j) { + h->fast[c+j] = (stbi_uc) i; + } + } + } + return 1; +} + +// build a table that decodes both magnitude and value of small ACs in +// one go. +static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h) +{ + int i; + for (i=0; i < (1 << FAST_BITS); ++i) { + stbi_uc fast = h->fast[i]; + fast_ac[i] = 0; + if (fast < 255) { + int rs = h->values[fast]; + int run = (rs >> 4) & 15; + int magbits = rs & 15; + int len = h->size[fast]; + + if (magbits && len + magbits <= FAST_BITS) { + // magnitude code followed by receive_extend code + int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits); + int m = 1 << (magbits - 1); + if (k < m) k += (~0U << magbits) + 1; + // if the result is small enough, we can fit it in fast_ac table + if (k >= -128 && k <= 127) + fast_ac[i] = (stbi__int16) ((k * 256) + (run * 16) + (len + magbits)); + } + } + } +} + +static void stbi__grow_buffer_unsafe(stbi__jpeg *j) +{ + do { + unsigned int b = j->nomore ? 0 : stbi__get8(j->s); + if (b == 0xff) { + int c = stbi__get8(j->s); + while (c == 0xff) c = stbi__get8(j->s); // consume fill bytes + if (c != 0) { + j->marker = (unsigned char) c; + j->nomore = 1; + return; + } + } + j->code_buffer |= b << (24 - j->code_bits); + j->code_bits += 8; + } while (j->code_bits <= 24); +} + +// (1 << n) - 1 +static const stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535}; + +// decode a jpeg huffman value from the bitstream +stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h) +{ + unsigned int temp; + int c,k; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + // look at the top FAST_BITS and determine what symbol ID it is, + // if the code is <= FAST_BITS + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + k = h->fast[c]; + if (k < 255) { + int s = h->size[k]; + if (s > j->code_bits) + return -1; + j->code_buffer <<= s; + j->code_bits -= s; + return h->values[k]; + } + + // naive test is to shift the code_buffer down so k bits are + // valid, then test against maxcode. To speed this up, we've + // preshifted maxcode left so that it has (16-k) 0s at the + // end; in other words, regardless of the number of bits, it + // wants to be compared against something shifted to have 16; + // that way we don't need to shift inside the loop. + temp = j->code_buffer >> 16; + for (k=FAST_BITS+1 ; ; ++k) + if (temp < h->maxcode[k]) + break; + if (k == 17) { + // error! code not found + j->code_bits -= 16; + return -1; + } + + if (k > j->code_bits) + return -1; + + // convert the huffman code to the symbol id + c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k]; + if(c < 0 || c >= 256) // symbol id out of bounds! + return -1; + STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]); + + // convert the id to a symbol + j->code_bits -= k; + j->code_buffer <<= k; + return h->values[c]; +} + +// bias[n] = (-1<code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + + sgn = j->code_buffer >> 31; // sign bit always in MSB; 0 if MSB clear (positive), 1 if MSB set (negative) + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k + (stbi__jbias[n] & (sgn - 1)); +} + +// get some unsigned bits +stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n) +{ + unsigned int k; + if (j->code_bits < n) stbi__grow_buffer_unsafe(j); + if (j->code_bits < n) return 0; // ran out of bits from stream, return 0s intead of continuing + k = stbi_lrot(j->code_buffer, n); + j->code_buffer = k & ~stbi__bmask[n]; + k &= stbi__bmask[n]; + j->code_bits -= n; + return k; +} + +stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j) +{ + unsigned int k; + if (j->code_bits < 1) stbi__grow_buffer_unsafe(j); + if (j->code_bits < 1) return 0; // ran out of bits from stream, return 0s intead of continuing + k = j->code_buffer; + j->code_buffer <<= 1; + --j->code_bits; + return k & 0x80000000; +} + +// given a value that's at position X in the zigzag stream, +// where does it appear in the 8x8 matrix coded as row-major? +static const stbi_uc stbi__jpeg_dezigzag[64+15] = +{ + 0, 1, 8, 16, 9, 2, 3, 10, + 17, 24, 32, 25, 18, 11, 4, 5, + 12, 19, 26, 33, 40, 48, 41, 34, + 27, 20, 13, 6, 7, 14, 21, 28, + 35, 42, 49, 56, 57, 50, 43, 36, + 29, 22, 15, 23, 30, 37, 44, 51, + 58, 59, 52, 45, 38, 31, 39, 46, + 53, 60, 61, 54, 47, 55, 62, 63, + // let corrupt input sample past end + 63, 63, 63, 63, 63, 63, 63, 63, + 63, 63, 63, 63, 63, 63, 63 +}; + +// decode one 64-entry block-- +static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi__uint16 *dequant) +{ + int diff,dc,k; + int t; + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("bad huffman code","Corrupt JPEG"); + + // 0 all the ac values now so we can do it 32-bits at a time + memset(data,0,64*sizeof(data[0])); + + diff = t ? stbi__extend_receive(j, t) : 0; + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta","Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, dequant[0])) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * dequant[0]); + + // decode AC components, see JPEG spec + k = 1; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * dequant[zig]); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (rs != 0xf0) break; // end block + k += 16; + } else { + k += r; + // decode into unzigzag'd location + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]); + } + } + } while (k < 64); + return 1; +} + +static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b) +{ + int diff,dc; + int t; + if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + + if (j->succ_high == 0) { + // first scan for DC coefficient, must be first + memset(data,0,64*sizeof(data[0])); // 0 all the ac values now + t = stbi__jpeg_huff_decode(j, hdc); + if (t < 0 || t > 15) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + diff = t ? stbi__extend_receive(j, t) : 0; + + if (!stbi__addints_valid(j->img_comp[b].dc_pred, diff)) return stbi__err("bad delta", "Corrupt JPEG"); + dc = j->img_comp[b].dc_pred + diff; + j->img_comp[b].dc_pred = dc; + if (!stbi__mul2shorts_valid(dc, 1 << j->succ_low)) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + data[0] = (short) (dc * (1 << j->succ_low)); + } else { + // refinement scan for DC coefficient + if (stbi__jpeg_get_bit(j)) + data[0] += (short) (1 << j->succ_low); + } + return 1; +} + +// @OPTIMIZE: store non-zigzagged during the decode passes, +// and only de-zigzag when dequantizing +static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac) +{ + int k; + if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG"); + + if (j->succ_high == 0) { + int shift = j->succ_low; + + if (j->eob_run) { + --j->eob_run; + return 1; + } + + k = j->spec_start; + do { + unsigned int zig; + int c,r,s; + if (j->code_bits < 16) stbi__grow_buffer_unsafe(j); + c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1); + r = fac[c]; + if (r) { // fast-AC path + k += (r >> 4) & 15; // run + s = r & 15; // combined length + if (s > j->code_bits) return stbi__err("bad huffman code", "Combined length longer than code bits available"); + j->code_buffer <<= s; + j->code_bits -= s; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) ((r >> 8) * (1 << shift)); + } else { + int rs = stbi__jpeg_huff_decode(j, hac); + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r); + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + --j->eob_run; + break; + } + k += 16; + } else { + k += r; + zig = stbi__jpeg_dezigzag[k++]; + data[zig] = (short) (stbi__extend_receive(j,s) * (1 << shift)); + } + } + } while (k <= j->spec_end); + } else { + // refinement scan for these AC coefficients + + short bit = (short) (1 << j->succ_low); + + if (j->eob_run) { + --j->eob_run; + for (k = j->spec_start; k <= j->spec_end; ++k) { + short *p = &data[stbi__jpeg_dezigzag[k]]; + if (*p != 0) + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } + } else { + k = j->spec_start; + do { + int r,s; + int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh + if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG"); + s = rs & 15; + r = rs >> 4; + if (s == 0) { + if (r < 15) { + j->eob_run = (1 << r) - 1; + if (r) + j->eob_run += stbi__jpeg_get_bits(j, r); + r = 64; // force end of block + } else { + // r=15 s=0 should write 16 0s, so we just do + // a run of 15 0s and then write s (which is 0), + // so we don't have to do anything special here + } + } else { + if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG"); + // sign bit + if (stbi__jpeg_get_bit(j)) + s = bit; + else + s = -bit; + } + + // advance by r + while (k <= j->spec_end) { + short *p = &data[stbi__jpeg_dezigzag[k++]]; + if (*p != 0) { + if (stbi__jpeg_get_bit(j)) + if ((*p & bit)==0) { + if (*p > 0) + *p += bit; + else + *p -= bit; + } + } else { + if (r == 0) { + *p = (short) s; + break; + } + --r; + } + } + } while (k <= j->spec_end); + } + } + return 1; +} + +// take a -128..127 value and stbi__clamp it and convert to 0..255 +stbi_inline static stbi_uc stbi__clamp(int x) +{ + // trick to use a single test to catch both cases + if ((unsigned int) x > 255) { + if (x < 0) return 0; + if (x > 255) return 255; + } + return (stbi_uc) x; +} + +#define stbi__f2f(x) ((int) (((x) * 4096 + 0.5))) +#define stbi__fsh(x) ((x) * 4096) + +// derived from jidctint -- DCT_ISLOW +#define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \ + int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \ + p2 = s2; \ + p3 = s6; \ + p1 = (p2+p3) * stbi__f2f(0.5411961f); \ + t2 = p1 + p3*stbi__f2f(-1.847759065f); \ + t3 = p1 + p2*stbi__f2f( 0.765366865f); \ + p2 = s0; \ + p3 = s4; \ + t0 = stbi__fsh(p2+p3); \ + t1 = stbi__fsh(p2-p3); \ + x0 = t0+t3; \ + x3 = t0-t3; \ + x1 = t1+t2; \ + x2 = t1-t2; \ + t0 = s7; \ + t1 = s5; \ + t2 = s3; \ + t3 = s1; \ + p3 = t0+t2; \ + p4 = t1+t3; \ + p1 = t0+t3; \ + p2 = t1+t2; \ + p5 = (p3+p4)*stbi__f2f( 1.175875602f); \ + t0 = t0*stbi__f2f( 0.298631336f); \ + t1 = t1*stbi__f2f( 2.053119869f); \ + t2 = t2*stbi__f2f( 3.072711026f); \ + t3 = t3*stbi__f2f( 1.501321110f); \ + p1 = p5 + p1*stbi__f2f(-0.899976223f); \ + p2 = p5 + p2*stbi__f2f(-2.562915447f); \ + p3 = p3*stbi__f2f(-1.961570560f); \ + p4 = p4*stbi__f2f(-0.390180644f); \ + t3 += p1+p4; \ + t2 += p2+p3; \ + t1 += p2+p4; \ + t0 += p1+p3; + +static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64]) +{ + int i,val[64],*v=val; + stbi_uc *o; + short *d = data; + + // columns + for (i=0; i < 8; ++i,++d, ++v) { + // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing + if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0 + && d[40]==0 && d[48]==0 && d[56]==0) { + // no shortcut 0 seconds + // (1|2|3|4|5|6|7)==0 0 seconds + // all separate -0.047 seconds + // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds + int dcterm = d[0]*4; + v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm; + } else { + STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56]) + // constants scaled things up by 1<<12; let's bring them back + // down, but keep 2 extra bits of precision + x0 += 512; x1 += 512; x2 += 512; x3 += 512; + v[ 0] = (x0+t3) >> 10; + v[56] = (x0-t3) >> 10; + v[ 8] = (x1+t2) >> 10; + v[48] = (x1-t2) >> 10; + v[16] = (x2+t1) >> 10; + v[40] = (x2-t1) >> 10; + v[24] = (x3+t0) >> 10; + v[32] = (x3-t0) >> 10; + } + } + + for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) { + // no fast case since the first 1D IDCT spread components out + STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7]) + // constants scaled things up by 1<<12, plus we had 1<<2 from first + // loop, plus horizontal and vertical each scale by sqrt(8) so together + // we've got an extra 1<<3, so 1<<17 total we need to remove. + // so we want to round that, which means adding 0.5 * 1<<17, + // aka 65536. Also, we'll end up with -128 to 127 that we want + // to encode as 0..255 by adding 128, so we'll add that before the shift + x0 += 65536 + (128<<17); + x1 += 65536 + (128<<17); + x2 += 65536 + (128<<17); + x3 += 65536 + (128<<17); + // tried computing the shifts into temps, or'ing the temps to see + // if any were out of range, but that was slower + o[0] = stbi__clamp((x0+t3) >> 17); + o[7] = stbi__clamp((x0-t3) >> 17); + o[1] = stbi__clamp((x1+t2) >> 17); + o[6] = stbi__clamp((x1-t2) >> 17); + o[2] = stbi__clamp((x2+t1) >> 17); + o[5] = stbi__clamp((x2-t1) >> 17); + o[3] = stbi__clamp((x3+t0) >> 17); + o[4] = stbi__clamp((x3-t0) >> 17); + } +} + +#ifdef STBI_SSE2 +// sse2 integer IDCT. not the fastest possible implementation but it +// produces bit-identical results to the generic C version so it's +// fully "transparent". +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + // This is constructed to match our regular (generic) integer IDCT exactly. + __m128i row0, row1, row2, row3, row4, row5, row6, row7; + __m128i tmp; + + // dot product constant: even elems=x, odd elems=y + #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y)) + + // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit) + // out(1) = c1[even]*x + c1[odd]*y + #define dct_rot(out0,out1, x,y,c0,c1) \ + __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \ + __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \ + __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \ + __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \ + __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \ + __m128i out1##_h = _mm_madd_epi16(c0##hi, c1) + + // out = in << 12 (in 16-bit, out 32-bit) + #define dct_widen(out, in) \ + __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \ + __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4) + + // wide add + #define dct_wadd(out, a, b) \ + __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_add_epi32(a##_h, b##_h) + + // wide sub + #define dct_wsub(out, a, b) \ + __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \ + __m128i out##_h = _mm_sub_epi32(a##_h, b##_h) + + // butterfly a/b, add bias, then shift by "s" and pack + #define dct_bfly32o(out0, out1, a,b,bias,s) \ + { \ + __m128i abiased_l = _mm_add_epi32(a##_l, bias); \ + __m128i abiased_h = _mm_add_epi32(a##_h, bias); \ + dct_wadd(sum, abiased, b); \ + dct_wsub(dif, abiased, b); \ + out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \ + out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \ + } + + // 8-bit interleave step (for transposes) + #define dct_interleave8(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi8(a, b); \ + b = _mm_unpackhi_epi8(tmp, b) + + // 16-bit interleave step (for transposes) + #define dct_interleave16(a, b) \ + tmp = a; \ + a = _mm_unpacklo_epi16(a, b); \ + b = _mm_unpackhi_epi16(tmp, b) + + #define dct_pass(bias,shift) \ + { \ + /* even part */ \ + dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \ + __m128i sum04 = _mm_add_epi16(row0, row4); \ + __m128i dif04 = _mm_sub_epi16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \ + dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \ + __m128i sum17 = _mm_add_epi16(row1, row7); \ + __m128i sum35 = _mm_add_epi16(row3, row5); \ + dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \ + dct_wadd(x4, y0o, y4o); \ + dct_wadd(x5, y1o, y5o); \ + dct_wadd(x6, y2o, y5o); \ + dct_wadd(x7, y3o, y4o); \ + dct_bfly32o(row0,row7, x0,x7,bias,shift); \ + dct_bfly32o(row1,row6, x1,x6,bias,shift); \ + dct_bfly32o(row2,row5, x2,x5,bias,shift); \ + dct_bfly32o(row3,row4, x3,x4,bias,shift); \ + } + + __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f)); + __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f)); + __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f)); + __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f)); + __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f)); + __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f)); + __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f)); + __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f)); + + // rounding biases in column/row passes, see stbi__idct_block for explanation. + __m128i bias_0 = _mm_set1_epi32(512); + __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17)); + + // load + row0 = _mm_load_si128((const __m128i *) (data + 0*8)); + row1 = _mm_load_si128((const __m128i *) (data + 1*8)); + row2 = _mm_load_si128((const __m128i *) (data + 2*8)); + row3 = _mm_load_si128((const __m128i *) (data + 3*8)); + row4 = _mm_load_si128((const __m128i *) (data + 4*8)); + row5 = _mm_load_si128((const __m128i *) (data + 5*8)); + row6 = _mm_load_si128((const __m128i *) (data + 6*8)); + row7 = _mm_load_si128((const __m128i *) (data + 7*8)); + + // column pass + dct_pass(bias_0, 10); + + { + // 16bit 8x8 transpose pass 1 + dct_interleave16(row0, row4); + dct_interleave16(row1, row5); + dct_interleave16(row2, row6); + dct_interleave16(row3, row7); + + // transpose pass 2 + dct_interleave16(row0, row2); + dct_interleave16(row1, row3); + dct_interleave16(row4, row6); + dct_interleave16(row5, row7); + + // transpose pass 3 + dct_interleave16(row0, row1); + dct_interleave16(row2, row3); + dct_interleave16(row4, row5); + dct_interleave16(row6, row7); + } + + // row pass + dct_pass(bias_1, 17); + + { + // pack + __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7 + __m128i p1 = _mm_packus_epi16(row2, row3); + __m128i p2 = _mm_packus_epi16(row4, row5); + __m128i p3 = _mm_packus_epi16(row6, row7); + + // 8bit 8x8 transpose pass 1 + dct_interleave8(p0, p2); // a0e0a1e1... + dct_interleave8(p1, p3); // c0g0c1g1... + + // transpose pass 2 + dct_interleave8(p0, p1); // a0c0e0g0... + dct_interleave8(p2, p3); // b0d0f0h0... + + // transpose pass 3 + dct_interleave8(p0, p2); // a0b0c0d0... + dct_interleave8(p1, p3); // a4b4c4d4... + + // store + _mm_storel_epi64((__m128i *) out, p0); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p2); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p1); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride; + _mm_storel_epi64((__m128i *) out, p3); out += out_stride; + _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e)); + } + +#undef dct_const +#undef dct_rot +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_interleave8 +#undef dct_interleave16 +#undef dct_pass +} + +#endif // STBI_SSE2 + +#ifdef STBI_NEON + +// NEON integer IDCT. should produce bit-identical +// results to the generic C version. +static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64]) +{ + int16x8_t row0, row1, row2, row3, row4, row5, row6, row7; + + int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f)); + int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f)); + int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f)); + int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f)); + int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f)); + int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f)); + int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f)); + int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f)); + int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f)); + int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f)); + int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f)); + int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f)); + +#define dct_long_mul(out, inq, coeff) \ + int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff) + +#define dct_long_mac(out, acc, inq, coeff) \ + int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \ + int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff) + +#define dct_widen(out, inq) \ + int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \ + int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12) + +// wide add +#define dct_wadd(out, a, b) \ + int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vaddq_s32(a##_h, b##_h) + +// wide sub +#define dct_wsub(out, a, b) \ + int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \ + int32x4_t out##_h = vsubq_s32(a##_h, b##_h) + +// butterfly a/b, then shift using "shiftop" by "s" and pack +#define dct_bfly32o(out0,out1, a,b,shiftop,s) \ + { \ + dct_wadd(sum, a, b); \ + dct_wsub(dif, a, b); \ + out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \ + out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \ + } + +#define dct_pass(shiftop, shift) \ + { \ + /* even part */ \ + int16x8_t sum26 = vaddq_s16(row2, row6); \ + dct_long_mul(p1e, sum26, rot0_0); \ + dct_long_mac(t2e, p1e, row6, rot0_1); \ + dct_long_mac(t3e, p1e, row2, rot0_2); \ + int16x8_t sum04 = vaddq_s16(row0, row4); \ + int16x8_t dif04 = vsubq_s16(row0, row4); \ + dct_widen(t0e, sum04); \ + dct_widen(t1e, dif04); \ + dct_wadd(x0, t0e, t3e); \ + dct_wsub(x3, t0e, t3e); \ + dct_wadd(x1, t1e, t2e); \ + dct_wsub(x2, t1e, t2e); \ + /* odd part */ \ + int16x8_t sum15 = vaddq_s16(row1, row5); \ + int16x8_t sum17 = vaddq_s16(row1, row7); \ + int16x8_t sum35 = vaddq_s16(row3, row5); \ + int16x8_t sum37 = vaddq_s16(row3, row7); \ + int16x8_t sumodd = vaddq_s16(sum17, sum35); \ + dct_long_mul(p5o, sumodd, rot1_0); \ + dct_long_mac(p1o, p5o, sum17, rot1_1); \ + dct_long_mac(p2o, p5o, sum35, rot1_2); \ + dct_long_mul(p3o, sum37, rot2_0); \ + dct_long_mul(p4o, sum15, rot2_1); \ + dct_wadd(sump13o, p1o, p3o); \ + dct_wadd(sump24o, p2o, p4o); \ + dct_wadd(sump23o, p2o, p3o); \ + dct_wadd(sump14o, p1o, p4o); \ + dct_long_mac(x4, sump13o, row7, rot3_0); \ + dct_long_mac(x5, sump24o, row5, rot3_1); \ + dct_long_mac(x6, sump23o, row3, rot3_2); \ + dct_long_mac(x7, sump14o, row1, rot3_3); \ + dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \ + dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \ + dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \ + dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \ + } + + // load + row0 = vld1q_s16(data + 0*8); + row1 = vld1q_s16(data + 1*8); + row2 = vld1q_s16(data + 2*8); + row3 = vld1q_s16(data + 3*8); + row4 = vld1q_s16(data + 4*8); + row5 = vld1q_s16(data + 5*8); + row6 = vld1q_s16(data + 6*8); + row7 = vld1q_s16(data + 7*8); + + // add DC bias + row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0)); + + // column pass + dct_pass(vrshrn_n_s32, 10); + + // 16bit 8x8 transpose + { +// these three map to a single VTRN.16, VTRN.32, and VSWP, respectively. +// whether compilers actually get this is another story, sadly. +#define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); } +#define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); } + + // pass 1 + dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6 + dct_trn16(row2, row3); + dct_trn16(row4, row5); + dct_trn16(row6, row7); + + // pass 2 + dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4 + dct_trn32(row1, row3); + dct_trn32(row4, row6); + dct_trn32(row5, row7); + + // pass 3 + dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0 + dct_trn64(row1, row5); + dct_trn64(row2, row6); + dct_trn64(row3, row7); + +#undef dct_trn16 +#undef dct_trn32 +#undef dct_trn64 + } + + // row pass + // vrshrn_n_s32 only supports shifts up to 16, we need + // 17. so do a non-rounding shift of 16 first then follow + // up with a rounding shift by 1. + dct_pass(vshrn_n_s32, 16); + + { + // pack and round + uint8x8_t p0 = vqrshrun_n_s16(row0, 1); + uint8x8_t p1 = vqrshrun_n_s16(row1, 1); + uint8x8_t p2 = vqrshrun_n_s16(row2, 1); + uint8x8_t p3 = vqrshrun_n_s16(row3, 1); + uint8x8_t p4 = vqrshrun_n_s16(row4, 1); + uint8x8_t p5 = vqrshrun_n_s16(row5, 1); + uint8x8_t p6 = vqrshrun_n_s16(row6, 1); + uint8x8_t p7 = vqrshrun_n_s16(row7, 1); + + // again, these can translate into one instruction, but often don't. +#define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; } +#define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); } +#define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); } + + // sadly can't use interleaved stores here since we only write + // 8 bytes to each scan line! + + // 8x8 8-bit transpose pass 1 + dct_trn8_8(p0, p1); + dct_trn8_8(p2, p3); + dct_trn8_8(p4, p5); + dct_trn8_8(p6, p7); + + // pass 2 + dct_trn8_16(p0, p2); + dct_trn8_16(p1, p3); + dct_trn8_16(p4, p6); + dct_trn8_16(p5, p7); + + // pass 3 + dct_trn8_32(p0, p4); + dct_trn8_32(p1, p5); + dct_trn8_32(p2, p6); + dct_trn8_32(p3, p7); + + // store + vst1_u8(out, p0); out += out_stride; + vst1_u8(out, p1); out += out_stride; + vst1_u8(out, p2); out += out_stride; + vst1_u8(out, p3); out += out_stride; + vst1_u8(out, p4); out += out_stride; + vst1_u8(out, p5); out += out_stride; + vst1_u8(out, p6); out += out_stride; + vst1_u8(out, p7); + +#undef dct_trn8_8 +#undef dct_trn8_16 +#undef dct_trn8_32 + } + +#undef dct_long_mul +#undef dct_long_mac +#undef dct_widen +#undef dct_wadd +#undef dct_wsub +#undef dct_bfly32o +#undef dct_pass +} + +#endif // STBI_NEON + +#define STBI__MARKER_none 0xff +// if there's a pending marker from the entropy stream, return that +// otherwise, fetch from the stream and get a marker. if there's no +// marker, return 0xff, which is never a valid marker value +static stbi_uc stbi__get_marker(stbi__jpeg *j) +{ + stbi_uc x; + if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; } + x = stbi__get8(j->s); + if (x != 0xff) return STBI__MARKER_none; + while (x == 0xff) + x = stbi__get8(j->s); // consume repeated 0xff fill bytes + return x; +} + +// in each scan, we'll have scan_n components, and the order +// of the components is specified by order[] +#define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7) + +// after a restart interval, stbi__jpeg_reset the entropy decoder and +// the dc prediction +static void stbi__jpeg_reset(stbi__jpeg *j) +{ + j->code_bits = 0; + j->code_buffer = 0; + j->nomore = 0; + j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = j->img_comp[3].dc_pred = 0; + j->marker = STBI__MARKER_none; + j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff; + j->eob_run = 0; + // no more than 1<<31 MCUs if no restart_interal? that's plenty safe, + // since we don't even allow 1<<30 pixels +} + +static int stbi__parse_entropy_coded_data(stbi__jpeg *z) +{ + stbi__jpeg_reset(z); + if (!z->progressive) { + if (z->scan_n == 1) { + int i,j; + STBI_SIMD_ALIGN(short, data[64]); + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + // if it's NOT a restart, then just bail, so we get corrupt data + // rather than no data + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + STBI_SIMD_ALIGN(short, data[64]); + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x)*8; + int y2 = (j*z->img_comp[n].v + y)*8; + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0; + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data); + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } else { + if (z->scan_n == 1) { + int i,j; + int n = z->order[0]; + // non-interleaved data, we just need to process one block at a time, + // in trivial scanline order + // number of blocks to do just depends on how many actual "pixels" this + // component has, independent of interleaved MCU blocking and such + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + if (z->spec_start == 0) { + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } else { + int ha = z->img_comp[n].ha; + if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha])) + return 0; + } + // every data block is an MCU, so countdown the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } else { // interleaved + int i,j,k,x,y; + for (j=0; j < z->img_mcu_y; ++j) { + for (i=0; i < z->img_mcu_x; ++i) { + // scan an interleaved mcu... process scan_n components in order + for (k=0; k < z->scan_n; ++k) { + int n = z->order[k]; + // scan out an mcu's worth of this component; that's just determined + // by the basic H and V specified for the component + for (y=0; y < z->img_comp[n].v; ++y) { + for (x=0; x < z->img_comp[n].h; ++x) { + int x2 = (i*z->img_comp[n].h + x); + int y2 = (j*z->img_comp[n].v + y); + short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w); + if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n)) + return 0; + } + } + } + // after all interleaved components, that's an interleaved MCU, + // so now count down the restart interval + if (--z->todo <= 0) { + if (z->code_bits < 24) stbi__grow_buffer_unsafe(z); + if (!STBI__RESTART(z->marker)) return 1; + stbi__jpeg_reset(z); + } + } + } + return 1; + } + } +} + +static void stbi__jpeg_dequantize(short *data, stbi__uint16 *dequant) +{ + int i; + for (i=0; i < 64; ++i) + data[i] *= dequant[i]; +} + +static void stbi__jpeg_finish(stbi__jpeg *z) +{ + if (z->progressive) { + // dequantize and idct the data + int i,j,n; + for (n=0; n < z->s->img_n; ++n) { + int w = (z->img_comp[n].x+7) >> 3; + int h = (z->img_comp[n].y+7) >> 3; + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) { + short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w); + stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]); + z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data); + } + } + } + } +} + +static int stbi__process_marker(stbi__jpeg *z, int m) +{ + int L; + switch (m) { + case STBI__MARKER_none: // no marker found + return stbi__err("expected marker","Corrupt JPEG"); + + case 0xDD: // DRI - specify restart interval + if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG"); + z->restart_interval = stbi__get16be(z->s); + return 1; + + case 0xDB: // DQT - define quantization table + L = stbi__get16be(z->s)-2; + while (L > 0) { + int q = stbi__get8(z->s); + int p = q >> 4, sixteen = (p != 0); + int t = q & 15,i; + if (p != 0 && p != 1) return stbi__err("bad DQT type","Corrupt JPEG"); + if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG"); + + for (i=0; i < 64; ++i) + z->dequant[t][stbi__jpeg_dezigzag[i]] = (stbi__uint16)(sixteen ? stbi__get16be(z->s) : stbi__get8(z->s)); + L -= (sixteen ? 129 : 65); + } + return L==0; + + case 0xC4: // DHT - define huffman table + L = stbi__get16be(z->s)-2; + while (L > 0) { + stbi_uc *v; + int sizes[16],i,n=0; + int q = stbi__get8(z->s); + int tc = q >> 4; + int th = q & 15; + if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG"); + for (i=0; i < 16; ++i) { + sizes[i] = stbi__get8(z->s); + n += sizes[i]; + } + if(n > 256) return stbi__err("bad DHT header","Corrupt JPEG"); // Loop over i < n would write past end of values! + L -= 17; + if (tc == 0) { + if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0; + v = z->huff_dc[th].values; + } else { + if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0; + v = z->huff_ac[th].values; + } + for (i=0; i < n; ++i) + v[i] = stbi__get8(z->s); + if (tc != 0) + stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th); + L -= n; + } + return L==0; + } + + // check for comment block or APP blocks + if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) { + L = stbi__get16be(z->s); + if (L < 2) { + if (m == 0xFE) + return stbi__err("bad COM len","Corrupt JPEG"); + else + return stbi__err("bad APP len","Corrupt JPEG"); + } + L -= 2; + + if (m == 0xE0 && L >= 5) { // JFIF APP0 segment + static const unsigned char tag[5] = {'J','F','I','F','\0'}; + int ok = 1; + int i; + for (i=0; i < 5; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 5; + if (ok) + z->jfif = 1; + } else if (m == 0xEE && L >= 12) { // Adobe APP14 segment + static const unsigned char tag[6] = {'A','d','o','b','e','\0'}; + int ok = 1; + int i; + for (i=0; i < 6; ++i) + if (stbi__get8(z->s) != tag[i]) + ok = 0; + L -= 6; + if (ok) { + stbi__get8(z->s); // version + stbi__get16be(z->s); // flags0 + stbi__get16be(z->s); // flags1 + z->app14_color_transform = stbi__get8(z->s); // color transform + L -= 6; + } + } + + stbi__skip(z->s, L); + return 1; + } + + return stbi__err("unknown marker","Corrupt JPEG"); +} + +// after we see SOS +static int stbi__process_scan_header(stbi__jpeg *z) +{ + int i; + int Ls = stbi__get16be(z->s); + z->scan_n = stbi__get8(z->s); + if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG"); + if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG"); + for (i=0; i < z->scan_n; ++i) { + int id = stbi__get8(z->s), which; + int q = stbi__get8(z->s); + for (which = 0; which < z->s->img_n; ++which) + if (z->img_comp[which].id == id) + break; + if (which == z->s->img_n) return 0; // no match + z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG"); + z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG"); + z->order[i] = which; + } + + { + int aa; + z->spec_start = stbi__get8(z->s); + z->spec_end = stbi__get8(z->s); // should be 63, but might be 0 + aa = stbi__get8(z->s); + z->succ_high = (aa >> 4); + z->succ_low = (aa & 15); + if (z->progressive) { + if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13) + return stbi__err("bad SOS", "Corrupt JPEG"); + } else { + if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG"); + if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG"); + z->spec_end = 63; + } + } + + return 1; +} + +static int stbi__free_jpeg_components(stbi__jpeg *z, int ncomp, int why) +{ + int i; + for (i=0; i < ncomp; ++i) { + if (z->img_comp[i].raw_data) { + STBI_FREE(z->img_comp[i].raw_data); + z->img_comp[i].raw_data = NULL; + z->img_comp[i].data = NULL; + } + if (z->img_comp[i].raw_coeff) { + STBI_FREE(z->img_comp[i].raw_coeff); + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].coeff = 0; + } + if (z->img_comp[i].linebuf) { + STBI_FREE(z->img_comp[i].linebuf); + z->img_comp[i].linebuf = NULL; + } + } + return why; +} + +static int stbi__process_frame_header(stbi__jpeg *z, int scan) +{ + stbi__context *s = z->s; + int Lf,p,i,q, h_max=1,v_max=1,c; + Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG + p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline + s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG + s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + c = stbi__get8(s); + if (c != 3 && c != 1 && c != 4) return stbi__err("bad component count","Corrupt JPEG"); + s->img_n = c; + for (i=0; i < c; ++i) { + z->img_comp[i].data = NULL; + z->img_comp[i].linebuf = NULL; + } + + if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG"); + + z->rgb = 0; + for (i=0; i < s->img_n; ++i) { + static const unsigned char rgb[3] = { 'R', 'G', 'B' }; + z->img_comp[i].id = stbi__get8(s); + if (s->img_n == 3 && z->img_comp[i].id == rgb[i]) + ++z->rgb; + q = stbi__get8(s); + z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG"); + z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG"); + z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG"); + } + + if (scan != STBI__SCAN_load) return 1; + + if (!stbi__mad3sizes_valid(s->img_x, s->img_y, s->img_n, 0)) return stbi__err("too large", "Image too large to decode"); + + for (i=0; i < s->img_n; ++i) { + if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h; + if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v; + } + + // check that plane subsampling factors are integer ratios; our resamplers can't deal with fractional ratios + // and I've never seen a non-corrupted JPEG file actually use them + for (i=0; i < s->img_n; ++i) { + if (h_max % z->img_comp[i].h != 0) return stbi__err("bad H","Corrupt JPEG"); + if (v_max % z->img_comp[i].v != 0) return stbi__err("bad V","Corrupt JPEG"); + } + + // compute interleaved mcu info + z->img_h_max = h_max; + z->img_v_max = v_max; + z->img_mcu_w = h_max * 8; + z->img_mcu_h = v_max * 8; + // these sizes can't be more than 17 bits + z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w; + z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h; + + for (i=0; i < s->img_n; ++i) { + // number of effective pixels (e.g. for non-interleaved MCU) + z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max; + z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max; + // to simplify generation, we'll allocate enough memory to decode + // the bogus oversized data from using interleaved MCUs and their + // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't + // discard the extra data until colorspace conversion + // + // img_mcu_x, img_mcu_y: <=17 bits; comp[i].h and .v are <=4 (checked earlier) + // so these muls can't overflow with 32-bit ints (which we require) + z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8; + z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8; + z->img_comp[i].coeff = 0; + z->img_comp[i].raw_coeff = 0; + z->img_comp[i].linebuf = NULL; + z->img_comp[i].raw_data = stbi__malloc_mad2(z->img_comp[i].w2, z->img_comp[i].h2, 15); + if (z->img_comp[i].raw_data == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + // align blocks for idct using mmx/sse + z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15); + if (z->progressive) { + // w2, h2 are multiples of 8 (see above) + z->img_comp[i].coeff_w = z->img_comp[i].w2 / 8; + z->img_comp[i].coeff_h = z->img_comp[i].h2 / 8; + z->img_comp[i].raw_coeff = stbi__malloc_mad3(z->img_comp[i].w2, z->img_comp[i].h2, sizeof(short), 15); + if (z->img_comp[i].raw_coeff == NULL) + return stbi__free_jpeg_components(z, i+1, stbi__err("outofmem", "Out of memory")); + z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15); + } + } + + return 1; +} + +// use comparisons since in some cases we handle more than one case (e.g. SOF) +#define stbi__DNL(x) ((x) == 0xdc) +#define stbi__SOI(x) ((x) == 0xd8) +#define stbi__EOI(x) ((x) == 0xd9) +#define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2) +#define stbi__SOS(x) ((x) == 0xda) + +#define stbi__SOF_progressive(x) ((x) == 0xc2) + +static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan) +{ + int m; + z->jfif = 0; + z->app14_color_transform = -1; // valid values are 0,1,2 + z->marker = STBI__MARKER_none; // initialize cached marker to empty + m = stbi__get_marker(z); + if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG"); + if (scan == STBI__SCAN_type) return 1; + m = stbi__get_marker(z); + while (!stbi__SOF(m)) { + if (!stbi__process_marker(z,m)) return 0; + m = stbi__get_marker(z); + while (m == STBI__MARKER_none) { + // some files have extra padding after their blocks, so ok, we'll scan + if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG"); + m = stbi__get_marker(z); + } + } + z->progressive = stbi__SOF_progressive(m); + if (!stbi__process_frame_header(z, scan)) return 0; + return 1; +} + +static stbi_uc stbi__skip_jpeg_junk_at_end(stbi__jpeg *j) +{ + // some JPEGs have junk at end, skip over it but if we find what looks + // like a valid marker, resume there + while (!stbi__at_eof(j->s)) { + stbi_uc x = stbi__get8(j->s); + while (x == 0xff) { // might be a marker + if (stbi__at_eof(j->s)) return STBI__MARKER_none; + x = stbi__get8(j->s); + if (x != 0x00 && x != 0xff) { + // not a stuffed zero or lead-in to another marker, looks + // like an actual marker, return it + return x; + } + // stuffed zero has x=0 now which ends the loop, meaning we go + // back to regular scan loop. + // repeated 0xff keeps trying to read the next byte of the marker. + } + } + return STBI__MARKER_none; +} + +// decode image to YCbCr format +static int stbi__decode_jpeg_image(stbi__jpeg *j) +{ + int m; + for (m = 0; m < 4; m++) { + j->img_comp[m].raw_data = NULL; + j->img_comp[m].raw_coeff = NULL; + } + j->restart_interval = 0; + if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0; + m = stbi__get_marker(j); + while (!stbi__EOI(m)) { + if (stbi__SOS(m)) { + if (!stbi__process_scan_header(j)) return 0; + if (!stbi__parse_entropy_coded_data(j)) return 0; + if (j->marker == STBI__MARKER_none ) { + j->marker = stbi__skip_jpeg_junk_at_end(j); + // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0 + } + m = stbi__get_marker(j); + if (STBI__RESTART(m)) + m = stbi__get_marker(j); + } else if (stbi__DNL(m)) { + int Ld = stbi__get16be(j->s); + stbi__uint32 NL = stbi__get16be(j->s); + if (Ld != 4) return stbi__err("bad DNL len", "Corrupt JPEG"); + if (NL != j->s->img_y) return stbi__err("bad DNL height", "Corrupt JPEG"); + m = stbi__get_marker(j); + } else { + if (!stbi__process_marker(j, m)) return 1; + m = stbi__get_marker(j); + } + } + if (j->progressive) + stbi__jpeg_finish(j); + return 1; +} + +// static jfif-centered resampling (across block boundaries) + +typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1, + int w, int hs); + +#define stbi__div4(x) ((stbi_uc) ((x) >> 2)) + +static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + STBI_NOTUSED(out); + STBI_NOTUSED(in_far); + STBI_NOTUSED(w); + STBI_NOTUSED(hs); + return in_near; +} + +static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples vertically for every one in input + int i; + STBI_NOTUSED(hs); + for (i=0; i < w; ++i) + out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2); + return out; +} + +static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate two samples horizontally for every one in input + int i; + stbi_uc *input = in_near; + + if (w == 1) { + // if only one sample, can't do any interpolation + out[0] = out[1] = input[0]; + return out; + } + + out[0] = input[0]; + out[1] = stbi__div4(input[0]*3 + input[1] + 2); + for (i=1; i < w-1; ++i) { + int n = 3*input[i]+2; + out[i*2+0] = stbi__div4(n+input[i-1]); + out[i*2+1] = stbi__div4(n+input[i+1]); + } + out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2); + out[i*2+1] = input[w-1]; + + STBI_NOTUSED(in_far); + STBI_NOTUSED(hs); + + return out; +} + +#define stbi__div16(x) ((stbi_uc) ((x) >> 4)) + +static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i,t0,t1; + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + out[0] = stbi__div4(t1+2); + for (i=1; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // need to generate 2x2 samples for every one in input + int i=0,t0,t1; + + if (w == 1) { + out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2); + return out; + } + + t1 = 3*in_near[0] + in_far[0]; + // process groups of 8 pixels for as long as we can. + // note we can't handle the last pixel in a row in this loop + // because we need to handle the filter boundary conditions. + for (; i < ((w-1) & ~7); i += 8) { +#if defined(STBI_SSE2) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + __m128i zero = _mm_setzero_si128(); + __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i)); + __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i)); + __m128i farw = _mm_unpacklo_epi8(farb, zero); + __m128i nearw = _mm_unpacklo_epi8(nearb, zero); + __m128i diff = _mm_sub_epi16(farw, nearw); + __m128i nears = _mm_slli_epi16(nearw, 2); + __m128i curr = _mm_add_epi16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + __m128i prv0 = _mm_slli_si128(curr, 2); + __m128i nxt0 = _mm_srli_si128(curr, 2); + __m128i prev = _mm_insert_epi16(prv0, t1, 0); + __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + __m128i bias = _mm_set1_epi16(8); + __m128i curs = _mm_slli_epi16(curr, 2); + __m128i prvd = _mm_sub_epi16(prev, curr); + __m128i nxtd = _mm_sub_epi16(next, curr); + __m128i curb = _mm_add_epi16(curs, bias); + __m128i even = _mm_add_epi16(prvd, curb); + __m128i odd = _mm_add_epi16(nxtd, curb); + + // interleave even and odd pixels, then undo scaling. + __m128i int0 = _mm_unpacklo_epi16(even, odd); + __m128i int1 = _mm_unpackhi_epi16(even, odd); + __m128i de0 = _mm_srli_epi16(int0, 4); + __m128i de1 = _mm_srli_epi16(int1, 4); + + // pack and write output + __m128i outv = _mm_packus_epi16(de0, de1); + _mm_storeu_si128((__m128i *) (out + i*2), outv); +#elif defined(STBI_NEON) + // load and perform the vertical filtering pass + // this uses 3*x + y = 4*x + (y - x) + uint8x8_t farb = vld1_u8(in_far + i); + uint8x8_t nearb = vld1_u8(in_near + i); + int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb)); + int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2)); + int16x8_t curr = vaddq_s16(nears, diff); // current row + + // horizontal filter works the same based on shifted vers of current + // row. "prev" is current row shifted right by 1 pixel; we need to + // insert the previous pixel value (from t1). + // "next" is current row shifted left by 1 pixel, with first pixel + // of next block of 8 pixels added in. + int16x8_t prv0 = vextq_s16(curr, curr, 7); + int16x8_t nxt0 = vextq_s16(curr, curr, 1); + int16x8_t prev = vsetq_lane_s16(t1, prv0, 0); + int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7); + + // horizontal filter, polyphase implementation since it's convenient: + // even pixels = 3*cur + prev = cur*4 + (prev - cur) + // odd pixels = 3*cur + next = cur*4 + (next - cur) + // note the shared term. + int16x8_t curs = vshlq_n_s16(curr, 2); + int16x8_t prvd = vsubq_s16(prev, curr); + int16x8_t nxtd = vsubq_s16(next, curr); + int16x8_t even = vaddq_s16(curs, prvd); + int16x8_t odd = vaddq_s16(curs, nxtd); + + // undo scaling and round, then store with even/odd phases interleaved + uint8x8x2_t o; + o.val[0] = vqrshrun_n_s16(even, 4); + o.val[1] = vqrshrun_n_s16(odd, 4); + vst2_u8(out + i*2, o); +#endif + + // "previous" value for next iter + t1 = 3*in_near[i+7] + in_far[i+7]; + } + + t0 = t1; + t1 = 3*in_near[i] + in_far[i]; + out[i*2] = stbi__div16(3*t1 + t0 + 8); + + for (++i; i < w; ++i) { + t0 = t1; + t1 = 3*in_near[i]+in_far[i]; + out[i*2-1] = stbi__div16(3*t0 + t1 + 8); + out[i*2 ] = stbi__div16(3*t1 + t0 + 8); + } + out[w*2-1] = stbi__div4(t1+2); + + STBI_NOTUSED(hs); + + return out; +} +#endif + +static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs) +{ + // resample with nearest-neighbor + int i,j; + STBI_NOTUSED(in_far); + for (i=0; i < w; ++i) + for (j=0; j < hs; ++j) + out[i*hs+j] = in_near[i]; + return out; +} + +// this is a reduced-precision calculation of YCbCr-to-RGB introduced +// to make sure the code produces the same results in both SIMD and scalar +#define stbi__float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8) +static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step) +{ + int i; + for (i=0; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + (cr*-stbi__float2fixed(0.71414f)) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} + +#if defined(STBI_SSE2) || defined(STBI_NEON) +static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step) +{ + int i = 0; + +#ifdef STBI_SSE2 + // step == 3 is pretty ugly on the final interleave, and i'm not convinced + // it's useful in practice (you wouldn't use it for textures, for example). + // so just accelerate step == 4 case. + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + __m128i signflip = _mm_set1_epi8(-0x80); + __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f)); + __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f)); + __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f)); + __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f)); + __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128); + __m128i xw = _mm_set1_epi16(255); // alpha channel + + for (; i+7 < count; i += 8) { + // load + __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i)); + __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i)); + __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i)); + __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128 + __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128 + + // unpack to short (and left-shift cr, cb by 8) + __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes); + __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased); + __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased); + + // color transform + __m128i yws = _mm_srli_epi16(yw, 4); + __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw); + __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw); + __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1); + __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1); + __m128i rws = _mm_add_epi16(cr0, yws); + __m128i gwt = _mm_add_epi16(cb0, yws); + __m128i bws = _mm_add_epi16(yws, cb1); + __m128i gws = _mm_add_epi16(gwt, cr1); + + // descale + __m128i rw = _mm_srai_epi16(rws, 4); + __m128i bw = _mm_srai_epi16(bws, 4); + __m128i gw = _mm_srai_epi16(gws, 4); + + // back to byte, set up for transpose + __m128i brb = _mm_packus_epi16(rw, bw); + __m128i gxb = _mm_packus_epi16(gw, xw); + + // transpose to interleave channels + __m128i t0 = _mm_unpacklo_epi8(brb, gxb); + __m128i t1 = _mm_unpackhi_epi8(brb, gxb); + __m128i o0 = _mm_unpacklo_epi16(t0, t1); + __m128i o1 = _mm_unpackhi_epi16(t0, t1); + + // store + _mm_storeu_si128((__m128i *) (out + 0), o0); + _mm_storeu_si128((__m128i *) (out + 16), o1); + out += 32; + } + } +#endif + +#ifdef STBI_NEON + // in this version, step=3 support would be easy to add. but is there demand? + if (step == 4) { + // this is a fairly straightforward implementation and not super-optimized. + uint8x8_t signflip = vdup_n_u8(0x80); + int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f)); + int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f)); + int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f)); + int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f)); + + for (; i+7 < count; i += 8) { + // load + uint8x8_t y_bytes = vld1_u8(y + i); + uint8x8_t cr_bytes = vld1_u8(pcr + i); + uint8x8_t cb_bytes = vld1_u8(pcb + i); + int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip)); + int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip)); + + // expand to s16 + int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4)); + int16x8_t crw = vshll_n_s8(cr_biased, 7); + int16x8_t cbw = vshll_n_s8(cb_biased, 7); + + // color transform + int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0); + int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0); + int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1); + int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1); + int16x8_t rws = vaddq_s16(yws, cr0); + int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1); + int16x8_t bws = vaddq_s16(yws, cb1); + + // undo scaling, round, convert to byte + uint8x8x4_t o; + o.val[0] = vqrshrun_n_s16(rws, 4); + o.val[1] = vqrshrun_n_s16(gws, 4); + o.val[2] = vqrshrun_n_s16(bws, 4); + o.val[3] = vdup_n_u8(255); + + // store, interleaving r/g/b/a + vst4_u8(out, o); + out += 8*4; + } + } +#endif + + for (; i < count; ++i) { + int y_fixed = (y[i] << 20) + (1<<19); // rounding + int r,g,b; + int cr = pcr[i] - 128; + int cb = pcb[i] - 128; + r = y_fixed + cr* stbi__float2fixed(1.40200f); + g = y_fixed + cr*-stbi__float2fixed(0.71414f) + ((cb*-stbi__float2fixed(0.34414f)) & 0xffff0000); + b = y_fixed + cb* stbi__float2fixed(1.77200f); + r >>= 20; + g >>= 20; + b >>= 20; + if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; } + if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; } + if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; } + out[0] = (stbi_uc)r; + out[1] = (stbi_uc)g; + out[2] = (stbi_uc)b; + out[3] = 255; + out += step; + } +} +#endif + +// set up the kernels +static void stbi__setup_jpeg(stbi__jpeg *j) +{ + j->idct_block_kernel = stbi__idct_block; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2; + +#ifdef STBI_SSE2 + if (stbi__sse2_available()) { + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; + } +#endif + +#ifdef STBI_NEON + j->idct_block_kernel = stbi__idct_simd; + j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd; + j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd; +#endif +} + +// clean up the temporary component buffers +static void stbi__cleanup_jpeg(stbi__jpeg *j) +{ + stbi__free_jpeg_components(j, j->s->img_n, 0); +} + +typedef struct +{ + resample_row_func resample; + stbi_uc *line0,*line1; + int hs,vs; // expansion factor in each axis + int w_lores; // horizontal pixels pre-expansion + int ystep; // how far through vertical expansion we are + int ypos; // which pre-expansion row we're on +} stbi__resample; + +// fast 0..255 * 0..255 => 0..255 rounded multiplication +static stbi_uc stbi__blinn_8x8(stbi_uc x, stbi_uc y) +{ + unsigned int t = x*y + 128; + return (stbi_uc) ((t + (t >>8)) >> 8); +} + +static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp) +{ + int n, decode_n, is_rgb; + z->s->img_n = 0; // make stbi__cleanup_jpeg safe + + // validate req_comp + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + + // load a jpeg image from whichever source, but leave in YCbCr format + if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; } + + // determine actual number of components to generate + n = req_comp ? req_comp : z->s->img_n >= 3 ? 3 : 1; + + is_rgb = z->s->img_n == 3 && (z->rgb == 3 || (z->app14_color_transform == 0 && !z->jfif)); + + if (z->s->img_n == 3 && n < 3 && !is_rgb) + decode_n = 1; + else + decode_n = z->s->img_n; + + // nothing to do if no components requested; check this now to avoid + // accessing uninitialized coutput[0] later + if (decode_n <= 0) { stbi__cleanup_jpeg(z); return NULL; } + + // resample and color-convert + { + int k; + unsigned int i,j; + stbi_uc *output; + stbi_uc *coutput[4] = { NULL, NULL, NULL, NULL }; + + stbi__resample res_comp[4]; + + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + + // allocate line buffer big enough for upsampling off the edges + // with upsample factor of 4 + z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3); + if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + r->hs = z->img_h_max / z->img_comp[k].h; + r->vs = z->img_v_max / z->img_comp[k].v; + r->ystep = r->vs >> 1; + r->w_lores = (z->s->img_x + r->hs-1) / r->hs; + r->ypos = 0; + r->line0 = r->line1 = z->img_comp[k].data; + + if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1; + else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2; + else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2; + else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel; + else r->resample = stbi__resample_row_generic; + } + + // can't error after this so, this is safe + output = (stbi_uc *) stbi__malloc_mad3(n, z->s->img_x, z->s->img_y, 1); + if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); } + + // now go ahead and resample + for (j=0; j < z->s->img_y; ++j) { + stbi_uc *out = output + n * z->s->img_x * j; + for (k=0; k < decode_n; ++k) { + stbi__resample *r = &res_comp[k]; + int y_bot = r->ystep >= (r->vs >> 1); + coutput[k] = r->resample(z->img_comp[k].linebuf, + y_bot ? r->line1 : r->line0, + y_bot ? r->line0 : r->line1, + r->w_lores, r->hs); + if (++r->ystep >= r->vs) { + r->ystep = 0; + r->line0 = r->line1; + if (++r->ypos < z->img_comp[k].y) + r->line1 += z->img_comp[k].w2; + } + } + if (n >= 3) { + stbi_uc *y = coutput[0]; + if (z->s->img_n == 3) { + if (is_rgb) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = y[i]; + out[1] = coutput[1][i]; + out[2] = coutput[2][i]; + out[3] = 255; + out += n; + } + } else { + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else if (z->s->img_n == 4) { + if (z->app14_color_transform == 0) { // CMYK + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(coutput[0][i], m); + out[1] = stbi__blinn_8x8(coutput[1][i], m); + out[2] = stbi__blinn_8x8(coutput[2][i], m); + out[3] = 255; + out += n; + } + } else if (z->app14_color_transform == 2) { // YCCK + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + out[0] = stbi__blinn_8x8(255 - out[0], m); + out[1] = stbi__blinn_8x8(255 - out[1], m); + out[2] = stbi__blinn_8x8(255 - out[2], m); + out += n; + } + } else { // YCbCr + alpha? Ignore the fourth channel for now + z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n); + } + } else + for (i=0; i < z->s->img_x; ++i) { + out[0] = out[1] = out[2] = y[i]; + out[3] = 255; // not used if n==3 + out += n; + } + } else { + if (is_rgb) { + if (n == 1) + for (i=0; i < z->s->img_x; ++i) + *out++ = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + else { + for (i=0; i < z->s->img_x; ++i, out += 2) { + out[0] = stbi__compute_y(coutput[0][i], coutput[1][i], coutput[2][i]); + out[1] = 255; + } + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 0) { + for (i=0; i < z->s->img_x; ++i) { + stbi_uc m = coutput[3][i]; + stbi_uc r = stbi__blinn_8x8(coutput[0][i], m); + stbi_uc g = stbi__blinn_8x8(coutput[1][i], m); + stbi_uc b = stbi__blinn_8x8(coutput[2][i], m); + out[0] = stbi__compute_y(r, g, b); + out[1] = 255; + out += n; + } + } else if (z->s->img_n == 4 && z->app14_color_transform == 2) { + for (i=0; i < z->s->img_x; ++i) { + out[0] = stbi__blinn_8x8(255 - coutput[0][i], coutput[3][i]); + out[1] = 255; + out += n; + } + } else { + stbi_uc *y = coutput[0]; + if (n == 1) + for (i=0; i < z->s->img_x; ++i) out[i] = y[i]; + else + for (i=0; i < z->s->img_x; ++i) { *out++ = y[i]; *out++ = 255; } + } + } + } + stbi__cleanup_jpeg(z); + *out_x = z->s->img_x; + *out_y = z->s->img_y; + if (comp) *comp = z->s->img_n >= 3 ? 3 : 1; // report original components, not output + return output; + } +} + +static void *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + unsigned char* result; + stbi__jpeg* j = (stbi__jpeg*) stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__errpuc("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + STBI_NOTUSED(ri); + j->s = s; + stbi__setup_jpeg(j); + result = load_jpeg_image(j, x,y,comp,req_comp); + STBI_FREE(j); + return result; +} + +static int stbi__jpeg_test(stbi__context *s) +{ + int r; + stbi__jpeg* j = (stbi__jpeg*)stbi__malloc(sizeof(stbi__jpeg)); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + stbi__setup_jpeg(j); + r = stbi__decode_jpeg_header(j, STBI__SCAN_type); + stbi__rewind(s); + STBI_FREE(j); + return r; +} + +static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp) +{ + if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) { + stbi__rewind( j->s ); + return 0; + } + if (x) *x = j->s->img_x; + if (y) *y = j->s->img_y; + if (comp) *comp = j->s->img_n >= 3 ? 3 : 1; + return 1; +} + +static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp) +{ + int result; + stbi__jpeg* j = (stbi__jpeg*) (stbi__malloc(sizeof(stbi__jpeg))); + if (!j) return stbi__err("outofmem", "Out of memory"); + memset(j, 0, sizeof(stbi__jpeg)); + j->s = s; + result = stbi__jpeg_info_raw(j, x, y, comp); + STBI_FREE(j); + return result; +} +#endif + +// public domain zlib decode v0.2 Sean Barrett 2006-11-18 +// simple implementation +// - all input must be provided in an upfront buffer +// - all output is written to a single output buffer (can malloc/realloc) +// performance +// - fast huffman + +#ifndef STBI_NO_ZLIB + +// fast-way is faster to check than jpeg huffman, but slow way is slower +#define STBI__ZFAST_BITS 9 // accelerate all cases in default tables +#define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1) +#define STBI__ZNSYMS 288 // number of symbols in literal/length alphabet + +// zlib-style huffman encoding +// (jpegs packs from left, zlib from right, so can't share code) +typedef struct +{ + stbi__uint16 fast[1 << STBI__ZFAST_BITS]; + stbi__uint16 firstcode[16]; + int maxcode[17]; + stbi__uint16 firstsymbol[16]; + stbi_uc size[STBI__ZNSYMS]; + stbi__uint16 value[STBI__ZNSYMS]; +} stbi__zhuffman; + +stbi_inline static int stbi__bitreverse16(int n) +{ + n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1); + n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2); + n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4); + n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8); + return n; +} + +stbi_inline static int stbi__bit_reverse(int v, int bits) +{ + STBI_ASSERT(bits <= 16); + // to bit reverse n bits, reverse 16 and shift + // e.g. 11 bits, bit reverse and shift away 5 + return stbi__bitreverse16(v) >> (16-bits); +} + +static int stbi__zbuild_huffman(stbi__zhuffman *z, const stbi_uc *sizelist, int num) +{ + int i,k=0; + int code, next_code[16], sizes[17]; + + // DEFLATE spec for generating codes + memset(sizes, 0, sizeof(sizes)); + memset(z->fast, 0, sizeof(z->fast)); + for (i=0; i < num; ++i) + ++sizes[sizelist[i]]; + sizes[0] = 0; + for (i=1; i < 16; ++i) + if (sizes[i] > (1 << i)) + return stbi__err("bad sizes", "Corrupt PNG"); + code = 0; + for (i=1; i < 16; ++i) { + next_code[i] = code; + z->firstcode[i] = (stbi__uint16) code; + z->firstsymbol[i] = (stbi__uint16) k; + code = (code + sizes[i]); + if (sizes[i]) + if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG"); + z->maxcode[i] = code << (16-i); // preshift for inner loop + code <<= 1; + k += sizes[i]; + } + z->maxcode[16] = 0x10000; // sentinel + for (i=0; i < num; ++i) { + int s = sizelist[i]; + if (s) { + int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s]; + stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i); + z->size [c] = (stbi_uc ) s; + z->value[c] = (stbi__uint16) i; + if (s <= STBI__ZFAST_BITS) { + int j = stbi__bit_reverse(next_code[s],s); + while (j < (1 << STBI__ZFAST_BITS)) { + z->fast[j] = fastv; + j += (1 << s); + } + } + ++next_code[s]; + } + } + return 1; +} + +// zlib-from-memory implementation for PNG reading +// because PNG allows splitting the zlib stream arbitrarily, +// and it's annoying structurally to have PNG call ZLIB call PNG, +// we require PNG read all the IDATs and combine them into a single +// memory buffer + +typedef struct +{ + stbi_uc *zbuffer, *zbuffer_end; + int num_bits; + int hit_zeof_once; + stbi__uint32 code_buffer; + + char *zout; + char *zout_start; + char *zout_end; + int z_expandable; + + stbi__zhuffman z_length, z_distance; +} stbi__zbuf; + +stbi_inline static int stbi__zeof(stbi__zbuf *z) +{ + return (z->zbuffer >= z->zbuffer_end); +} + +stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z) +{ + return stbi__zeof(z) ? 0 : *z->zbuffer++; +} + +static void stbi__fill_bits(stbi__zbuf *z) +{ + do { + if (z->code_buffer >= (1U << z->num_bits)) { + z->zbuffer = z->zbuffer_end; /* treat this as EOF so we fail. */ + return; + } + z->code_buffer |= (unsigned int) stbi__zget8(z) << z->num_bits; + z->num_bits += 8; + } while (z->num_bits <= 24); +} + +stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n) +{ + unsigned int k; + if (z->num_bits < n) stbi__fill_bits(z); + k = z->code_buffer & ((1 << n) - 1); + z->code_buffer >>= n; + z->num_bits -= n; + return k; +} + +static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s,k; + // not resolved by fast table, so compute it the slow way + // use jpeg approach, which requires MSbits at top + k = stbi__bit_reverse(a->code_buffer, 16); + for (s=STBI__ZFAST_BITS+1; ; ++s) + if (k < z->maxcode[s]) + break; + if (s >= 16) return -1; // invalid code! + // code size is s, so: + b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s]; + if (b >= STBI__ZNSYMS) return -1; // some data was corrupt somewhere! + if (z->size[b] != s) return -1; // was originally an assert, but report failure instead. + a->code_buffer >>= s; + a->num_bits -= s; + return z->value[b]; +} + +stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z) +{ + int b,s; + if (a->num_bits < 16) { + if (stbi__zeof(a)) { + if (!a->hit_zeof_once) { + // This is the first time we hit eof, insert 16 extra padding btis + // to allow us to keep going; if we actually consume any of them + // though, that is invalid data. This is caught later. + a->hit_zeof_once = 1; + a->num_bits += 16; // add 16 implicit zero bits + } else { + // We already inserted our extra 16 padding bits and are again + // out, this stream is actually prematurely terminated. + return -1; + } + } else { + stbi__fill_bits(a); + } + } + b = z->fast[a->code_buffer & STBI__ZFAST_MASK]; + if (b) { + s = b >> 9; + a->code_buffer >>= s; + a->num_bits -= s; + return b & 511; + } + return stbi__zhuffman_decode_slowpath(a, z); +} + +static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes +{ + char *q; + unsigned int cur, limit, old_limit; + z->zout = zout; + if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG"); + cur = (unsigned int) (z->zout - z->zout_start); + limit = old_limit = (unsigned) (z->zout_end - z->zout_start); + if (UINT_MAX - cur < (unsigned) n) return stbi__err("outofmem", "Out of memory"); + while (cur + n > limit) { + if(limit > UINT_MAX / 2) return stbi__err("outofmem", "Out of memory"); + limit *= 2; + } + q = (char *) STBI_REALLOC_SIZED(z->zout_start, old_limit, limit); + STBI_NOTUSED(old_limit); + if (q == NULL) return stbi__err("outofmem", "Out of memory"); + z->zout_start = q; + z->zout = q + cur; + z->zout_end = q + limit; + return 1; +} + +static const int stbi__zlength_base[31] = { + 3,4,5,6,7,8,9,10,11,13, + 15,17,19,23,27,31,35,43,51,59, + 67,83,99,115,131,163,195,227,258,0,0 }; + +static const int stbi__zlength_extra[31]= +{ 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 }; + +static const int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193, +257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0}; + +static const int stbi__zdist_extra[32] = +{ 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +static int stbi__parse_huffman_block(stbi__zbuf *a) +{ + char *zout = a->zout; + for(;;) { + int z = stbi__zhuffman_decode(a, &a->z_length); + if (z < 256) { + if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes + if (zout >= a->zout_end) { + if (!stbi__zexpand(a, zout, 1)) return 0; + zout = a->zout; + } + *zout++ = (char) z; + } else { + stbi_uc *p; + int len,dist; + if (z == 256) { + a->zout = zout; + if (a->hit_zeof_once && a->num_bits < 16) { + // The first time we hit zeof, we inserted 16 extra zero bits into our bit + // buffer so the decoder can just do its speculative decoding. But if we + // actually consumed any of those bits (which is the case when num_bits < 16), + // the stream actually read past the end so it is malformed. + return stbi__err("unexpected end","Corrupt PNG"); + } + return 1; + } + if (z >= 286) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, length codes 286 and 287 must not appear in compressed data + z -= 257; + len = stbi__zlength_base[z]; + if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]); + z = stbi__zhuffman_decode(a, &a->z_distance); + if (z < 0 || z >= 30) return stbi__err("bad huffman code","Corrupt PNG"); // per DEFLATE, distance codes 30 and 31 must not appear in compressed data + dist = stbi__zdist_base[z]; + if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]); + if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG"); + if (len > a->zout_end - zout) { + if (!stbi__zexpand(a, zout, len)) return 0; + zout = a->zout; + } + p = (stbi_uc *) (zout - dist); + if (dist == 1) { // run of one byte; common in images. + stbi_uc v = *p; + if (len) { do *zout++ = v; while (--len); } + } else { + if (len) { do *zout++ = *p++; while (--len); } + } + } + } +} + +static int stbi__compute_huffman_codes(stbi__zbuf *a) +{ + static const stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 }; + stbi__zhuffman z_codelength; + stbi_uc lencodes[286+32+137];//padding for maximum single op + stbi_uc codelength_sizes[19]; + int i,n; + + int hlit = stbi__zreceive(a,5) + 257; + int hdist = stbi__zreceive(a,5) + 1; + int hclen = stbi__zreceive(a,4) + 4; + int ntot = hlit + hdist; + + memset(codelength_sizes, 0, sizeof(codelength_sizes)); + for (i=0; i < hclen; ++i) { + int s = stbi__zreceive(a,3); + codelength_sizes[length_dezigzag[i]] = (stbi_uc) s; + } + if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0; + + n = 0; + while (n < ntot) { + int c = stbi__zhuffman_decode(a, &z_codelength); + if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG"); + if (c < 16) + lencodes[n++] = (stbi_uc) c; + else { + stbi_uc fill = 0; + if (c == 16) { + c = stbi__zreceive(a,2)+3; + if (n == 0) return stbi__err("bad codelengths", "Corrupt PNG"); + fill = lencodes[n-1]; + } else if (c == 17) { + c = stbi__zreceive(a,3)+3; + } else if (c == 18) { + c = stbi__zreceive(a,7)+11; + } else { + return stbi__err("bad codelengths", "Corrupt PNG"); + } + if (ntot - n < c) return stbi__err("bad codelengths", "Corrupt PNG"); + memset(lencodes+n, fill, c); + n += c; + } + } + if (n != ntot) return stbi__err("bad codelengths","Corrupt PNG"); + if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0; + return 1; +} + +static int stbi__parse_uncompressed_block(stbi__zbuf *a) +{ + stbi_uc header[4]; + int len,nlen,k; + if (a->num_bits & 7) + stbi__zreceive(a, a->num_bits & 7); // discard + // drain the bit-packed data into header + k = 0; + while (a->num_bits > 0) { + header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check + a->code_buffer >>= 8; + a->num_bits -= 8; + } + if (a->num_bits < 0) return stbi__err("zlib corrupt","Corrupt PNG"); + // now fill header the normal way + while (k < 4) + header[k++] = stbi__zget8(a); + len = header[1] * 256 + header[0]; + nlen = header[3] * 256 + header[2]; + if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG"); + if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG"); + if (a->zout + len > a->zout_end) + if (!stbi__zexpand(a, a->zout, len)) return 0; + memcpy(a->zout, a->zbuffer, len); + a->zbuffer += len; + a->zout += len; + return 1; +} + +static int stbi__parse_zlib_header(stbi__zbuf *a) +{ + int cmf = stbi__zget8(a); + int cm = cmf & 15; + /* int cinfo = cmf >> 4; */ + int flg = stbi__zget8(a); + if (stbi__zeof(a)) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec + if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png + if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png + // window = 1 << (8 + cinfo)... but who cares, we fully buffer output + return 1; +} + +static const stbi_uc stbi__zdefault_length[STBI__ZNSYMS] = +{ + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, + 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, + 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8 +}; +static const stbi_uc stbi__zdefault_distance[32] = +{ + 5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5 +}; +/* +Init algorithm: +{ + int i; // use <= to match clearly with spec + for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8; + for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9; + for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7; + for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8; + + for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5; +} +*/ + +static int stbi__parse_zlib(stbi__zbuf *a, int parse_header) +{ + int final, type; + if (parse_header) + if (!stbi__parse_zlib_header(a)) return 0; + a->num_bits = 0; + a->code_buffer = 0; + a->hit_zeof_once = 0; + do { + final = stbi__zreceive(a,1); + type = stbi__zreceive(a,2); + if (type == 0) { + if (!stbi__parse_uncompressed_block(a)) return 0; + } else if (type == 3) { + return 0; + } else { + if (type == 1) { + // use fixed code lengths + if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , STBI__ZNSYMS)) return 0; + if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0; + } else { + if (!stbi__compute_huffman_codes(a)) return 0; + } + if (!stbi__parse_huffman_block(a)) return 0; + } + } while (!final); + return 1; +} + +static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header) +{ + a->zout_start = obuf; + a->zout = obuf; + a->zout_end = obuf + olen; + a->z_expandable = exp; + + return stbi__parse_zlib(a, parse_header); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, 1)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen) +{ + return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen); +} + +STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(initial_size); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer + len; + if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 1)) + return (int) (a.zout - a.zout_start); + else + return -1; +} + +STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen) +{ + stbi__zbuf a; + char *p = (char *) stbi__malloc(16384); + if (p == NULL) return NULL; + a.zbuffer = (stbi_uc *) buffer; + a.zbuffer_end = (stbi_uc *) buffer+len; + if (stbi__do_zlib(&a, p, 16384, 1, 0)) { + if (outlen) *outlen = (int) (a.zout - a.zout_start); + return a.zout_start; + } else { + STBI_FREE(a.zout_start); + return NULL; + } +} + +STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen) +{ + stbi__zbuf a; + a.zbuffer = (stbi_uc *) ibuffer; + a.zbuffer_end = (stbi_uc *) ibuffer + ilen; + if (stbi__do_zlib(&a, obuffer, olen, 0, 0)) + return (int) (a.zout - a.zout_start); + else + return -1; +} +#endif + +// public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18 +// simple implementation +// - only 8-bit samples +// - no CRC checking +// - allocates lots of intermediate memory +// - avoids problem of streaming data between subsystems +// - avoids explicit window management +// performance +// - uses stb_zlib, a PD zlib implementation with fast huffman decoding + +#ifndef STBI_NO_PNG +typedef struct +{ + stbi__uint32 length; + stbi__uint32 type; +} stbi__pngchunk; + +static stbi__pngchunk stbi__get_chunk_header(stbi__context *s) +{ + stbi__pngchunk c; + c.length = stbi__get32be(s); + c.type = stbi__get32be(s); + return c; +} + +static int stbi__check_png_header(stbi__context *s) +{ + static const stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 }; + int i; + for (i=0; i < 8; ++i) + if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG"); + return 1; +} + +typedef struct +{ + stbi__context *s; + stbi_uc *idata, *expanded, *out; + int depth; +} stbi__png; + + +enum { + STBI__F_none=0, + STBI__F_sub=1, + STBI__F_up=2, + STBI__F_avg=3, + STBI__F_paeth=4, + // synthetic filter used for first scanline to avoid needing a dummy row of 0s + STBI__F_avg_first +}; + +static stbi_uc first_row_filter[5] = +{ + STBI__F_none, + STBI__F_sub, + STBI__F_none, + STBI__F_avg_first, + STBI__F_sub // Paeth with b=c=0 turns out to be equivalent to sub +}; + +static int stbi__paeth(int a, int b, int c) +{ + // This formulation looks very different from the reference in the PNG spec, but is + // actually equivalent and has favorable data dependencies and admits straightforward + // generation of branch-free code, which helps performance significantly. + int thresh = c*3 - (a + b); + int lo = a < b ? a : b; + int hi = a < b ? b : a; + int t0 = (hi <= thresh) ? lo : c; + int t1 = (thresh <= lo) ? hi : t0; + return t1; +} + +static const stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 }; + +// adds an extra all-255 alpha channel +// dest == src is legal +// img_n must be 1 or 3 +static void stbi__create_png_alpha_expand8(stbi_uc *dest, stbi_uc *src, stbi__uint32 x, int img_n) +{ + int i; + // must process data backwards since we allow dest==src + if (img_n == 1) { + for (i=x-1; i >= 0; --i) { + dest[i*2+1] = 255; + dest[i*2+0] = src[i]; + } + } else { + STBI_ASSERT(img_n == 3); + for (i=x-1; i >= 0; --i) { + dest[i*4+3] = 255; + dest[i*4+2] = src[i*3+2]; + dest[i*4+1] = src[i*3+1]; + dest[i*4+0] = src[i*3+0]; + } + } +} + +// create the png data from post-deflated data +static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color) +{ + int bytes = (depth == 16 ? 2 : 1); + stbi__context *s = a->s; + stbi__uint32 i,j,stride = x*out_n*bytes; + stbi__uint32 img_len, img_width_bytes; + stbi_uc *filter_buf; + int all_ok = 1; + int k; + int img_n = s->img_n; // copy it into a local for later + + int output_bytes = out_n*bytes; + int filter_bytes = img_n*bytes; + int width = x; + + STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1); + a->out = (stbi_uc *) stbi__malloc_mad3(x, y, output_bytes, 0); // extra bytes to write off the end into + if (!a->out) return stbi__err("outofmem", "Out of memory"); + + // note: error exits here don't need to clean up a->out individually, + // stbi__do_png always does on error. + if (!stbi__mad3sizes_valid(img_n, x, depth, 7)) return stbi__err("too large", "Corrupt PNG"); + img_width_bytes = (((img_n * x * depth) + 7) >> 3); + if (!stbi__mad2sizes_valid(img_width_bytes, y, img_width_bytes)) return stbi__err("too large", "Corrupt PNG"); + img_len = (img_width_bytes + 1) * y; + + // we used to check for exact match between raw_len and img_len on non-interlaced PNGs, + // but issue #276 reported a PNG in the wild that had extra data at the end (all zeros), + // so just check for raw_len < img_len always. + if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG"); + + // Allocate two scan lines worth of filter workspace buffer. + filter_buf = (stbi_uc *) stbi__malloc_mad2(img_width_bytes, 2, 0); + if (!filter_buf) return stbi__err("outofmem", "Out of memory"); + + // Filtering for low-bit-depth images + if (depth < 8) { + filter_bytes = 1; + width = img_width_bytes; + } + + for (j=0; j < y; ++j) { + // cur/prior filter buffers alternate + stbi_uc *cur = filter_buf + (j & 1)*img_width_bytes; + stbi_uc *prior = filter_buf + (~j & 1)*img_width_bytes; + stbi_uc *dest = a->out + stride*j; + int nk = width * filter_bytes; + int filter = *raw++; + + // check filter type + if (filter > 4) { + all_ok = stbi__err("invalid filter","Corrupt PNG"); + break; + } + + // if first row, use special filter that doesn't sample previous row + if (j == 0) filter = first_row_filter[filter]; + + // perform actual filtering + switch (filter) { + case STBI__F_none: + memcpy(cur, raw, nk); + break; + case STBI__F_sub: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); + break; + case STBI__F_up: + for (k = 0; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); + break; + case STBI__F_avg: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); + break; + case STBI__F_paeth: + for (k = 0; k < filter_bytes; ++k) + cur[k] = STBI__BYTECAST(raw[k] + prior[k]); // prior[k] == stbi__paeth(0,prior[k],0) + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes], prior[k], prior[k-filter_bytes])); + break; + case STBI__F_avg_first: + memcpy(cur, raw, filter_bytes); + for (k = filter_bytes; k < nk; ++k) + cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); + break; + } + + raw += nk; + + // expand decoded bits in cur to dest, also adding an extra alpha channel if desired + if (depth < 8) { + stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range + stbi_uc *in = cur; + stbi_uc *out = dest; + stbi_uc inb = 0; + stbi__uint32 nsmp = x*img_n; + + // expand bits to bytes first + if (depth == 4) { + for (i=0; i < nsmp; ++i) { + if ((i & 1) == 0) inb = *in++; + *out++ = scale * (inb >> 4); + inb <<= 4; + } + } else if (depth == 2) { + for (i=0; i < nsmp; ++i) { + if ((i & 3) == 0) inb = *in++; + *out++ = scale * (inb >> 6); + inb <<= 2; + } + } else { + STBI_ASSERT(depth == 1); + for (i=0; i < nsmp; ++i) { + if ((i & 7) == 0) inb = *in++; + *out++ = scale * (inb >> 7); + inb <<= 1; + } + } + + // insert alpha=255 values if desired + if (img_n != out_n) + stbi__create_png_alpha_expand8(dest, dest, x, img_n); + } else if (depth == 8) { + if (img_n == out_n) + memcpy(dest, cur, x*img_n); + else + stbi__create_png_alpha_expand8(dest, cur, x, img_n); + } else if (depth == 16) { + // convert the image data from big-endian to platform-native + stbi__uint16 *dest16 = (stbi__uint16*)dest; + stbi__uint32 nsmp = x*img_n; + + if (img_n == out_n) { + for (i = 0; i < nsmp; ++i, ++dest16, cur += 2) + *dest16 = (cur[0] << 8) | cur[1]; + } else { + STBI_ASSERT(img_n+1 == out_n); + if (img_n == 1) { + for (i = 0; i < x; ++i, dest16 += 2, cur += 2) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = 0xffff; + } + } else { + STBI_ASSERT(img_n == 3); + for (i = 0; i < x; ++i, dest16 += 4, cur += 6) { + dest16[0] = (cur[0] << 8) | cur[1]; + dest16[1] = (cur[2] << 8) | cur[3]; + dest16[2] = (cur[4] << 8) | cur[5]; + dest16[3] = 0xffff; + } + } + } + } + } + + STBI_FREE(filter_buf); + if (!all_ok) return 0; + + return 1; +} + +static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced) +{ + int bytes = (depth == 16 ? 2 : 1); + int out_bytes = out_n * bytes; + stbi_uc *final; + int p; + if (!interlaced) + return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color); + + // de-interlacing + final = (stbi_uc *) stbi__malloc_mad3(a->s->img_x, a->s->img_y, out_bytes, 0); + if (!final) return stbi__err("outofmem", "Out of memory"); + for (p=0; p < 7; ++p) { + int xorig[] = { 0,4,0,2,0,1,0 }; + int yorig[] = { 0,0,4,0,2,0,1 }; + int xspc[] = { 8,8,4,4,2,2,1 }; + int yspc[] = { 8,8,8,4,4,2,2 }; + int i,j,x,y; + // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1 + x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p]; + y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p]; + if (x && y) { + stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y; + if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) { + STBI_FREE(final); + return 0; + } + for (j=0; j < y; ++j) { + for (i=0; i < x; ++i) { + int out_y = j*yspc[p]+yorig[p]; + int out_x = i*xspc[p]+xorig[p]; + memcpy(final + out_y*a->s->img_x*out_bytes + out_x*out_bytes, + a->out + (j*x+i)*out_bytes, out_bytes); + } + } + STBI_FREE(a->out); + image_data += img_len; + image_data_len -= img_len; + } + } + a->out = final; + + return 1; +} + +static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + // compute color-based transparency, assuming we've + // already got 255 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i=0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 255); + p += 2; + } + } else { + for (i=0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__compute_transparency16(stbi__png *z, stbi__uint16 tc[3], int out_n) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi__uint16 *p = (stbi__uint16*) z->out; + + // compute color-based transparency, assuming we've + // already got 65535 as the alpha value in the output + STBI_ASSERT(out_n == 2 || out_n == 4); + + if (out_n == 2) { + for (i = 0; i < pixel_count; ++i) { + p[1] = (p[0] == tc[0] ? 0 : 65535); + p += 2; + } + } else { + for (i = 0; i < pixel_count; ++i) { + if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2]) + p[3] = 0; + p += 4; + } + } + return 1; +} + +static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n) +{ + stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y; + stbi_uc *p, *temp_out, *orig = a->out; + + p = (stbi_uc *) stbi__malloc_mad2(pixel_count, pal_img_n, 0); + if (p == NULL) return stbi__err("outofmem", "Out of memory"); + + // between here and free(out) below, exitting would leak + temp_out = p; + + if (pal_img_n == 3) { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p += 3; + } + } else { + for (i=0; i < pixel_count; ++i) { + int n = orig[i]*4; + p[0] = palette[n ]; + p[1] = palette[n+1]; + p[2] = palette[n+2]; + p[3] = palette[n+3]; + p += 4; + } + } + STBI_FREE(a->out); + a->out = temp_out; + + STBI_NOTUSED(len); + + return 1; +} + +static int stbi__unpremultiply_on_load_global = 0; +static int stbi__de_iphone_flag_global = 0; + +STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_global = flag_true_if_should_unpremultiply; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_global = flag_true_if_should_convert; +} + +#ifndef STBI_THREAD_LOCAL +#define stbi__unpremultiply_on_load stbi__unpremultiply_on_load_global +#define stbi__de_iphone_flag stbi__de_iphone_flag_global +#else +static STBI_THREAD_LOCAL int stbi__unpremultiply_on_load_local, stbi__unpremultiply_on_load_set; +static STBI_THREAD_LOCAL int stbi__de_iphone_flag_local, stbi__de_iphone_flag_set; + +STBIDEF void stbi_set_unpremultiply_on_load_thread(int flag_true_if_should_unpremultiply) +{ + stbi__unpremultiply_on_load_local = flag_true_if_should_unpremultiply; + stbi__unpremultiply_on_load_set = 1; +} + +STBIDEF void stbi_convert_iphone_png_to_rgb_thread(int flag_true_if_should_convert) +{ + stbi__de_iphone_flag_local = flag_true_if_should_convert; + stbi__de_iphone_flag_set = 1; +} + +#define stbi__unpremultiply_on_load (stbi__unpremultiply_on_load_set \ + ? stbi__unpremultiply_on_load_local \ + : stbi__unpremultiply_on_load_global) +#define stbi__de_iphone_flag (stbi__de_iphone_flag_set \ + ? stbi__de_iphone_flag_local \ + : stbi__de_iphone_flag_global) +#endif // STBI_THREAD_LOCAL + +static void stbi__de_iphone(stbi__png *z) +{ + stbi__context *s = z->s; + stbi__uint32 i, pixel_count = s->img_x * s->img_y; + stbi_uc *p = z->out; + + if (s->img_out_n == 3) { // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 3; + } + } else { + STBI_ASSERT(s->img_out_n == 4); + if (stbi__unpremultiply_on_load) { + // convert bgr to rgb and unpremultiply + for (i=0; i < pixel_count; ++i) { + stbi_uc a = p[3]; + stbi_uc t = p[0]; + if (a) { + stbi_uc half = a / 2; + p[0] = (p[2] * 255 + half) / a; + p[1] = (p[1] * 255 + half) / a; + p[2] = ( t * 255 + half) / a; + } else { + p[0] = p[2]; + p[2] = t; + } + p += 4; + } + } else { + // convert bgr to rgb + for (i=0; i < pixel_count; ++i) { + stbi_uc t = p[0]; + p[0] = p[2]; + p[2] = t; + p += 4; + } + } + } +} + +#define STBI__PNG_TYPE(a,b,c,d) (((unsigned) (a) << 24) + ((unsigned) (b) << 16) + ((unsigned) (c) << 8) + (unsigned) (d)) + +static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp) +{ + stbi_uc palette[1024], pal_img_n=0; + stbi_uc has_trans=0, tc[3]={0}; + stbi__uint16 tc16[3]; + stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0; + int first=1,k,interlace=0, color=0, is_iphone=0; + stbi__context *s = z->s; + + z->expanded = NULL; + z->idata = NULL; + z->out = NULL; + + if (!stbi__check_png_header(s)) return 0; + + if (scan == STBI__SCAN_type) return 1; + + for (;;) { + stbi__pngchunk c = stbi__get_chunk_header(s); + switch (c.type) { + case STBI__PNG_TYPE('C','g','B','I'): + is_iphone = 1; + stbi__skip(s, c.length); + break; + case STBI__PNG_TYPE('I','H','D','R'): { + int comp,filter; + if (!first) return stbi__err("multiple IHDR","Corrupt PNG"); + first = 0; + if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG"); + s->img_x = stbi__get32be(s); + s->img_y = stbi__get32be(s); + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + z->depth = stbi__get8(s); if (z->depth != 1 && z->depth != 2 && z->depth != 4 && z->depth != 8 && z->depth != 16) return stbi__err("1/2/4/8/16-bit only","PNG not supported: 1/2/4/8/16-bit only"); + color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3 && z->depth == 16) return stbi__err("bad ctype","Corrupt PNG"); + if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG"); + comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG"); + filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG"); + interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG"); + if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG"); + if (!pal_img_n) { + s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0); + if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode"); + } else { + // if paletted, then pal_n is our final components, and + // img_n is # components to decompress/filter. + s->img_n = 1; + if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG"); + } + // even with SCAN_header, have to scan to see if we have a tRNS + break; + } + + case STBI__PNG_TYPE('P','L','T','E'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG"); + pal_len = c.length / 3; + if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG"); + for (i=0; i < pal_len; ++i) { + palette[i*4+0] = stbi__get8(s); + palette[i*4+1] = stbi__get8(s); + palette[i*4+2] = stbi__get8(s); + palette[i*4+3] = 255; + } + break; + } + + case STBI__PNG_TYPE('t','R','N','S'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG"); + if (pal_img_n) { + if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; } + if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG"); + if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG"); + pal_img_n = 4; + for (i=0; i < c.length; ++i) + palette[i*4+3] = stbi__get8(s); + } else { + if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG"); + if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG"); + has_trans = 1; + // non-paletted with tRNS = constant alpha. if header-scanning, we can stop now. + if (scan == STBI__SCAN_header) { ++s->img_n; return 1; } + if (z->depth == 16) { + for (k = 0; k < s->img_n; ++k) tc16[k] = (stbi__uint16)stbi__get16be(s); // copy the values as-is + } else { + for (k = 0; k < s->img_n; ++k) tc[k] = (stbi_uc)(stbi__get16be(s) & 255) * stbi__depth_scale_table[z->depth]; // non 8-bit images will be larger + } + } + break; + } + + case STBI__PNG_TYPE('I','D','A','T'): { + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG"); + if (scan == STBI__SCAN_header) { + // header scan definitely stops at first IDAT + if (pal_img_n) + s->img_n = pal_img_n; + return 1; + } + if (c.length > (1u << 30)) return stbi__err("IDAT size limit", "IDAT section larger than 2^30 bytes"); + if ((int)(ioff + c.length) < (int)ioff) return 0; + if (ioff + c.length > idata_limit) { + stbi__uint32 idata_limit_old = idata_limit; + stbi_uc *p; + if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096; + while (ioff + c.length > idata_limit) + idata_limit *= 2; + STBI_NOTUSED(idata_limit_old); + p = (stbi_uc *) STBI_REALLOC_SIZED(z->idata, idata_limit_old, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory"); + z->idata = p; + } + if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG"); + ioff += c.length; + break; + } + + case STBI__PNG_TYPE('I','E','N','D'): { + stbi__uint32 raw_len, bpl; + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if (scan != STBI__SCAN_load) return 1; + if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG"); + // initial guess for decoded data size to avoid unnecessary reallocs + bpl = (s->img_x * z->depth + 7) / 8; // bytes per line, per component + raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */; + z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone); + if (z->expanded == NULL) return 0; // zlib should set error + STBI_FREE(z->idata); z->idata = NULL; + if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans) + s->img_out_n = s->img_n+1; + else + s->img_out_n = s->img_n; + if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, z->depth, color, interlace)) return 0; + if (has_trans) { + if (z->depth == 16) { + if (!stbi__compute_transparency16(z, tc16, s->img_out_n)) return 0; + } else { + if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0; + } + } + if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2) + stbi__de_iphone(z); + if (pal_img_n) { + // pal_img_n == 3 or 4 + s->img_n = pal_img_n; // record the actual colors we had + s->img_out_n = pal_img_n; + if (req_comp >= 3) s->img_out_n = req_comp; + if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n)) + return 0; + } else if (has_trans) { + // non-paletted image with tRNS -> source image has (constant) alpha + ++s->img_n; + } + STBI_FREE(z->expanded); z->expanded = NULL; + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + return 1; + } + + default: + // if critical, fail + if (first) return stbi__err("first not IHDR", "Corrupt PNG"); + if ((c.type & (1 << 29)) == 0) { + #ifndef STBI_NO_FAILURE_STRINGS + // not threadsafe + static char invalid_chunk[] = "XXXX PNG chunk not known"; + invalid_chunk[0] = STBI__BYTECAST(c.type >> 24); + invalid_chunk[1] = STBI__BYTECAST(c.type >> 16); + invalid_chunk[2] = STBI__BYTECAST(c.type >> 8); + invalid_chunk[3] = STBI__BYTECAST(c.type >> 0); + #endif + return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type"); + } + stbi__skip(s, c.length); + break; + } + // end of PNG chunk, read and skip CRC + stbi__get32be(s); + } +} + +static void *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp, stbi__result_info *ri) +{ + void *result=NULL; + if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error"); + if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) { + if (p->depth <= 8) + ri->bits_per_channel = 8; + else if (p->depth == 16) + ri->bits_per_channel = 16; + else + return stbi__errpuc("bad bits_per_channel", "PNG not supported: unsupported color depth"); + result = p->out; + p->out = NULL; + if (req_comp && req_comp != p->s->img_out_n) { + if (ri->bits_per_channel == 8) + result = stbi__convert_format((unsigned char *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + else + result = stbi__convert_format16((stbi__uint16 *) result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y); + p->s->img_out_n = req_comp; + if (result == NULL) return result; + } + *x = p->s->img_x; + *y = p->s->img_y; + if (n) *n = p->s->img_n; + } + STBI_FREE(p->out); p->out = NULL; + STBI_FREE(p->expanded); p->expanded = NULL; + STBI_FREE(p->idata); p->idata = NULL; + + return result; +} + +static void *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi__png p; + p.s = s; + return stbi__do_png(&p, x,y,comp,req_comp, ri); +} + +static int stbi__png_test(stbi__context *s) +{ + int r; + r = stbi__check_png_header(s); + stbi__rewind(s); + return r; +} + +static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp) +{ + if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) { + stbi__rewind( p->s ); + return 0; + } + if (x) *x = p->s->img_x; + if (y) *y = p->s->img_y; + if (comp) *comp = p->s->img_n; + return 1; +} + +static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__png p; + p.s = s; + return stbi__png_info_raw(&p, x, y, comp); +} + +static int stbi__png_is16(stbi__context *s) +{ + stbi__png p; + p.s = s; + if (!stbi__png_info_raw(&p, NULL, NULL, NULL)) + return 0; + if (p.depth != 16) { + stbi__rewind(p.s); + return 0; + } + return 1; +} +#endif + +// Microsoft/Windows BMP image + +#ifndef STBI_NO_BMP +static int stbi__bmp_test_raw(stbi__context *s) +{ + int r; + int sz; + if (stbi__get8(s) != 'B') return 0; + if (stbi__get8(s) != 'M') return 0; + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + stbi__get32le(s); // discard data offset + sz = stbi__get32le(s); + r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124); + return r; +} + +static int stbi__bmp_test(stbi__context *s) +{ + int r = stbi__bmp_test_raw(s); + stbi__rewind(s); + return r; +} + + +// returns 0..31 for the highest set bit +static int stbi__high_bit(unsigned int z) +{ + int n=0; + if (z == 0) return -1; + if (z >= 0x10000) { n += 16; z >>= 16; } + if (z >= 0x00100) { n += 8; z >>= 8; } + if (z >= 0x00010) { n += 4; z >>= 4; } + if (z >= 0x00004) { n += 2; z >>= 2; } + if (z >= 0x00002) { n += 1;/* >>= 1;*/ } + return n; +} + +static int stbi__bitcount(unsigned int a) +{ + a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 + a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 + a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits + a = (a + (a >> 8)); // max 16 per 8 bits + a = (a + (a >> 16)); // max 32 per 8 bits + return a & 0xff; +} + +// extract an arbitrarily-aligned N-bit value (N=bits) +// from v, and then make it 8-bits long and fractionally +// extend it to full full range. +static int stbi__shiftsigned(unsigned int v, int shift, int bits) +{ + static unsigned int mul_table[9] = { + 0, + 0xff/*0b11111111*/, 0x55/*0b01010101*/, 0x49/*0b01001001*/, 0x11/*0b00010001*/, + 0x21/*0b00100001*/, 0x41/*0b01000001*/, 0x81/*0b10000001*/, 0x01/*0b00000001*/, + }; + static unsigned int shift_table[9] = { + 0, 0,0,1,0,2,4,6,0, + }; + if (shift < 0) + v <<= -shift; + else + v >>= shift; + STBI_ASSERT(v < 256); + v >>= (8-bits); + STBI_ASSERT(bits >= 0 && bits <= 8); + return (int) ((unsigned) v * mul_table[bits]) >> shift_table[bits]; +} + +typedef struct +{ + int bpp, offset, hsz; + unsigned int mr,mg,mb,ma, all_a; + int extra_read; +} stbi__bmp_data; + +static int stbi__bmp_set_mask_defaults(stbi__bmp_data *info, int compress) +{ + // BI_BITFIELDS specifies masks explicitly, don't override + if (compress == 3) + return 1; + + if (compress == 0) { + if (info->bpp == 16) { + info->mr = 31u << 10; + info->mg = 31u << 5; + info->mb = 31u << 0; + } else if (info->bpp == 32) { + info->mr = 0xffu << 16; + info->mg = 0xffu << 8; + info->mb = 0xffu << 0; + info->ma = 0xffu << 24; + info->all_a = 0; // if all_a is 0 at end, then we loaded alpha channel but it was all 0 + } else { + // otherwise, use defaults, which is all-0 + info->mr = info->mg = info->mb = info->ma = 0; + } + return 1; + } + return 0; // error +} + +static void *stbi__bmp_parse_header(stbi__context *s, stbi__bmp_data *info) +{ + int hsz; + if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP"); + stbi__get32le(s); // discard filesize + stbi__get16le(s); // discard reserved + stbi__get16le(s); // discard reserved + info->offset = stbi__get32le(s); + info->hsz = hsz = stbi__get32le(s); + info->mr = info->mg = info->mb = info->ma = 0; + info->extra_read = 14; + + if (info->offset < 0) return stbi__errpuc("bad BMP", "bad BMP"); + + if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown"); + if (hsz == 12) { + s->img_x = stbi__get16le(s); + s->img_y = stbi__get16le(s); + } else { + s->img_x = stbi__get32le(s); + s->img_y = stbi__get32le(s); + } + if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP"); + info->bpp = stbi__get16le(s); + if (hsz != 12) { + int compress = stbi__get32le(s); + if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE"); + if (compress >= 4) return stbi__errpuc("BMP JPEG/PNG", "BMP type not supported: unsupported compression"); // this includes PNG/JPEG modes + if (compress == 3 && info->bpp != 16 && info->bpp != 32) return stbi__errpuc("bad BMP", "bad BMP"); // bitfields requires 16 or 32 bits/pixel + stbi__get32le(s); // discard sizeof + stbi__get32le(s); // discard hres + stbi__get32le(s); // discard vres + stbi__get32le(s); // discard colorsused + stbi__get32le(s); // discard max important + if (hsz == 40 || hsz == 56) { + if (hsz == 56) { + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + stbi__get32le(s); + } + if (info->bpp == 16 || info->bpp == 32) { + if (compress == 0) { + stbi__bmp_set_mask_defaults(info, compress); + } else if (compress == 3) { + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->extra_read += 12; + // not documented, but generated by photoshop and handled by mspaint + if (info->mr == info->mg && info->mg == info->mb) { + // ?!?!? + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else + return stbi__errpuc("bad BMP", "bad BMP"); + } + } else { + // V4/V5 header + int i; + if (hsz != 108 && hsz != 124) + return stbi__errpuc("bad BMP", "bad BMP"); + info->mr = stbi__get32le(s); + info->mg = stbi__get32le(s); + info->mb = stbi__get32le(s); + info->ma = stbi__get32le(s); + if (compress != 3) // override mr/mg/mb unless in BI_BITFIELDS mode, as per docs + stbi__bmp_set_mask_defaults(info, compress); + stbi__get32le(s); // discard color space + for (i=0; i < 12; ++i) + stbi__get32le(s); // discard color space parameters + if (hsz == 124) { + stbi__get32le(s); // discard rendering intent + stbi__get32le(s); // discard offset of profile data + stbi__get32le(s); // discard size of profile data + stbi__get32le(s); // discard reserved + } + } + } + return (void *) 1; +} + + +static void *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + unsigned int mr=0,mg=0,mb=0,ma=0, all_a; + stbi_uc pal[256][4]; + int psize=0,i,j,width; + int flip_vertically, pad, target; + stbi__bmp_data info; + STBI_NOTUSED(ri); + + info.all_a = 255; + if (stbi__bmp_parse_header(s, &info) == NULL) + return NULL; // error code already set + + flip_vertically = ((int) s->img_y) > 0; + s->img_y = abs((int) s->img_y); + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + mr = info.mr; + mg = info.mg; + mb = info.mb; + ma = info.ma; + all_a = info.all_a; + + if (info.hsz == 12) { + if (info.bpp < 24) + psize = (info.offset - info.extra_read - 24) / 3; + } else { + if (info.bpp < 16) + psize = (info.offset - info.extra_read - info.hsz) >> 2; + } + if (psize == 0) { + // accept some number of extra bytes after the header, but if the offset points either to before + // the header ends or implies a large amount of extra data, reject the file as malformed + int bytes_read_so_far = s->callback_already_read + (int)(s->img_buffer - s->img_buffer_original); + int header_limit = 1024; // max we actually read is below 256 bytes currently. + int extra_data_limit = 256*4; // what ordinarily goes here is a palette; 256 entries*4 bytes is its max size. + if (bytes_read_so_far <= 0 || bytes_read_so_far > header_limit) { + return stbi__errpuc("bad header", "Corrupt BMP"); + } + // we established that bytes_read_so_far is positive and sensible. + // the first half of this test rejects offsets that are either too small positives, or + // negative, and guarantees that info.offset >= bytes_read_so_far > 0. this in turn + // ensures the number computed in the second half of the test can't overflow. + if (info.offset < bytes_read_so_far || info.offset - bytes_read_so_far > extra_data_limit) { + return stbi__errpuc("bad offset", "Corrupt BMP"); + } else { + stbi__skip(s, info.offset - bytes_read_so_far); + } + } + + if (info.bpp == 24 && ma == 0xff000000) + s->img_n = 3; + else + s->img_n = ma ? 4 : 3; + if (req_comp && req_comp >= 3) // we can directly decode 3 or 4 + target = req_comp; + else + target = s->img_n; // if they want monochrome, we'll post-convert + + // sanity-check size + if (!stbi__mad3sizes_valid(target, s->img_x, s->img_y, 0)) + return stbi__errpuc("too large", "Corrupt BMP"); + + out = (stbi_uc *) stbi__malloc_mad3(target, s->img_x, s->img_y, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (info.bpp < 16) { + int z=0; + if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); } + for (i=0; i < psize; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + if (info.hsz != 12) stbi__get8(s); + pal[i][3] = 255; + } + stbi__skip(s, info.offset - info.extra_read - info.hsz - psize * (info.hsz == 12 ? 3 : 4)); + if (info.bpp == 1) width = (s->img_x + 7) >> 3; + else if (info.bpp == 4) width = (s->img_x + 1) >> 1; + else if (info.bpp == 8) width = s->img_x; + else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); } + pad = (-width)&3; + if (info.bpp == 1) { + for (j=0; j < (int) s->img_y; ++j) { + int bit_offset = 7, v = stbi__get8(s); + for (i=0; i < (int) s->img_x; ++i) { + int color = (v>>bit_offset)&0x1; + out[z++] = pal[color][0]; + out[z++] = pal[color][1]; + out[z++] = pal[color][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + if((--bit_offset) < 0) { + bit_offset = 7; + v = stbi__get8(s); + } + } + stbi__skip(s, pad); + } + } else { + for (j=0; j < (int) s->img_y; ++j) { + for (i=0; i < (int) s->img_x; i += 2) { + int v=stbi__get8(s),v2=0; + if (info.bpp == 4) { + v2 = v & 15; + v >>= 4; + } + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + if (i+1 == (int) s->img_x) break; + v = (info.bpp == 8) ? stbi__get8(s) : v2; + out[z++] = pal[v][0]; + out[z++] = pal[v][1]; + out[z++] = pal[v][2]; + if (target == 4) out[z++] = 255; + } + stbi__skip(s, pad); + } + } + } else { + int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0; + int z = 0; + int easy=0; + stbi__skip(s, info.offset - info.extra_read - info.hsz); + if (info.bpp == 24) width = 3 * s->img_x; + else if (info.bpp == 16) width = 2*s->img_x; + else /* bpp = 32 and pad = 0 */ width=0; + pad = (-width) & 3; + if (info.bpp == 24) { + easy = 1; + } else if (info.bpp == 32) { + if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000) + easy = 2; + } + if (!easy) { + if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + // right shift amt to put high bit in position #7 + rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr); + gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg); + bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb); + ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma); + if (rcount > 8 || gcount > 8 || bcount > 8 || acount > 8) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); } + } + for (j=0; j < (int) s->img_y; ++j) { + if (easy) { + for (i=0; i < (int) s->img_x; ++i) { + unsigned char a; + out[z+2] = stbi__get8(s); + out[z+1] = stbi__get8(s); + out[z+0] = stbi__get8(s); + z += 3; + a = (easy == 2 ? stbi__get8(s) : 255); + all_a |= a; + if (target == 4) out[z++] = a; + } + } else { + int bpp = info.bpp; + for (i=0; i < (int) s->img_x; ++i) { + stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s)); + unsigned int a; + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount)); + out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount)); + a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255); + all_a |= a; + if (target == 4) out[z++] = STBI__BYTECAST(a); + } + } + stbi__skip(s, pad); + } + } + + // if alpha channel is all 0s, replace with all 255s + if (target == 4 && all_a == 0) + for (i=4*s->img_x*s->img_y-1; i >= 0; i -= 4) + out[i] = 255; + + if (flip_vertically) { + stbi_uc t; + for (j=0; j < (int) s->img_y>>1; ++j) { + stbi_uc *p1 = out + j *s->img_x*target; + stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target; + for (i=0; i < (int) s->img_x*target; ++i) { + t = p1[i]; p1[i] = p2[i]; p2[i] = t; + } + } + } + + if (req_comp && req_comp != target) { + out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + return out; +} +#endif + +// Targa Truevision - TGA +// by Jonathan Dummer +#ifndef STBI_NO_TGA +// returns STBI_rgb or whatever, 0 on error +static int stbi__tga_get_comp(int bits_per_pixel, int is_grey, int* is_rgb16) +{ + // only RGB or RGBA (incl. 16bit) or grey allowed + if (is_rgb16) *is_rgb16 = 0; + switch(bits_per_pixel) { + case 8: return STBI_grey; + case 16: if(is_grey) return STBI_grey_alpha; + // fallthrough + case 15: if(is_rgb16) *is_rgb16 = 1; + return STBI_rgb; + case 24: // fallthrough + case 32: return bits_per_pixel/8; + default: return 0; + } +} + +static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp) +{ + int tga_w, tga_h, tga_comp, tga_image_type, tga_bits_per_pixel, tga_colormap_bpp; + int sz, tga_colormap_type; + stbi__get8(s); // discard Offset + tga_colormap_type = stbi__get8(s); // colormap type + if( tga_colormap_type > 1 ) { + stbi__rewind(s); + return 0; // only RGB or indexed allowed + } + tga_image_type = stbi__get8(s); // image type + if ( tga_colormap_type == 1 ) { // colormapped (paletted) image + if (tga_image_type != 1 && tga_image_type != 9) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) { + stbi__rewind(s); + return 0; + } + stbi__skip(s,4); // skip image x and y origin + tga_colormap_bpp = sz; + } else { // "normal" image w/o colormap - only RGB or grey allowed, +/- RLE + if ( (tga_image_type != 2) && (tga_image_type != 3) && (tga_image_type != 10) && (tga_image_type != 11) ) { + stbi__rewind(s); + return 0; // only RGB or grey allowed, +/- RLE + } + stbi__skip(s,9); // skip colormap specification and image x/y origin + tga_colormap_bpp = 0; + } + tga_w = stbi__get16le(s); + if( tga_w < 1 ) { + stbi__rewind(s); + return 0; // test width + } + tga_h = stbi__get16le(s); + if( tga_h < 1 ) { + stbi__rewind(s); + return 0; // test height + } + tga_bits_per_pixel = stbi__get8(s); // bits per pixel + stbi__get8(s); // ignore alpha bits + if (tga_colormap_bpp != 0) { + if((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16)) { + // when using a colormap, tga_bits_per_pixel is the size of the indexes + // I don't think anything but 8 or 16bit indexes makes sense + stbi__rewind(s); + return 0; + } + tga_comp = stbi__tga_get_comp(tga_colormap_bpp, 0, NULL); + } else { + tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3) || (tga_image_type == 11), NULL); + } + if(!tga_comp) { + stbi__rewind(s); + return 0; + } + if (x) *x = tga_w; + if (y) *y = tga_h; + if (comp) *comp = tga_comp; + return 1; // seems to have passed everything +} + +static int stbi__tga_test(stbi__context *s) +{ + int res = 0; + int sz, tga_color_type; + stbi__get8(s); // discard Offset + tga_color_type = stbi__get8(s); // color type + if ( tga_color_type > 1 ) goto errorEnd; // only RGB or indexed allowed + sz = stbi__get8(s); // image type + if ( tga_color_type == 1 ) { // colormapped (paletted) image + if (sz != 1 && sz != 9) goto errorEnd; // colortype 1 demands image type 1 or 9 + stbi__skip(s,4); // skip index of first colormap entry and number of entries + sz = stbi__get8(s); // check bits per palette color entry + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + stbi__skip(s,4); // skip image x and y origin + } else { // "normal" image w/o colormap + if ( (sz != 2) && (sz != 3) && (sz != 10) && (sz != 11) ) goto errorEnd; // only RGB or grey allowed, +/- RLE + stbi__skip(s,9); // skip colormap specification and image x/y origin + } + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test width + if ( stbi__get16le(s) < 1 ) goto errorEnd; // test height + sz = stbi__get8(s); // bits per pixel + if ( (tga_color_type == 1) && (sz != 8) && (sz != 16) ) goto errorEnd; // for colormapped images, bpp is size of an index + if ( (sz != 8) && (sz != 15) && (sz != 16) && (sz != 24) && (sz != 32) ) goto errorEnd; + + res = 1; // if we got this far, everything's good and we can return 1 instead of 0 + +errorEnd: + stbi__rewind(s); + return res; +} + +// read 16bit value and convert to 24bit RGB +static void stbi__tga_read_rgb16(stbi__context *s, stbi_uc* out) +{ + stbi__uint16 px = (stbi__uint16)stbi__get16le(s); + stbi__uint16 fiveBitMask = 31; + // we have 3 channels with 5bits each + int r = (px >> 10) & fiveBitMask; + int g = (px >> 5) & fiveBitMask; + int b = px & fiveBitMask; + // Note that this saves the data in RGB(A) order, so it doesn't need to be swapped later + out[0] = (stbi_uc)((r * 255)/31); + out[1] = (stbi_uc)((g * 255)/31); + out[2] = (stbi_uc)((b * 255)/31); + + // some people claim that the most significant bit might be used for alpha + // (possibly if an alpha-bit is set in the "image descriptor byte") + // but that only made 16bit test images completely translucent.. + // so let's treat all 15 and 16bit TGAs as RGB with no alpha. +} + +static void *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + // read in the TGA header stuff + int tga_offset = stbi__get8(s); + int tga_indexed = stbi__get8(s); + int tga_image_type = stbi__get8(s); + int tga_is_RLE = 0; + int tga_palette_start = stbi__get16le(s); + int tga_palette_len = stbi__get16le(s); + int tga_palette_bits = stbi__get8(s); + int tga_x_origin = stbi__get16le(s); + int tga_y_origin = stbi__get16le(s); + int tga_width = stbi__get16le(s); + int tga_height = stbi__get16le(s); + int tga_bits_per_pixel = stbi__get8(s); + int tga_comp, tga_rgb16=0; + int tga_inverted = stbi__get8(s); + // int tga_alpha_bits = tga_inverted & 15; // the 4 lowest bits - unused (useless?) + // image data + unsigned char *tga_data; + unsigned char *tga_palette = NULL; + int i, j; + unsigned char raw_data[4] = {0}; + int RLE_count = 0; + int RLE_repeating = 0; + int read_next_pixel = 1; + STBI_NOTUSED(ri); + STBI_NOTUSED(tga_x_origin); // @TODO + STBI_NOTUSED(tga_y_origin); // @TODO + + if (tga_height > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (tga_width > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // do a tiny bit of precessing + if ( tga_image_type >= 8 ) + { + tga_image_type -= 8; + tga_is_RLE = 1; + } + tga_inverted = 1 - ((tga_inverted >> 5) & 1); + + // If I'm paletted, then I'll use the number of bits from the palette + if ( tga_indexed ) tga_comp = stbi__tga_get_comp(tga_palette_bits, 0, &tga_rgb16); + else tga_comp = stbi__tga_get_comp(tga_bits_per_pixel, (tga_image_type == 3), &tga_rgb16); + + if(!tga_comp) // shouldn't really happen, stbi__tga_test() should have ensured basic consistency + return stbi__errpuc("bad format", "Can't find out TGA pixelformat"); + + // tga info + *x = tga_width; + *y = tga_height; + if (comp) *comp = tga_comp; + + if (!stbi__mad3sizes_valid(tga_width, tga_height, tga_comp, 0)) + return stbi__errpuc("too large", "Corrupt TGA"); + + tga_data = (unsigned char*)stbi__malloc_mad3(tga_width, tga_height, tga_comp, 0); + if (!tga_data) return stbi__errpuc("outofmem", "Out of memory"); + + // skip to the data's starting position (offset usually = 0) + stbi__skip(s, tga_offset ); + + if ( !tga_indexed && !tga_is_RLE && !tga_rgb16 ) { + for (i=0; i < tga_height; ++i) { + int row = tga_inverted ? tga_height -i - 1 : i; + stbi_uc *tga_row = tga_data + row*tga_width*tga_comp; + stbi__getn(s, tga_row, tga_width * tga_comp); + } + } else { + // do I need to load a palette? + if ( tga_indexed) + { + if (tga_palette_len == 0) { /* you have to have at least one entry! */ + STBI_FREE(tga_data); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + + // any data to skip? (offset usually = 0) + stbi__skip(s, tga_palette_start ); + // load the palette + tga_palette = (unsigned char*)stbi__malloc_mad2(tga_palette_len, tga_comp, 0); + if (!tga_palette) { + STBI_FREE(tga_data); + return stbi__errpuc("outofmem", "Out of memory"); + } + if (tga_rgb16) { + stbi_uc *pal_entry = tga_palette; + STBI_ASSERT(tga_comp == STBI_rgb); + for (i=0; i < tga_palette_len; ++i) { + stbi__tga_read_rgb16(s, pal_entry); + pal_entry += tga_comp; + } + } else if (!stbi__getn(s, tga_palette, tga_palette_len * tga_comp)) { + STBI_FREE(tga_data); + STBI_FREE(tga_palette); + return stbi__errpuc("bad palette", "Corrupt TGA"); + } + } + // load the data + for (i=0; i < tga_width * tga_height; ++i) + { + // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk? + if ( tga_is_RLE ) + { + if ( RLE_count == 0 ) + { + // yep, get the next byte as a RLE command + int RLE_cmd = stbi__get8(s); + RLE_count = 1 + (RLE_cmd & 127); + RLE_repeating = RLE_cmd >> 7; + read_next_pixel = 1; + } else if ( !RLE_repeating ) + { + read_next_pixel = 1; + } + } else + { + read_next_pixel = 1; + } + // OK, if I need to read a pixel, do it now + if ( read_next_pixel ) + { + // load however much data we did have + if ( tga_indexed ) + { + // read in index, then perform the lookup + int pal_idx = (tga_bits_per_pixel == 8) ? stbi__get8(s) : stbi__get16le(s); + if ( pal_idx >= tga_palette_len ) { + // invalid index + pal_idx = 0; + } + pal_idx *= tga_comp; + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = tga_palette[pal_idx+j]; + } + } else if(tga_rgb16) { + STBI_ASSERT(tga_comp == STBI_rgb); + stbi__tga_read_rgb16(s, raw_data); + } else { + // read in the data raw + for (j = 0; j < tga_comp; ++j) { + raw_data[j] = stbi__get8(s); + } + } + // clear the reading flag for the next pixel + read_next_pixel = 0; + } // end of reading a pixel + + // copy data + for (j = 0; j < tga_comp; ++j) + tga_data[i*tga_comp+j] = raw_data[j]; + + // in case we're in RLE mode, keep counting down + --RLE_count; + } + // do I need to invert the image? + if ( tga_inverted ) + { + for (j = 0; j*2 < tga_height; ++j) + { + int index1 = j * tga_width * tga_comp; + int index2 = (tga_height - 1 - j) * tga_width * tga_comp; + for (i = tga_width * tga_comp; i > 0; --i) + { + unsigned char temp = tga_data[index1]; + tga_data[index1] = tga_data[index2]; + tga_data[index2] = temp; + ++index1; + ++index2; + } + } + } + // clear my palette, if I had one + if ( tga_palette != NULL ) + { + STBI_FREE( tga_palette ); + } + } + + // swap RGB - if the source data was RGB16, it already is in the right order + if (tga_comp >= 3 && !tga_rgb16) + { + unsigned char* tga_pixel = tga_data; + for (i=0; i < tga_width * tga_height; ++i) + { + unsigned char temp = tga_pixel[0]; + tga_pixel[0] = tga_pixel[2]; + tga_pixel[2] = temp; + tga_pixel += tga_comp; + } + } + + // convert to target component count + if (req_comp && req_comp != tga_comp) + tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height); + + // the things I do to get rid of an error message, and yet keep + // Microsoft's C compilers happy... [8^( + tga_palette_start = tga_palette_len = tga_palette_bits = + tga_x_origin = tga_y_origin = 0; + STBI_NOTUSED(tga_palette_start); + // OK, done + return tga_data; +} +#endif + +// ************************************************************************************************* +// Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB + +#ifndef STBI_NO_PSD +static int stbi__psd_test(stbi__context *s) +{ + int r = (stbi__get32be(s) == 0x38425053); + stbi__rewind(s); + return r; +} + +static int stbi__psd_decode_rle(stbi__context *s, stbi_uc *p, int pixelCount) +{ + int count, nleft, len; + + count = 0; + while ((nleft = pixelCount - count) > 0) { + len = stbi__get8(s); + if (len == 128) { + // No-op. + } else if (len < 128) { + // Copy next len+1 bytes literally. + len++; + if (len > nleft) return 0; // corrupt data + count += len; + while (len) { + *p = stbi__get8(s); + p += 4; + len--; + } + } else if (len > 128) { + stbi_uc val; + // Next -len+1 bytes in the dest are replicated from next source byte. + // (Interpret len as a negative 8-bit int.) + len = 257 - len; + if (len > nleft) return 0; // corrupt data + val = stbi__get8(s); + count += len; + while (len) { + *p = val; + p += 4; + len--; + } + } + } + + return 1; +} + +static void *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri, int bpc) +{ + int pixelCount; + int channelCount, compression; + int channel, i; + int bitdepth; + int w,h; + stbi_uc *out; + STBI_NOTUSED(ri); + + // Check identifier + if (stbi__get32be(s) != 0x38425053) // "8BPS" + return stbi__errpuc("not PSD", "Corrupt PSD image"); + + // Check file type version. + if (stbi__get16be(s) != 1) + return stbi__errpuc("wrong version", "Unsupported version of PSD image"); + + // Skip 6 reserved bytes. + stbi__skip(s, 6 ); + + // Read the number of channels (R, G, B, A, etc). + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) + return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image"); + + // Read the rows and columns of the image. + h = stbi__get32be(s); + w = stbi__get32be(s); + + if (h > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (w > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + // Make sure the depth is 8 bits. + bitdepth = stbi__get16be(s); + if (bitdepth != 8 && bitdepth != 16) + return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 or 16 bit"); + + // Make sure the color mode is RGB. + // Valid options are: + // 0: Bitmap + // 1: Grayscale + // 2: Indexed color + // 3: RGB color + // 4: CMYK color + // 7: Multichannel + // 8: Duotone + // 9: Lab color + if (stbi__get16be(s) != 3) + return stbi__errpuc("wrong color format", "PSD is not in RGB color format"); + + // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.) + stbi__skip(s,stbi__get32be(s) ); + + // Skip the image resources. (resolution, pen tool paths, etc) + stbi__skip(s, stbi__get32be(s) ); + + // Skip the reserved data. + stbi__skip(s, stbi__get32be(s) ); + + // Find out if the data is compressed. + // Known values: + // 0: no compression + // 1: RLE compressed + compression = stbi__get16be(s); + if (compression > 1) + return stbi__errpuc("bad compression", "PSD has an unknown compression format"); + + // Check size + if (!stbi__mad3sizes_valid(4, w, h, 0)) + return stbi__errpuc("too large", "Corrupt PSD"); + + // Create the destination image. + + if (!compression && bitdepth == 16 && bpc == 16) { + out = (stbi_uc *) stbi__malloc_mad3(8, w, h, 0); + ri->bits_per_channel = 16; + } else + out = (stbi_uc *) stbi__malloc(4 * w*h); + + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + pixelCount = w*h; + + // Initialize the data to zero. + //memset( out, 0, pixelCount * 4 ); + + // Finally, the image data. + if (compression) { + // RLE as used by .PSD and .TIFF + // Loop until you get the number of unpacked bytes you are expecting: + // Read the next source byte into n. + // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally. + // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times. + // Else if n is 128, noop. + // Endloop + + // The RLE-compressed data is preceded by a 2-byte data count for each row in the data, + // which we're going to just skip. + stbi__skip(s, h * channelCount * 2 ); + + // Read the RLE data by channel. + for (channel = 0; channel < 4; channel++) { + stbi_uc *p; + + p = out+channel; + if (channel >= channelCount) { + // Fill this channel with default data. + for (i = 0; i < pixelCount; i++, p += 4) + *p = (channel == 3 ? 255 : 0); + } else { + // Read the RLE data. + if (!stbi__psd_decode_rle(s, p, pixelCount)) { + STBI_FREE(out); + return stbi__errpuc("corrupt", "bad RLE data"); + } + } + } + + } else { + // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...) + // where each channel consists of an 8-bit (or 16-bit) value for each pixel in the image. + + // Read the data by channel. + for (channel = 0; channel < 4; channel++) { + if (channel >= channelCount) { + // Fill this channel with default data. + if (bitdepth == 16 && bpc == 16) { + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + stbi__uint16 val = channel == 3 ? 65535 : 0; + for (i = 0; i < pixelCount; i++, q += 4) + *q = val; + } else { + stbi_uc *p = out+channel; + stbi_uc val = channel == 3 ? 255 : 0; + for (i = 0; i < pixelCount; i++, p += 4) + *p = val; + } + } else { + if (ri->bits_per_channel == 16) { // output bpc + stbi__uint16 *q = ((stbi__uint16 *) out) + channel; + for (i = 0; i < pixelCount; i++, q += 4) + *q = (stbi__uint16) stbi__get16be(s); + } else { + stbi_uc *p = out+channel; + if (bitdepth == 16) { // input bpc + for (i = 0; i < pixelCount; i++, p += 4) + *p = (stbi_uc) (stbi__get16be(s) >> 8); + } else { + for (i = 0; i < pixelCount; i++, p += 4) + *p = stbi__get8(s); + } + } + } + } + } + + // remove weird white matte from PSD + if (channelCount >= 4) { + if (ri->bits_per_channel == 16) { + for (i=0; i < w*h; ++i) { + stbi__uint16 *pixel = (stbi__uint16 *) out + 4*i; + if (pixel[3] != 0 && pixel[3] != 65535) { + float a = pixel[3] / 65535.0f; + float ra = 1.0f / a; + float inv_a = 65535.0f * (1 - ra); + pixel[0] = (stbi__uint16) (pixel[0]*ra + inv_a); + pixel[1] = (stbi__uint16) (pixel[1]*ra + inv_a); + pixel[2] = (stbi__uint16) (pixel[2]*ra + inv_a); + } + } + } else { + for (i=0; i < w*h; ++i) { + unsigned char *pixel = out + 4*i; + if (pixel[3] != 0 && pixel[3] != 255) { + float a = pixel[3] / 255.0f; + float ra = 1.0f / a; + float inv_a = 255.0f * (1 - ra); + pixel[0] = (unsigned char) (pixel[0]*ra + inv_a); + pixel[1] = (unsigned char) (pixel[1]*ra + inv_a); + pixel[2] = (unsigned char) (pixel[2]*ra + inv_a); + } + } + } + } + + // convert to desired output format + if (req_comp && req_comp != 4) { + if (ri->bits_per_channel == 16) + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, 4, req_comp, w, h); + else + out = stbi__convert_format(out, 4, req_comp, w, h); + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + + if (comp) *comp = 4; + *y = h; + *x = w; + + return out; +} +#endif + +// ************************************************************************************************* +// Softimage PIC loader +// by Tom Seddon +// +// See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format +// See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/ + +#ifndef STBI_NO_PIC +static int stbi__pic_is4(stbi__context *s,const char *str) +{ + int i; + for (i=0; i<4; ++i) + if (stbi__get8(s) != (stbi_uc)str[i]) + return 0; + + return 1; +} + +static int stbi__pic_test_core(stbi__context *s) +{ + int i; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) + return 0; + + for(i=0;i<84;++i) + stbi__get8(s); + + if (!stbi__pic_is4(s,"PICT")) + return 0; + + return 1; +} + +typedef struct +{ + stbi_uc size,type,channel; +} stbi__pic_packet; + +static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest) +{ + int mask=0x80, i; + + for (i=0; i<4; ++i, mask>>=1) { + if (channel & mask) { + if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short"); + dest[i]=stbi__get8(s); + } + } + + return dest; +} + +static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src) +{ + int mask=0x80,i; + + for (i=0;i<4; ++i, mask>>=1) + if (channel&mask) + dest[i]=src[i]; +} + +static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result) +{ + int act_comp=0,num_packets=0,y,chained; + stbi__pic_packet packets[10]; + + // this will (should...) cater for even some bizarre stuff like having data + // for the same channel in multiple packets. + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return stbi__errpuc("bad format","too many packets"); + + packet = &packets[num_packets++]; + + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + + act_comp |= packet->channel; + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)"); + if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp"); + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel? + + for(y=0; ytype) { + default: + return stbi__errpuc("bad format","packet has bad compression type"); + + case 0: {//uncompressed + int x; + + for(x=0;xchannel,dest)) + return 0; + break; + } + + case 1://Pure RLE + { + int left=width, i; + + while (left>0) { + stbi_uc count,value[4]; + + count=stbi__get8(s); + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)"); + + if (count > left) + count = (stbi_uc) left; + + if (!stbi__readval(s,packet->channel,value)) return 0; + + for(i=0; ichannel,dest,value); + left -= count; + } + } + break; + + case 2: {//Mixed RLE + int left=width; + while (left>0) { + int count = stbi__get8(s), i; + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)"); + + if (count >= 128) { // Repeated + stbi_uc value[4]; + + if (count==128) + count = stbi__get16be(s); + else + count -= 127; + if (count > left) + return stbi__errpuc("bad file","scanline overrun"); + + if (!stbi__readval(s,packet->channel,value)) + return 0; + + for(i=0;ichannel,dest,value); + } else { // Raw + ++count; + if (count>left) return stbi__errpuc("bad file","scanline overrun"); + + for(i=0;ichannel,dest)) + return 0; + } + left-=count; + } + break; + } + } + } + } + + return result; +} + +static void *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp, stbi__result_info *ri) +{ + stbi_uc *result; + int i, x,y, internal_comp; + STBI_NOTUSED(ri); + + if (!comp) comp = &internal_comp; + + for (i=0; i<92; ++i) + stbi__get8(s); + + x = stbi__get16be(s); + y = stbi__get16be(s); + + if (y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)"); + if (!stbi__mad3sizes_valid(x, y, 4, 0)) return stbi__errpuc("too large", "PIC image too large to decode"); + + stbi__get32be(s); //skip `ratio' + stbi__get16be(s); //skip `fields' + stbi__get16be(s); //skip `pad' + + // intermediate buffer is RGBA + result = (stbi_uc *) stbi__malloc_mad3(x, y, 4, 0); + if (!result) return stbi__errpuc("outofmem", "Out of memory"); + memset(result, 0xff, x*y*4); + + if (!stbi__pic_load_core(s,x,y,comp, result)) { + STBI_FREE(result); + result=0; + } + *px = x; + *py = y; + if (req_comp == 0) req_comp = *comp; + result=stbi__convert_format(result,4,req_comp,x,y); + + return result; +} + +static int stbi__pic_test(stbi__context *s) +{ + int r = stbi__pic_test_core(s); + stbi__rewind(s); + return r; +} +#endif + +// ************************************************************************************************* +// GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb + +#ifndef STBI_NO_GIF +typedef struct +{ + stbi__int16 prefix; + stbi_uc first; + stbi_uc suffix; +} stbi__gif_lzw; + +typedef struct +{ + int w,h; + stbi_uc *out; // output buffer (always 4 components) + stbi_uc *background; // The current "background" as far as a gif is concerned + stbi_uc *history; + int flags, bgindex, ratio, transparent, eflags; + stbi_uc pal[256][4]; + stbi_uc lpal[256][4]; + stbi__gif_lzw codes[8192]; + stbi_uc *color_table; + int parse, step; + int lflags; + int start_x, start_y; + int max_x, max_y; + int cur_x, cur_y; + int line_size; + int delay; +} stbi__gif; + +static int stbi__gif_test_raw(stbi__context *s) +{ + int sz; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0; + sz = stbi__get8(s); + if (sz != '9' && sz != '7') return 0; + if (stbi__get8(s) != 'a') return 0; + return 1; +} + +static int stbi__gif_test(stbi__context *s) +{ + int r = stbi__gif_test_raw(s); + stbi__rewind(s); + return r; +} + +static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp) +{ + int i; + for (i=0; i < num_entries; ++i) { + pal[i][2] = stbi__get8(s); + pal[i][1] = stbi__get8(s); + pal[i][0] = stbi__get8(s); + pal[i][3] = transp == i ? 0 : 255; + } +} + +static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info) +{ + stbi_uc version; + if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') + return stbi__err("not GIF", "Corrupt GIF"); + + version = stbi__get8(s); + if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF"); + if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF"); + + stbi__g_failure_reason = ""; + g->w = stbi__get16le(s); + g->h = stbi__get16le(s); + g->flags = stbi__get8(s); + g->bgindex = stbi__get8(s); + g->ratio = stbi__get8(s); + g->transparent = -1; + + if (g->w > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + if (g->h > STBI_MAX_DIMENSIONS) return stbi__err("too large","Very large image (corrupt?)"); + + if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments + + if (is_info) return 1; + + if (g->flags & 0x80) + stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1); + + return 1; +} + +static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp) +{ + stbi__gif* g = (stbi__gif*) stbi__malloc(sizeof(stbi__gif)); + if (!g) return stbi__err("outofmem", "Out of memory"); + if (!stbi__gif_header(s, g, comp, 1)) { + STBI_FREE(g); + stbi__rewind( s ); + return 0; + } + if (x) *x = g->w; + if (y) *y = g->h; + STBI_FREE(g); + return 1; +} + +static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code) +{ + stbi_uc *p, *c; + int idx; + + // recurse to decode the prefixes, since the linked-list is backwards, + // and working backwards through an interleaved image would be nasty + if (g->codes[code].prefix >= 0) + stbi__out_gif_code(g, g->codes[code].prefix); + + if (g->cur_y >= g->max_y) return; + + idx = g->cur_x + g->cur_y; + p = &g->out[idx]; + g->history[idx / 4] = 1; + + c = &g->color_table[g->codes[code].suffix * 4]; + if (c[3] > 128) { // don't render transparent pixels; + p[0] = c[2]; + p[1] = c[1]; + p[2] = c[0]; + p[3] = c[3]; + } + g->cur_x += 4; + + if (g->cur_x >= g->max_x) { + g->cur_x = g->start_x; + g->cur_y += g->step; + + while (g->cur_y >= g->max_y && g->parse > 0) { + g->step = (1 << g->parse) * g->line_size; + g->cur_y = g->start_y + (g->step >> 1); + --g->parse; + } + } +} + +static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g) +{ + stbi_uc lzw_cs; + stbi__int32 len, init_code; + stbi__uint32 first; + stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear; + stbi__gif_lzw *p; + + lzw_cs = stbi__get8(s); + if (lzw_cs > 12) return NULL; + clear = 1 << lzw_cs; + first = 1; + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + bits = 0; + valid_bits = 0; + for (init_code = 0; init_code < clear; init_code++) { + g->codes[init_code].prefix = -1; + g->codes[init_code].first = (stbi_uc) init_code; + g->codes[init_code].suffix = (stbi_uc) init_code; + } + + // support no starting clear code + avail = clear+2; + oldcode = -1; + + len = 0; + for(;;) { + if (valid_bits < codesize) { + if (len == 0) { + len = stbi__get8(s); // start new block + if (len == 0) + return g->out; + } + --len; + bits |= (stbi__int32) stbi__get8(s) << valid_bits; + valid_bits += 8; + } else { + stbi__int32 code = bits & codemask; + bits >>= codesize; + valid_bits -= codesize; + // @OPTIMIZE: is there some way we can accelerate the non-clear path? + if (code == clear) { // clear code + codesize = lzw_cs + 1; + codemask = (1 << codesize) - 1; + avail = clear + 2; + oldcode = -1; + first = 0; + } else if (code == clear + 1) { // end of stream code + stbi__skip(s, len); + while ((len = stbi__get8(s)) > 0) + stbi__skip(s,len); + return g->out; + } else if (code <= avail) { + if (first) { + return stbi__errpuc("no clear code", "Corrupt GIF"); + } + + if (oldcode >= 0) { + p = &g->codes[avail++]; + if (avail > 8192) { + return stbi__errpuc("too many codes", "Corrupt GIF"); + } + + p->prefix = (stbi__int16) oldcode; + p->first = g->codes[oldcode].first; + p->suffix = (code == avail) ? p->first : g->codes[code].first; + } else if (code == avail) + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + + stbi__out_gif_code(g, (stbi__uint16) code); + + if ((avail & codemask) == 0 && avail <= 0x0FFF) { + codesize++; + codemask = (1 << codesize) - 1; + } + + oldcode = code; + } else { + return stbi__errpuc("illegal code in raster", "Corrupt GIF"); + } + } + } +} + +// this function is designed to support animated gifs, although stb_image doesn't support it +// two back is the image from two frames ago, used for a very specific disposal format +static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp, stbi_uc *two_back) +{ + int dispose; + int first_frame; + int pi; + int pcount; + STBI_NOTUSED(req_comp); + + // on first frame, any non-written pixels get the background colour (non-transparent) + first_frame = 0; + if (g->out == 0) { + if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header + if (!stbi__mad3sizes_valid(4, g->w, g->h, 0)) + return stbi__errpuc("too large", "GIF image is too large"); + pcount = g->w * g->h; + g->out = (stbi_uc *) stbi__malloc(4 * pcount); + g->background = (stbi_uc *) stbi__malloc(4 * pcount); + g->history = (stbi_uc *) stbi__malloc(pcount); + if (!g->out || !g->background || !g->history) + return stbi__errpuc("outofmem", "Out of memory"); + + // image is treated as "transparent" at the start - ie, nothing overwrites the current background; + // background colour is only used for pixels that are not rendered first frame, after that "background" + // color refers to the color that was there the previous frame. + memset(g->out, 0x00, 4 * pcount); + memset(g->background, 0x00, 4 * pcount); // state of the background (starts transparent) + memset(g->history, 0x00, pcount); // pixels that were affected previous frame + first_frame = 1; + } else { + // second frame - how do we dispose of the previous one? + dispose = (g->eflags & 0x1C) >> 2; + pcount = g->w * g->h; + + if ((dispose == 3) && (two_back == 0)) { + dispose = 2; // if I don't have an image to revert back to, default to the old background + } + + if (dispose == 3) { // use previous graphic + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &two_back[pi * 4], 4 ); + } + } + } else if (dispose == 2) { + // restore what was changed last frame to background before that frame; + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi]) { + memcpy( &g->out[pi * 4], &g->background[pi * 4], 4 ); + } + } + } else { + // This is a non-disposal case eithe way, so just + // leave the pixels as is, and they will become the new background + // 1: do not dispose + // 0: not specified. + } + + // background is what out is after the undoing of the previou frame; + memcpy( g->background, g->out, 4 * g->w * g->h ); + } + + // clear my history; + memset( g->history, 0x00, g->w * g->h ); // pixels that were affected previous frame + + for (;;) { + int tag = stbi__get8(s); + switch (tag) { + case 0x2C: /* Image Descriptor */ + { + stbi__int32 x, y, w, h; + stbi_uc *o; + + x = stbi__get16le(s); + y = stbi__get16le(s); + w = stbi__get16le(s); + h = stbi__get16le(s); + if (((x + w) > (g->w)) || ((y + h) > (g->h))) + return stbi__errpuc("bad Image Descriptor", "Corrupt GIF"); + + g->line_size = g->w * 4; + g->start_x = x * 4; + g->start_y = y * g->line_size; + g->max_x = g->start_x + w * 4; + g->max_y = g->start_y + h * g->line_size; + g->cur_x = g->start_x; + g->cur_y = g->start_y; + + // if the width of the specified rectangle is 0, that means + // we may not see *any* pixels or the image is malformed; + // to make sure this is caught, move the current y down to + // max_y (which is what out_gif_code checks). + if (w == 0) + g->cur_y = g->max_y; + + g->lflags = stbi__get8(s); + + if (g->lflags & 0x40) { + g->step = 8 * g->line_size; // first interlaced spacing + g->parse = 3; + } else { + g->step = g->line_size; + g->parse = 0; + } + + if (g->lflags & 0x80) { + stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1); + g->color_table = (stbi_uc *) g->lpal; + } else if (g->flags & 0x80) { + g->color_table = (stbi_uc *) g->pal; + } else + return stbi__errpuc("missing color table", "Corrupt GIF"); + + o = stbi__process_gif_raster(s, g); + if (!o) return NULL; + + // if this was the first frame, + pcount = g->w * g->h; + if (first_frame && (g->bgindex > 0)) { + // if first frame, any pixel not drawn to gets the background color + for (pi = 0; pi < pcount; ++pi) { + if (g->history[pi] == 0) { + g->pal[g->bgindex][3] = 255; // just in case it was made transparent, undo that; It will be reset next frame if need be; + memcpy( &g->out[pi * 4], &g->pal[g->bgindex], 4 ); + } + } + } + + return o; + } + + case 0x21: // Comment Extension. + { + int len; + int ext = stbi__get8(s); + if (ext == 0xF9) { // Graphic Control Extension. + len = stbi__get8(s); + if (len == 4) { + g->eflags = stbi__get8(s); + g->delay = 10 * stbi__get16le(s); // delay - 1/100th of a second, saving as 1/1000ths. + + // unset old transparent + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 255; + } + if (g->eflags & 0x01) { + g->transparent = stbi__get8(s); + if (g->transparent >= 0) { + g->pal[g->transparent][3] = 0; + } + } else { + // don't need transparent + stbi__skip(s, 1); + g->transparent = -1; + } + } else { + stbi__skip(s, len); + break; + } + } + while ((len = stbi__get8(s)) != 0) { + stbi__skip(s, len); + } + break; + } + + case 0x3B: // gif stream termination code + return (stbi_uc *) s; // using '1' causes warning on some compilers + + default: + return stbi__errpuc("unknown code", "Corrupt GIF"); + } + } +} + +static void *stbi__load_gif_main_outofmem(stbi__gif *g, stbi_uc *out, int **delays) +{ + STBI_FREE(g->out); + STBI_FREE(g->history); + STBI_FREE(g->background); + + if (out) STBI_FREE(out); + if (delays && *delays) STBI_FREE(*delays); + return stbi__errpuc("outofmem", "Out of memory"); +} + +static void *stbi__load_gif_main(stbi__context *s, int **delays, int *x, int *y, int *z, int *comp, int req_comp) +{ + if (stbi__gif_test(s)) { + int layers = 0; + stbi_uc *u = 0; + stbi_uc *out = 0; + stbi_uc *two_back = 0; + stbi__gif g; + int stride; + int out_size = 0; + int delays_size = 0; + + STBI_NOTUSED(out_size); + STBI_NOTUSED(delays_size); + + memset(&g, 0, sizeof(g)); + if (delays) { + *delays = 0; + } + + do { + u = stbi__gif_load_next(s, &g, comp, req_comp, two_back); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + + if (u) { + *x = g.w; + *y = g.h; + ++layers; + stride = g.w * g.h * 4; + + if (out) { + void *tmp = (stbi_uc*) STBI_REALLOC_SIZED( out, out_size, layers * stride ); + if (!tmp) + return stbi__load_gif_main_outofmem(&g, out, delays); + else { + out = (stbi_uc*) tmp; + out_size = layers * stride; + } + + if (delays) { + int *new_delays = (int*) STBI_REALLOC_SIZED( *delays, delays_size, sizeof(int) * layers ); + if (!new_delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + *delays = new_delays; + delays_size = layers * sizeof(int); + } + } else { + out = (stbi_uc*)stbi__malloc( layers * stride ); + if (!out) + return stbi__load_gif_main_outofmem(&g, out, delays); + out_size = layers * stride; + if (delays) { + *delays = (int*) stbi__malloc( layers * sizeof(int) ); + if (!*delays) + return stbi__load_gif_main_outofmem(&g, out, delays); + delays_size = layers * sizeof(int); + } + } + memcpy( out + ((layers - 1) * stride), u, stride ); + if (layers >= 2) { + two_back = out - 2 * stride; + } + + if (delays) { + (*delays)[layers - 1U] = g.delay; + } + } + } while (u != 0); + + // free temp buffer; + STBI_FREE(g.out); + STBI_FREE(g.history); + STBI_FREE(g.background); + + // do the final conversion after loading everything; + if (req_comp && req_comp != 4) + out = stbi__convert_format(out, 4, req_comp, layers * g.w, g.h); + + *z = layers; + return out; + } else { + return stbi__errpuc("not GIF", "Image was not as a gif type."); + } +} + +static void *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *u = 0; + stbi__gif g; + memset(&g, 0, sizeof(g)); + STBI_NOTUSED(ri); + + u = stbi__gif_load_next(s, &g, comp, req_comp, 0); + if (u == (stbi_uc *) s) u = 0; // end of animated gif marker + if (u) { + *x = g.w; + *y = g.h; + + // moved conversion to after successful load so that the same + // can be done for multiple frames. + if (req_comp && req_comp != 4) + u = stbi__convert_format(u, 4, req_comp, g.w, g.h); + } else if (g.out) { + // if there was an error and we allocated an image buffer, free it! + STBI_FREE(g.out); + } + + // free buffers needed for multiple frame loading; + STBI_FREE(g.history); + STBI_FREE(g.background); + + return u; +} + +static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp) +{ + return stbi__gif_info_raw(s,x,y,comp); +} +#endif + +// ************************************************************************************************* +// Radiance RGBE HDR loader +// originally by Nicolas Schulz +#ifndef STBI_NO_HDR +static int stbi__hdr_test_core(stbi__context *s, const char *signature) +{ + int i; + for (i=0; signature[i]; ++i) + if (stbi__get8(s) != signature[i]) + return 0; + stbi__rewind(s); + return 1; +} + +static int stbi__hdr_test(stbi__context* s) +{ + int r = stbi__hdr_test_core(s, "#?RADIANCE\n"); + stbi__rewind(s); + if(!r) { + r = stbi__hdr_test_core(s, "#?RGBE\n"); + stbi__rewind(s); + } + return r; +} + +#define STBI__HDR_BUFLEN 1024 +static char *stbi__hdr_gettoken(stbi__context *z, char *buffer) +{ + int len=0; + char c = '\0'; + + c = (char) stbi__get8(z); + + while (!stbi__at_eof(z) && c != '\n') { + buffer[len++] = c; + if (len == STBI__HDR_BUFLEN-1) { + // flush to end of line + while (!stbi__at_eof(z) && stbi__get8(z) != '\n') + ; + break; + } + c = (char) stbi__get8(z); + } + + buffer[len] = 0; + return buffer; +} + +static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp) +{ + if ( input[3] != 0 ) { + float f1; + // Exponent + f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8)); + if (req_comp <= 2) + output[0] = (input[0] + input[1] + input[2]) * f1 / 3; + else { + output[0] = input[0] * f1; + output[1] = input[1] * f1; + output[2] = input[2] * f1; + } + if (req_comp == 2) output[1] = 1; + if (req_comp == 4) output[3] = 1; + } else { + switch (req_comp) { + case 4: output[3] = 1; /* fallthrough */ + case 3: output[0] = output[1] = output[2] = 0; + break; + case 2: output[1] = 1; /* fallthrough */ + case 1: output[0] = 0; + break; + } + } +} + +static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int width, height; + stbi_uc *scanline; + float *hdr_data; + int len; + unsigned char count, value; + int i, j, k, c1,c2, z; + const char *headerToken; + STBI_NOTUSED(ri); + + // Check identifier + headerToken = stbi__hdr_gettoken(s,buffer); + if (strcmp(headerToken, "#?RADIANCE") != 0 && strcmp(headerToken, "#?RGBE") != 0) + return stbi__errpf("not HDR", "Corrupt HDR image"); + + // Parse header + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format"); + + // Parse width and height + // can't use sscanf() if we're not using stdio! + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + height = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format"); + token += 3; + width = (int) strtol(token, NULL, 10); + + if (height > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + if (width > STBI_MAX_DIMENSIONS) return stbi__errpf("too large","Very large image (corrupt?)"); + + *x = width; + *y = height; + + if (comp) *comp = 3; + if (req_comp == 0) req_comp = 3; + + if (!stbi__mad4sizes_valid(width, height, req_comp, sizeof(float), 0)) + return stbi__errpf("too large", "HDR image is too large"); + + // Read data + hdr_data = (float *) stbi__malloc_mad4(width, height, req_comp, sizeof(float), 0); + if (!hdr_data) + return stbi__errpf("outofmem", "Out of memory"); + + // Load image data + // image data is stored as some number of sca + if ( width < 8 || width >= 32768) { + // Read flat data + for (j=0; j < height; ++j) { + for (i=0; i < width; ++i) { + stbi_uc rgbe[4]; + main_decode_loop: + stbi__getn(s, rgbe, 4); + stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp); + } + } + } else { + // Read RLE-encoded data + scanline = NULL; + + for (j = 0; j < height; ++j) { + c1 = stbi__get8(s); + c2 = stbi__get8(s); + len = stbi__get8(s); + if (c1 != 2 || c2 != 2 || (len & 0x80)) { + // not run-length encoded, so we have to actually use THIS data as a decoded + // pixel (note this can't be a valid pixel--one of RGB must be >= 128) + stbi_uc rgbe[4]; + rgbe[0] = (stbi_uc) c1; + rgbe[1] = (stbi_uc) c2; + rgbe[2] = (stbi_uc) len; + rgbe[3] = (stbi_uc) stbi__get8(s); + stbi__hdr_convert(hdr_data, rgbe, req_comp); + i = 1; + j = 0; + STBI_FREE(scanline); + goto main_decode_loop; // yes, this makes no sense + } + len <<= 8; + len |= stbi__get8(s); + if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); } + if (scanline == NULL) { + scanline = (stbi_uc *) stbi__malloc_mad2(width, 4, 0); + if (!scanline) { + STBI_FREE(hdr_data); + return stbi__errpf("outofmem", "Out of memory"); + } + } + + for (k = 0; k < 4; ++k) { + int nleft; + i = 0; + while ((nleft = width - i) > 0) { + count = stbi__get8(s); + if (count > 128) { + // Run + value = stbi__get8(s); + count -= 128; + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = value; + } else { + // Dump + if ((count == 0) || (count > nleft)) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("corrupt", "bad RLE data in HDR"); } + for (z = 0; z < count; ++z) + scanline[i++ * 4 + k] = stbi__get8(s); + } + } + } + for (i=0; i < width; ++i) + stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp); + } + if (scanline) + STBI_FREE(scanline); + } + + return hdr_data; +} + +static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp) +{ + char buffer[STBI__HDR_BUFLEN]; + char *token; + int valid = 0; + int dummy; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (stbi__hdr_test(s) == 0) { + stbi__rewind( s ); + return 0; + } + + for(;;) { + token = stbi__hdr_gettoken(s,buffer); + if (token[0] == 0) break; + if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1; + } + + if (!valid) { + stbi__rewind( s ); + return 0; + } + token = stbi__hdr_gettoken(s,buffer); + if (strncmp(token, "-Y ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *y = (int) strtol(token, &token, 10); + while (*token == ' ') ++token; + if (strncmp(token, "+X ", 3)) { + stbi__rewind( s ); + return 0; + } + token += 3; + *x = (int) strtol(token, NULL, 10); + *comp = 3; + return 1; +} +#endif // STBI_NO_HDR + +#ifndef STBI_NO_BMP +static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp) +{ + void *p; + stbi__bmp_data info; + + info.all_a = 255; + p = stbi__bmp_parse_header(s, &info); + if (p == NULL) { + stbi__rewind( s ); + return 0; + } + if (x) *x = s->img_x; + if (y) *y = s->img_y; + if (comp) { + if (info.bpp == 24 && info.ma == 0xff000000) + *comp = 3; + else + *comp = info.ma ? 4 : 3; + } + return 1; +} +#endif + +#ifndef STBI_NO_PSD +static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp) +{ + int channelCount, dummy, depth; + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + *y = stbi__get32be(s); + *x = stbi__get32be(s); + depth = stbi__get16be(s); + if (depth != 8 && depth != 16) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 3) { + stbi__rewind( s ); + return 0; + } + *comp = 4; + return 1; +} + +static int stbi__psd_is16(stbi__context *s) +{ + int channelCount, depth; + if (stbi__get32be(s) != 0x38425053) { + stbi__rewind( s ); + return 0; + } + if (stbi__get16be(s) != 1) { + stbi__rewind( s ); + return 0; + } + stbi__skip(s, 6); + channelCount = stbi__get16be(s); + if (channelCount < 0 || channelCount > 16) { + stbi__rewind( s ); + return 0; + } + STBI_NOTUSED(stbi__get32be(s)); + STBI_NOTUSED(stbi__get32be(s)); + depth = stbi__get16be(s); + if (depth != 16) { + stbi__rewind( s ); + return 0; + } + return 1; +} +#endif + +#ifndef STBI_NO_PIC +static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp) +{ + int act_comp=0,num_packets=0,chained,dummy; + stbi__pic_packet packets[10]; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + if (!stbi__pic_is4(s,"\x53\x80\xF6\x34")) { + stbi__rewind(s); + return 0; + } + + stbi__skip(s, 88); + + *x = stbi__get16be(s); + *y = stbi__get16be(s); + if (stbi__at_eof(s)) { + stbi__rewind( s); + return 0; + } + if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) { + stbi__rewind( s ); + return 0; + } + + stbi__skip(s, 8); + + do { + stbi__pic_packet *packet; + + if (num_packets==sizeof(packets)/sizeof(packets[0])) + return 0; + + packet = &packets[num_packets++]; + chained = stbi__get8(s); + packet->size = stbi__get8(s); + packet->type = stbi__get8(s); + packet->channel = stbi__get8(s); + act_comp |= packet->channel; + + if (stbi__at_eof(s)) { + stbi__rewind( s ); + return 0; + } + if (packet->size != 8) { + stbi__rewind( s ); + return 0; + } + } while (chained); + + *comp = (act_comp & 0x10 ? 4 : 3); + + return 1; +} +#endif + +// ************************************************************************************************* +// Portable Gray Map and Portable Pixel Map loader +// by Ken Miller +// +// PGM: http://netpbm.sourceforge.net/doc/pgm.html +// PPM: http://netpbm.sourceforge.net/doc/ppm.html +// +// Known limitations: +// Does not support comments in the header section +// Does not support ASCII image data (formats P2 and P3) + +#ifndef STBI_NO_PNM + +static int stbi__pnm_test(stbi__context *s) +{ + char p, t; + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind( s ); + return 0; + } + return 1; +} + +static void *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp, stbi__result_info *ri) +{ + stbi_uc *out; + STBI_NOTUSED(ri); + + ri->bits_per_channel = stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n); + if (ri->bits_per_channel == 0) + return 0; + + if (s->img_y > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + if (s->img_x > STBI_MAX_DIMENSIONS) return stbi__errpuc("too large","Very large image (corrupt?)"); + + *x = s->img_x; + *y = s->img_y; + if (comp) *comp = s->img_n; + + if (!stbi__mad4sizes_valid(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0)) + return stbi__errpuc("too large", "PNM too large"); + + out = (stbi_uc *) stbi__malloc_mad4(s->img_n, s->img_x, s->img_y, ri->bits_per_channel / 8, 0); + if (!out) return stbi__errpuc("outofmem", "Out of memory"); + if (!stbi__getn(s, out, s->img_n * s->img_x * s->img_y * (ri->bits_per_channel / 8))) { + STBI_FREE(out); + return stbi__errpuc("bad PNM", "PNM file truncated"); + } + + if (req_comp && req_comp != s->img_n) { + if (ri->bits_per_channel == 16) { + out = (stbi_uc *) stbi__convert_format16((stbi__uint16 *) out, s->img_n, req_comp, s->img_x, s->img_y); + } else { + out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y); + } + if (out == NULL) return out; // stbi__convert_format frees input on failure + } + return out; +} + +static int stbi__pnm_isspace(char c) +{ + return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r'; +} + +static void stbi__pnm_skip_whitespace(stbi__context *s, char *c) +{ + for (;;) { + while (!stbi__at_eof(s) && stbi__pnm_isspace(*c)) + *c = (char) stbi__get8(s); + + if (stbi__at_eof(s) || *c != '#') + break; + + while (!stbi__at_eof(s) && *c != '\n' && *c != '\r' ) + *c = (char) stbi__get8(s); + } +} + +static int stbi__pnm_isdigit(char c) +{ + return c >= '0' && c <= '9'; +} + +static int stbi__pnm_getinteger(stbi__context *s, char *c) +{ + int value = 0; + + while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) { + value = value*10 + (*c - '0'); + *c = (char) stbi__get8(s); + if((value > 214748364) || (value == 214748364 && *c > '7')) + return stbi__err("integer parse overflow", "Parsing an integer in the PPM header overflowed a 32-bit int"); + } + + return value; +} + +static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp) +{ + int maxv, dummy; + char c, p, t; + + if (!x) x = &dummy; + if (!y) y = &dummy; + if (!comp) comp = &dummy; + + stbi__rewind(s); + + // Get identifier + p = (char) stbi__get8(s); + t = (char) stbi__get8(s); + if (p != 'P' || (t != '5' && t != '6')) { + stbi__rewind(s); + return 0; + } + + *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm + + c = (char) stbi__get8(s); + stbi__pnm_skip_whitespace(s, &c); + + *x = stbi__pnm_getinteger(s, &c); // read width + if(*x == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + *y = stbi__pnm_getinteger(s, &c); // read height + if (*y == 0) + return stbi__err("invalid width", "PPM image header had zero or overflowing width"); + stbi__pnm_skip_whitespace(s, &c); + + maxv = stbi__pnm_getinteger(s, &c); // read max value + if (maxv > 65535) + return stbi__err("max value > 65535", "PPM image supports only 8-bit and 16-bit images"); + else if (maxv > 255) + return 16; + else + return 8; +} + +static int stbi__pnm_is16(stbi__context *s) +{ + if (stbi__pnm_info(s, NULL, NULL, NULL) == 16) + return 1; + return 0; +} +#endif + +static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp) +{ + #ifndef STBI_NO_JPEG + if (stbi__jpeg_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNG + if (stbi__png_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_GIF + if (stbi__gif_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_BMP + if (stbi__bmp_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PIC + if (stbi__pic_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_info(s, x, y, comp)) return 1; + #endif + + #ifndef STBI_NO_HDR + if (stbi__hdr_info(s, x, y, comp)) return 1; + #endif + + // test tga last because it's a crappy test! + #ifndef STBI_NO_TGA + if (stbi__tga_info(s, x, y, comp)) + return 1; + #endif + return stbi__err("unknown image type", "Image not of any known type, or corrupt"); +} + +static int stbi__is_16_main(stbi__context *s) +{ + #ifndef STBI_NO_PNG + if (stbi__png_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PSD + if (stbi__psd_is16(s)) return 1; + #endif + + #ifndef STBI_NO_PNM + if (stbi__pnm_is16(s)) return 1; + #endif + return 0; +} + +#ifndef STBI_NO_STDIO +STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_info_from_file(f, x, y, comp); + fclose(f); + return result; +} + +STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__info_main(&s,x,y,comp); + fseek(f,pos,SEEK_SET); + return r; +} + +STBIDEF int stbi_is_16_bit(char const *filename) +{ + FILE *f = stbi__fopen(filename, "rb"); + int result; + if (!f) return stbi__err("can't fopen", "Unable to open file"); + result = stbi_is_16_bit_from_file(f); + fclose(f); + return result; +} + +STBIDEF int stbi_is_16_bit_from_file(FILE *f) +{ + int r; + stbi__context s; + long pos = ftell(f); + stbi__start_file(&s, f); + r = stbi__is_16_main(&s); + fseek(f,pos,SEEK_SET); + return r; +} +#endif // !STBI_NO_STDIO + +STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__info_main(&s,x,y,comp); +} + +STBIDEF int stbi_is_16_bit_from_memory(stbi_uc const *buffer, int len) +{ + stbi__context s; + stbi__start_mem(&s,buffer,len); + return stbi__is_16_main(&s); +} + +STBIDEF int stbi_is_16_bit_from_callbacks(stbi_io_callbacks const *c, void *user) +{ + stbi__context s; + stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user); + return stbi__is_16_main(&s); +} + +#endif // STB_IMAGE_IMPLEMENTATION + +/* + revision history: + 2.20 (2019-02-07) support utf8 filenames in Windows; fix warnings and platform ifdefs + 2.19 (2018-02-11) fix warning + 2.18 (2018-01-30) fix warnings + 2.17 (2018-01-29) change sbti__shiftsigned to avoid clang -O2 bug + 1-bit BMP + *_is_16_bit api + avoid warnings + 2.16 (2017-07-23) all functions have 16-bit variants; + STBI_NO_STDIO works again; + compilation fixes; + fix rounding in unpremultiply; + optimize vertical flip; + disable raw_len validation; + documentation fixes + 2.15 (2017-03-18) fix png-1,2,4 bug; now all Imagenet JPGs decode; + warning fixes; disable run-time SSE detection on gcc; + uniform handling of optional "return" values; + thread-safe initialization of zlib tables + 2.14 (2017-03-03) remove deprecated STBI_JPEG_OLD; fixes for Imagenet JPGs + 2.13 (2016-11-29) add 16-bit API, only supported for PNG right now + 2.12 (2016-04-02) fix typo in 2.11 PSD fix that caused crashes + 2.11 (2016-04-02) allocate large structures on the stack + remove white matting for transparent PSD + fix reported channel count for PNG & BMP + re-enable SSE2 in non-gcc 64-bit + support RGB-formatted JPEG + read 16-bit PNGs (only as 8-bit) + 2.10 (2016-01-22) avoid warning introduced in 2.09 by STBI_REALLOC_SIZED + 2.09 (2016-01-16) allow comments in PNM files + 16-bit-per-pixel TGA (not bit-per-component) + info() for TGA could break due to .hdr handling + info() for BMP to shares code instead of sloppy parse + can use STBI_REALLOC_SIZED if allocator doesn't support realloc + code cleanup + 2.08 (2015-09-13) fix to 2.07 cleanup, reading RGB PSD as RGBA + 2.07 (2015-09-13) fix compiler warnings + partial animated GIF support + limited 16-bpc PSD support + #ifdef unused functions + bug with < 92 byte PIC,PNM,HDR,TGA + 2.06 (2015-04-19) fix bug where PSD returns wrong '*comp' value + 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning + 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit + 2.03 (2015-04-12) extra corruption checking (mmozeiko) + stbi_set_flip_vertically_on_load (nguillemot) + fix NEON support; fix mingw support + 2.02 (2015-01-19) fix incorrect assert, fix warning + 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2 + 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG + 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg) + progressive JPEG (stb) + PGM/PPM support (Ken Miller) + STBI_MALLOC,STBI_REALLOC,STBI_FREE + GIF bugfix -- seemingly never worked + STBI_NO_*, STBI_ONLY_* + 1.48 (2014-12-14) fix incorrectly-named assert() + 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb) + optimize PNG (ryg) + fix bug in interlaced PNG with user-specified channel count (stb) + 1.46 (2014-08-26) + fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG + 1.45 (2014-08-16) + fix MSVC-ARM internal compiler error by wrapping malloc + 1.44 (2014-08-07) + various warning fixes from Ronny Chevalier + 1.43 (2014-07-15) + fix MSVC-only compiler problem in code changed in 1.42 + 1.42 (2014-07-09) + don't define _CRT_SECURE_NO_WARNINGS (affects user code) + fixes to stbi__cleanup_jpeg path + added STBI_ASSERT to avoid requiring assert.h + 1.41 (2014-06-25) + fix search&replace from 1.36 that messed up comments/error messages + 1.40 (2014-06-22) + fix gcc struct-initialization warning + 1.39 (2014-06-15) + fix to TGA optimization when req_comp != number of components in TGA; + fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite) + add support for BMP version 5 (more ignored fields) + 1.38 (2014-06-06) + suppress MSVC warnings on integer casts truncating values + fix accidental rename of 'skip' field of I/O + 1.37 (2014-06-04) + remove duplicate typedef + 1.36 (2014-06-03) + convert to header file single-file library + if de-iphone isn't set, load iphone images color-swapped instead of returning NULL + 1.35 (2014-05-27) + various warnings + fix broken STBI_SIMD path + fix bug where stbi_load_from_file no longer left file pointer in correct place + fix broken non-easy path for 32-bit BMP (possibly never used) + TGA optimization by Arseny Kapoulkine + 1.34 (unknown) + use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case + 1.33 (2011-07-14) + make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements + 1.32 (2011-07-13) + support for "info" function for all supported filetypes (SpartanJ) + 1.31 (2011-06-20) + a few more leak fixes, bug in PNG handling (SpartanJ) + 1.30 (2011-06-11) + added ability to load files via callbacks to accomidate custom input streams (Ben Wenger) + removed deprecated format-specific test/load functions + removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway + error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha) + fix inefficiency in decoding 32-bit BMP (David Woo) + 1.29 (2010-08-16) + various warning fixes from Aurelien Pocheville + 1.28 (2010-08-01) + fix bug in GIF palette transparency (SpartanJ) + 1.27 (2010-08-01) + cast-to-stbi_uc to fix warnings + 1.26 (2010-07-24) + fix bug in file buffering for PNG reported by SpartanJ + 1.25 (2010-07-17) + refix trans_data warning (Won Chun) + 1.24 (2010-07-12) + perf improvements reading from files on platforms with lock-heavy fgetc() + minor perf improvements for jpeg + deprecated type-specific functions so we'll get feedback if they're needed + attempt to fix trans_data warning (Won Chun) + 1.23 fixed bug in iPhone support + 1.22 (2010-07-10) + removed image *writing* support + stbi_info support from Jetro Lauha + GIF support from Jean-Marc Lienher + iPhone PNG-extensions from James Brown + warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva) + 1.21 fix use of 'stbi_uc' in header (reported by jon blow) + 1.20 added support for Softimage PIC, by Tom Seddon + 1.19 bug in interlaced PNG corruption check (found by ryg) + 1.18 (2008-08-02) + fix a threading bug (local mutable static) + 1.17 support interlaced PNG + 1.16 major bugfix - stbi__convert_format converted one too many pixels + 1.15 initialize some fields for thread safety + 1.14 fix threadsafe conversion bug + header-file-only version (#define STBI_HEADER_FILE_ONLY before including) + 1.13 threadsafe + 1.12 const qualifiers in the API + 1.11 Support installable IDCT, colorspace conversion routines + 1.10 Fixes for 64-bit (don't use "unsigned long") + optimized upsampling by Fabian "ryg" Giesen + 1.09 Fix format-conversion for PSD code (bad global variables!) + 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz + 1.07 attempt to fix C++ warning/errors again + 1.06 attempt to fix C++ warning/errors again + 1.05 fix TGA loading to return correct *comp and use good luminance calc + 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free + 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR + 1.02 support for (subset of) HDR files, float interface for preferred access to them + 1.01 fix bug: possible bug in handling right-side up bmps... not sure + fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all + 1.00 interface to zlib that skips zlib header + 0.99 correct handling of alpha in palette + 0.98 TGA loader by lonesock; dynamically add loaders (untested) + 0.97 jpeg errors on too large a file; also catch another malloc failure + 0.96 fix detection of invalid v value - particleman@mollyrocket forum + 0.95 during header scan, seek to markers in case of padding + 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same + 0.93 handle jpegtran output; verbose errors + 0.92 read 4,8,16,24,32-bit BMP files of several formats + 0.91 output 24-bit Windows 3.0 BMP files + 0.90 fix a few more warnings; bump version number to approach 1.0 + 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd + 0.60 fix compiling as c++ + 0.59 fix warnings: merge Dave Moore's -Wall fixes + 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian + 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available + 0.56 fix bug: zlib uncompressed mode len vs. nlen + 0.55 fix bug: restart_interval not initialized to 0 + 0.54 allow NULL for 'int *comp' + 0.53 fix bug in png 3->4; speedup png decoding + 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments + 0.51 obey req_comp requests, 1-component jpegs return as 1-component, + on 'test' only check type, not whether we support this variant + 0.50 (2006-11-19) + first released version +*/ + + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ diff --git a/Libs/AST/CMakeLists.txt b/Libs/AST/CMakeLists.txt index 23829d36..df09e114 100644 --- a/Libs/AST/CMakeLists.txt +++ b/Libs/AST/CMakeLists.txt @@ -1,16 +1,16 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftAST STATIC) -target_include_directories(RiftAST PUBLIC Include) +add_library(RiftASTLib STATIC) +target_include_directories(RiftASTLib PUBLIC Include) file(GLOB_RECURSE AST_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) -target_sources(RiftAST PRIVATE ${AST_SOURCE_FILES}) +target_sources(RiftASTLib PRIVATE ${AST_SOURCE_FILES}) -target_link_libraries(RiftAST PUBLIC +target_link_libraries(RiftASTLib PUBLIC Pipe Taskflow - RiftBindingNative + RiftBindingNativeLib ) -rift_module(RiftAST) -set_target_properties (RiftAST PROPERTIES FOLDER Rift) +rift_module(RiftASTLib) +set_target_properties (RiftASTLib PROPERTIES FOLDER Rift) diff --git a/Libs/AST/Include/AST/Components/CDeclClass.h b/Libs/AST/Include/AST/Components/CDeclClass.h deleted file mode 100644 index 679f93f2..00000000 --- a/Libs/AST/Include/AST/Components/CDeclClass.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclRecord.h" - - -namespace rift::AST -{ - struct CDeclClass : public CDeclRecord - { - STRUCT(CDeclClass, CDeclRecord) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclFunction.h b/Libs/AST/Include/AST/Components/CDeclFunction.h deleted file mode 100644 index 5cbcfd59..00000000 --- a/Libs/AST/Include/AST/Components/CDeclFunction.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclaration.h" - - -namespace rift::AST -{ - struct CDeclFunction : public CDeclaration - { - STRUCT(CDeclFunction, CDeclaration) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclNative.h b/Libs/AST/Include/AST/Components/CDeclNative.h deleted file mode 100644 index 257a0a79..00000000 --- a/Libs/AST/Include/AST/Components/CDeclNative.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclRecord.h" - - -namespace rift::AST -{ - struct CDeclNative : public CDeclRecord - { - STRUCT(CDeclNative, CDeclRecord) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclRecord.h b/Libs/AST/Include/AST/Components/CDeclRecord.h deleted file mode 100644 index 39d93aec..00000000 --- a/Libs/AST/Include/AST/Components/CDeclRecord.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclaration.h" - - -namespace rift::AST -{ - struct CDeclRecord : public CDeclaration - { - STRUCT(CDeclRecord, CDeclaration) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclStatic.h b/Libs/AST/Include/AST/Components/CDeclStatic.h deleted file mode 100644 index 55f6523c..00000000 --- a/Libs/AST/Include/AST/Components/CDeclStatic.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclaration.h" - - -namespace rift::AST -{ - struct CDeclStatic : public CDeclaration - { - STRUCT(CDeclStatic, CDeclaration) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclStruct.h b/Libs/AST/Include/AST/Components/CDeclStruct.h deleted file mode 100644 index 341edc82..00000000 --- a/Libs/AST/Include/AST/Components/CDeclStruct.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclRecord.h" - - -namespace rift::AST -{ - struct CDeclStruct : public CDeclRecord - { - STRUCT(CDeclStruct, CDeclRecord, ) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclType.h b/Libs/AST/Include/AST/Components/CDeclType.h deleted file mode 100644 index 17da5c03..00000000 --- a/Libs/AST/Include/AST/Components/CDeclType.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CDeclType : public p::Struct - { - STRUCT(CDeclType, p::Struct) - - PROP(typeId) - p::Tag typeId; - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclVariable.h b/Libs/AST/Include/AST/Components/CDeclVariable.h deleted file mode 100644 index 1c45013c..00000000 --- a/Libs/AST/Include/AST/Components/CDeclVariable.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CDeclaration.h" -#include "AST/Id.h" - -#include - - -namespace rift::AST -{ - struct CDeclVariable : public CDeclaration - { - STRUCT(CDeclVariable, CDeclaration) - - PROP(typeId, p::Prop_NotSerialized) - Id typeId = NoId; - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CDeclaration.h b/Libs/AST/Include/AST/Components/CDeclaration.h deleted file mode 100644 index 0d4c5b48..00000000 --- a/Libs/AST/Include/AST/Components/CDeclaration.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CDeclaration : public p::Struct - { - STRUCT(CDeclaration, p::Struct) - }; - -} // namespace rift::AST - -namespace std -{ - template T> - struct is_empty - { - static constexpr bool value = false; - }; -} // namespace std diff --git a/Libs/AST/Include/AST/Components/CExprBinaryOperator.h b/Libs/AST/Include/AST/Components/CExprBinaryOperator.h deleted file mode 100644 index 1d5725f1..00000000 --- a/Libs/AST/Include/AST/Components/CExprBinaryOperator.h +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include - - -namespace rift::AST -{ - using namespace p::core; - - - enum class BinaryOperatorType : u8 - { - // Mathematic - Add, // + - Sub, // - - Mul, // * - Div, // / - Mod, // % - - // Comparison - Equal, // == - NotEqual, // != - Greater, // > - Less, // < - GreaterOrEqual, // >= - LessOrEqual, // <= - - // Logical - And, // && - Or, // || - BitAnd, // & - BitOr, // | - Xor // ^ - }; -} // namespace rift::AST -ENUM(rift::AST::BinaryOperatorType) - - -namespace rift::AST -{ - struct CExprBinaryOperator : public CExpression - { - STRUCT(CExprBinaryOperator, CExpression) - - PROP(type) - BinaryOperatorType type = BinaryOperatorType::Add; - - - CExprBinaryOperator() = default; - CExprBinaryOperator(BinaryOperatorType type) : type{type} {} - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprCall.h b/Libs/AST/Include/AST/Components/CExprCall.h deleted file mode 100644 index 2ceda851..00000000 --- a/Libs/AST/Include/AST/Components/CExprCall.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CExpression.h" -#include "AST/Components/CNamespace.h" -#include "AST/Id.h" - -#include -#include - - -namespace rift::AST -{ - struct CExprCall : public CExpression - { - STRUCT(CExprCall, CExpression) - - PROP(function) - Namespace function; - }; - - inline void Read(p::Reader& ct, CExprCall& val) - { - ct.Serialize(val.function); - } - inline void Write(p::Writer& ct, const CExprCall& val) - { - ct.Serialize(val.function); - } - - - // Data pointing to the id of the function from CExprCall's type and function names - struct CExprCallId : public CExpression - { - STRUCT(CExprCallId, CExpression, p::Struct_NotSerialized) - - // Id pointing to the function declaration - PROP(functionId) - Id functionId = NoId; - - - CExprCallId(Id functionId = NoId) : functionId{functionId} {} - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprDeclRef.h b/Libs/AST/Include/AST/Components/CExprDeclRef.h deleted file mode 100644 index 5a32c917..00000000 --- a/Libs/AST/Include/AST/Components/CExprDeclRef.h +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CExpression.h" - - -namespace rift::AST -{ - struct CExprDeclRef : public CExpression - { - STRUCT(CExprDeclRef, CExpression) - - PROP(ownerName) - p::Tag ownerName; - - PROP(name) - p::Tag name; - }; - - struct CExprDeclRefId : public CExpression - { - STRUCT(CExprDeclRefId, CExpression) - - PROP(declarationId) - Id declarationId; - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprInputs.h b/Libs/AST/Include/AST/Components/CExprInputs.h deleted file mode 100644 index 03107002..00000000 --- a/Libs/AST/Include/AST/Components/CExprInputs.h +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include -#include - - -namespace rift::AST -{ - struct ExprOutput : public p::Struct - { - STRUCT(ExprOutput, p::Struct) - - PROP(nodeId) - AST::Id nodeId = AST::NoId; - - PROP(pinId) - AST::Id pinId = AST::NoId; - - - ExprOutput() = default; - - bool IsNone() const - { - return p::IsNone(nodeId) || p::IsNone(pinId); - } - }; - - struct CExprInputs : public p::Struct - { - STRUCT(CExprInputs, p::Struct) - - PROP(linkedOutputs) - p::TArray linkedOutputs; - - PROP(pinIds) - p::TArray pinIds; - - - CExprInputs& Add(AST::Id pinId) - { - linkedOutputs.Add(); - pinIds.Add(pinId); - return *this; - } - - CExprInputs& Insert(p::i32 index, AST::Id pinId) - { - pinIds.Insert(index, pinId); - linkedOutputs.Insert(index); - return *this; - } - - CExprInputs& Swap(p::i32 firstIndex, p::i32 secondIndex) - { - pinIds.Swap(firstIndex, secondIndex); - linkedOutputs.Swap(firstIndex, secondIndex); - return *this; - } - - void Resize(p::i32 count) - { - linkedOutputs.Resize(count); - pinIds.Resize(count, AST::NoId); - } - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprOutputs.h b/Libs/AST/Include/AST/Components/CExprOutputs.h deleted file mode 100644 index 46ec5976..00000000 --- a/Libs/AST/Include/AST/Components/CExprOutputs.h +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include -#include - - -namespace rift::AST -{ - struct ExprInput : public p::Struct - { - STRUCT(ExprInput, p::Struct) - - PROP(nodeId) - AST::Id nodeId = AST::NoId; - - PROP(pinId) - AST::Id pinId = AST::NoId; - - - ExprInput() = default; - - bool IsNone() const - { - return p::IsNone(nodeId) || p::IsNone(pinId); - } - }; - - struct CExprOutputs : public p::Struct - { - STRUCT(CExprOutputs, p::Struct) - - PROP(pinIds) - p::TArray pinIds; - - - CExprOutputs() {} - CExprOutputs(AST::Id pinId) - { - Add(pinId); - } - - CExprOutputs& Add(AST::Id pinId) - { - pinIds.Add(pinId); - return *this; - } - - CExprOutputs& Insert(p::i32 index, AST::Id pinId) - { - pinIds.Insert(index, pinId); - return *this; - } - - CExprOutputs& Swap(p::i32 firstIndex, p::i32 secondIndex) - { - pinIds.Swap(firstIndex, secondIndex); - return *this; - } - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprType.h b/Libs/AST/Include/AST/Components/CExprType.h deleted file mode 100644 index 9c6245af..00000000 --- a/Libs/AST/Include/AST/Components/CExprType.h +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CNamespace.h" -#include "AST/Id.h" - -#include - - -namespace rift::AST -{ - enum class TypeMode - { - Value, - Pointer, - PointerToPointer - }; -} // namespace rift::AST -ENUM(rift::AST::TypeMode) - - -namespace rift::AST -{ - struct CExprType : public p::Struct - { - STRUCT(CExprType, p::Struct) - - PROP(type) - AST::Namespace type; - - PROP(mode) - TypeMode mode = TypeMode::Value; - }; - - static void Read(p::Reader& ct, CExprType& val) - { - ct.Serialize(val.type); - } - static void Write(p::Writer& ct, const CExprType& val) - { - ct.Serialize(val.type); - } - - - struct CExprTypeId : public p::Struct - { - STRUCT(CExprTypeId, p::Struct) - - PROP(id, p::Prop_NotSerialized) - AST::Id id = AST::NoId; - - PROP(mode) - TypeMode mode = TypeMode::Value; - }; - -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExprUnaryOperator.h b/Libs/AST/Include/AST/Components/CExprUnaryOperator.h deleted file mode 100644 index bc28eb11..00000000 --- a/Libs/AST/Include/AST/Components/CExprUnaryOperator.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include - - -namespace rift::AST -{ - enum class UnaryOperatorType : p::u8 - { - Not, // ! - Negation, // - - Increment, // ++ - Decrement, // -- - BitNot, // ~ - }; -} // namespace rift::AST -ENUM(rift::AST::UnaryOperatorType) - - -namespace rift::AST -{ - struct CExprUnaryOperator : public CExpression - { - STRUCT(CExprUnaryOperator, CExpression) - - PROP(type) - UnaryOperatorType type = UnaryOperatorType::Not; - - - CExprUnaryOperator() = default; - CExprUnaryOperator(UnaryOperatorType type) : type{type} {} - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CExpression.h b/Libs/AST/Include/AST/Components/CExpression.h deleted file mode 100644 index 031b01ac..00000000 --- a/Libs/AST/Include/AST/Components/CExpression.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CExpression : public p::Struct - { - STRUCT(CExpression, p::Struct) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CFileRef.h b/Libs/AST/Include/AST/Components/CFileRef.h index a75d6452..b67c9699 100644 --- a/Libs/AST/Include/AST/Components/CFileRef.h +++ b/Libs/AST/Include/AST/Components/CFileRef.h @@ -1,27 +1,27 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include #include -#include +#include -namespace rift::AST +namespace rift::ast { /** * This component points an AST node to a file. * Some examples are Class, p::Struct and Function Library declarations pointing to their * files */ - struct CFileRef : public p::Struct + struct CFileRef { - STRUCT(CFileRef, p::Struct, p::Struct_NotSerialized) + P_STRUCT(CFileRef, p::TF_NotSerialized) - PROP(path) + P_PROP(path) p::String path; CFileRef() {} CFileRef(p::StringView path) : path{path} {} }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/CLiteral.h b/Libs/AST/Include/AST/Components/CLiteral.h deleted file mode 100644 index 76359982..00000000 --- a/Libs/AST/Include/AST/Components/CLiteral.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CLiteral : public p::Struct - { - STRUCT(CLiteral, p::Struct) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CLiteralBool.h b/Libs/AST/Include/AST/Components/CLiteralBool.h deleted file mode 100644 index a2e5dd66..00000000 --- a/Libs/AST/Include/AST/Components/CLiteralBool.h +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CLiteral.h" - - -namespace rift::AST -{ - struct CLiteralBool : public CLiteral - { - STRUCT(CLiteralBool, CLiteral) - - PROP(value) - bool value = false; - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CLiteralFloating.h b/Libs/AST/Include/AST/Components/CLiteralFloating.h deleted file mode 100644 index 1ac88740..00000000 --- a/Libs/AST/Include/AST/Components/CLiteralFloating.h +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CLiteral.h" - -#include -#include - - -namespace rift::AST -{ - using namespace p::core; - - enum class FloatingType : u8 - { - F32 = 32, - F64 = 64 - }; -} // namespace rift::AST -ENUM(rift::AST::FloatingType) - - -namespace rift::AST -{ - struct CLiteralFloating : public CLiteral - { - STRUCT(CLiteralFloating, CLiteral) - - - PROP(value) - double value = 0.; - - PROP(type) - FloatingType type = FloatingType::F32; - - - u8 GetSize() const - { - return static_cast>(type); - } - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CLiteralIntegral.h b/Libs/AST/Include/AST/Components/CLiteralIntegral.h deleted file mode 100644 index b38e33d7..00000000 --- a/Libs/AST/Include/AST/Components/CLiteralIntegral.h +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CLiteral.h" - -#include -#include - - -namespace rift::AST -{ - using namespace p::core; - - static constexpr u8 literalUnsignedMask = 1 << 7; // Last bit marks type as unsigned - - enum class IntegralType : u8 - { - S8 = 8, - S16 = 16, - S32 = 32, - S64 = 64, - U8 = S8 | literalUnsignedMask, - U16 = S16 | literalUnsignedMask, - U32 = S32 | literalUnsignedMask, - U64 = S64 | literalUnsignedMask - }; -} // namespace rift::AST -ENUM(rift::AST::IntegralType) -template<> -struct magic_enum::customize::enum_range -{ - static constexpr int min = 0; - static constexpr int max = 256; - // static constexpr bool is_flags = true; - // (max - min) must be less than UINT16_MAX. -}; - - -namespace rift::AST -{ - struct CLiteralIntegral : public CLiteral - { - STRUCT(CLiteralIntegral, CLiteral) - - - PROP(value) - u64 value = 0; - - PROP(type) - IntegralType type = IntegralType::S32; - - - bool IsSigned() const - { - return u8(type) & literalUnsignedMask == literalUnsignedMask; - } - u8 GetSize() const - { - return u8(type) & ~literalUnsignedMask; - } - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CLiteralString.h b/Libs/AST/Include/AST/Components/CLiteralString.h deleted file mode 100644 index 965f21e7..00000000 --- a/Libs/AST/Include/AST/Components/CLiteralString.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CLiteral.h" - -#include - - -namespace rift::AST -{ - struct CLiteralString : public CLiteral - { - STRUCT(CLiteralString, CLiteral) - - PROP(value) - p::String value; - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CModule.h b/Libs/AST/Include/AST/Components/CModule.h index 71d9dc74..fe2bf980 100644 --- a/Libs/AST/Include/AST/Components/CModule.h +++ b/Libs/AST/Include/AST/Components/CModule.h @@ -1,10 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include +#include -namespace rift::AST + +namespace rift::ast { enum class RiftModuleTarget : p::u8 { @@ -12,22 +13,22 @@ namespace rift::AST Shared, Static }; -} // namespace rift::AST -ENUM(rift::AST::RiftModuleTarget) +} // namespace rift::ast +P_ENUM(rift::ast::RiftModuleTarget) -namespace rift::AST +namespace rift::ast { static constexpr p::StringView moduleFilename = "__module__.rf"; - struct CModule : public p::Struct + struct CModule { - STRUCT(CModule, p::Struct) + P_STRUCT(CModule) - PROP(target) + P_PROP(target) RiftModuleTarget target = RiftModuleTarget::Executable; - PROP(dependencies) + P_PROP(dependencies, p::PF_Edit) p::TArray dependencies; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/CNamespace.h b/Libs/AST/Include/AST/Components/CNamespace.h index 4ec43fd7..78b55066 100644 --- a/Libs/AST/Include/AST/Components/CNamespace.h +++ b/Libs/AST/Include/AST/Components/CNamespace.h @@ -1,17 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include +#include -namespace rift::AST +namespace rift::ast { - struct CNamespace : public p::Struct + struct CNamespace { - STRUCT(CNamespace, p::Struct) + P_STRUCT(CNamespace) - PROP(name); + P_PROP(name, p::PF_Edit); p::Tag name; @@ -38,9 +38,9 @@ namespace rift::AST } - struct Namespace : public p::Struct + struct Namespace { - STRUCT(Namespace, p::Struct) + P_STRUCT(Namespace) static constexpr p::i32 scopeCount = 8; p::Tag scopes[scopeCount]; // TODO: Implement Inline arrays @@ -57,7 +57,7 @@ namespace rift::AST Namespace(const p::String& value) : Namespace(p::StringView{value}) {} Namespace(std::initializer_list values) { - const p::i32 size = p::math::Min(p::i32(values.size()), scopeCount); + const p::i32 size = p::Min(p::i32(values.size()), scopeCount); for (p::i32 i = 0; i < size; ++i) { scopes[i] = *(values.begin() + i); @@ -68,7 +68,7 @@ namespace rift::AST bool IsEmpty() const; p::i32 Size() const; bool Contains(const Namespace& other) const; - p::String ToString(bool isLocal = false) const; + p::String ToString(bool isLocal = false, char separator = '.') const; p::Tag& First() { return scopes[0]; @@ -95,7 +95,7 @@ namespace rift::AST } p::Tag operator[](p::i32 index) const { - Check(index >= 0 && index < scopeCount); + P_Check(index >= 0 && index < scopeCount); return scopes[index]; } operator bool() const @@ -123,4 +123,4 @@ namespace rift::AST void Read(p::Reader& ct); void Write(p::Writer& ct) const; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/CProject.h b/Libs/AST/Include/AST/Components/CProject.h index 578eadeb..9792659e 100644 --- a/Libs/AST/Include/AST/Components/CProject.h +++ b/Libs/AST/Include/AST/Components/CProject.h @@ -1,13 +1,12 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include +#include - -namespace rift::AST +namespace rift::ast { - struct CProject : public p::Struct + struct CProject { - STRUCT(CProject, p::Struct) + P_STRUCT(CProject) }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/CStatement.h b/Libs/AST/Include/AST/Components/CStatement.h deleted file mode 100644 index ed60d700..00000000 --- a/Libs/AST/Include/AST/Components/CStatement.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CStatement : public p::Struct - { - STRUCT(CStatement, p::Struct) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CStmtFor.h b/Libs/AST/Include/AST/Components/CStmtFor.h deleted file mode 100644 index db8d4362..00000000 --- a/Libs/AST/Include/AST/Components/CStmtFor.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CStmtFor : public p::Struct - { - STRUCT(CStmtFor, p::Struct) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CStmtIf.h b/Libs/AST/Include/AST/Components/CStmtIf.h deleted file mode 100644 index 3cbf34d6..00000000 --- a/Libs/AST/Include/AST/Components/CStmtIf.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift::AST -{ - struct CStmtIf : public p::Struct - { - STRUCT(CStmtIf, p::Struct) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CStmtInput.h b/Libs/AST/Include/AST/Components/CStmtInput.h deleted file mode 100644 index e0ab9fd3..00000000 --- a/Libs/AST/Include/AST/Components/CStmtInput.h +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include - - -namespace rift::AST -{ - using namespace p; - - struct CStmtInput : public Struct - { - STRUCT(CStmtInput, Struct) - - PROP(linkOutputNode) - Id linkOutputNode = NoId; - }; - - static void Read(Reader& ct, CStmtInput& val) - { - ct.Serialize(val.linkOutputNode); - } - static void Write(Writer& ct, const CStmtInput& val) - { - ct.Serialize(val.linkOutputNode); - } -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CStmtOutputs.h b/Libs/AST/Include/AST/Components/CStmtOutputs.h deleted file mode 100644 index bd30e355..00000000 --- a/Libs/AST/Include/AST/Components/CStmtOutputs.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Id.h" - -#include -#include - - -namespace rift::AST -{ - using namespace p::core; - - - struct CStmtOutput : public p::Struct - { - STRUCT(CStmtOutput, p::Struct) - - PROP(linkInputNode) - Id linkInputNode = NoId; - }; - - - struct CStmtOutputs : public p::Struct - { - STRUCT(CStmtOutputs, p::Struct) - - // Both arrays keep the same index to the input node and the output pin - PROP(pinIds) - TArray pinIds; - PROP(linkInputNodes) - TArray linkInputNodes; - - - CStmtOutputs() = default; - CStmtOutputs(p::TArray pins) : pinIds{Move(pins)}, linkInputNodes(pinIds.Size(), NoId) - {} - }; - - static void Read(Reader& ct, CStmtOutput& val) - { - ct.Serialize(val.linkInputNode); - } - static void Write(Writer& ct, const CStmtOutput& val) - { - ct.Serialize(val.linkInputNode); - } -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/CStmtReturn.h b/Libs/AST/Include/AST/Components/CStmtReturn.h deleted file mode 100644 index 07e21fc3..00000000 --- a/Libs/AST/Include/AST/Components/CStmtReturn.h +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CExpression.h" - - -namespace rift::AST -{ - /** Represents a return expression of a function - * Return arguments are dynamically populated depending on the function this expression is - * connected to. - */ - struct CStmtReturn : public CExpression - { - STRUCT(CStmtReturn, CExpression) - }; -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Components/Declarations.h b/Libs/AST/Include/AST/Components/Declarations.h new file mode 100644 index 00000000..47be6032 --- /dev/null +++ b/Libs/AST/Include/AST/Components/Declarations.h @@ -0,0 +1,66 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + + +#include +#include + + +namespace rift::ast +{ + struct CDeclStatic + { + P_STRUCT(CDeclStatic) + }; + + + struct CDeclRecord + { + P_STRUCT(CDeclRecord) + }; + + + struct CDeclStruct : public CDeclRecord + { + using Super = CDeclRecord; + P_STRUCT(CDeclStruct) + }; + + + struct CDeclClass : public CDeclRecord + { + using Super = CDeclRecord; + P_STRUCT(CDeclClass) + }; + + + struct CDeclType + { + P_STRUCT(CDeclType) + + P_PROP(typeId) + p::Tag typeId; + }; + + + struct CDeclNative : public CDeclRecord + { + using Super = CDeclRecord; + P_STRUCT(CDeclNative) + }; + + + struct CDeclFunction + { + P_STRUCT(CDeclFunction) + }; + + + struct CDeclVariable + { + P_STRUCT(CDeclVariable) + + P_PROP(typeId, p::PF_NotSerialized) + p::Id typeId = p::NoId; + }; +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Expressions.h b/Libs/AST/Include/AST/Components/Expressions.h new file mode 100644 index 00000000..11d48195 --- /dev/null +++ b/Libs/AST/Include/AST/Components/Expressions.h @@ -0,0 +1,297 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include "AST/Components/CNamespace.h" + +#include +#include + + +namespace rift::ast +{ + enum class UnaryOperatorType : p::u8 + { + Not, // ! + Negation, // - + Increment, // ++ + Decrement, // -- + BitNot, // ~ + }; + + enum class BinaryOperatorType : p::u8 + { + // Mathematic + Add, // + + Sub, // - + Mul, // * + Div, // / + Mod, // % + + // Comparison + Equal, // == + NotEqual, // != + Greater, // > + Less, // < + GreaterOrEqual, // >= + LessOrEqual, // <= + + // Logical + And, // && + Or, // || + BitAnd, // & + BitOr, // | + Xor // ^ + }; + + enum class TypeMode + { + Value, + Pointer, + PointerToPointer + }; +} // namespace rift::ast +P_ENUM(rift::ast::UnaryOperatorType) +P_ENUM(rift::ast::BinaryOperatorType) +P_ENUM(rift::ast::TypeMode) + + +namespace rift::ast +{ + struct CExpression + { + P_STRUCT(CExpression) + }; + + + struct CExprCall : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprCall) + + P_PROP(function) + Namespace function; + }; + + + // Data pointing to the id of the function from CExprCall's type and function names + struct CExprCallId : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprCallId, p::TF_NotSerialized) + + // Id pointing to the function declaration + P_PROP(functionId) + p::Id functionId = p::NoId; + + + CExprCallId(p::Id functionId = p::NoId) : functionId{functionId} {} + }; + + + struct CExprUnaryOperator : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprUnaryOperator) + + P_PROP(type) + UnaryOperatorType type = UnaryOperatorType::Not; + + + CExprUnaryOperator() = default; + CExprUnaryOperator(UnaryOperatorType type) : type{type} {} + }; + + + struct CExprBinaryOperator : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprBinaryOperator) + + P_PROP(type) + BinaryOperatorType type = BinaryOperatorType::Add; + + + CExprBinaryOperator() = default; + CExprBinaryOperator(BinaryOperatorType type) : type{type} {} + }; + + + struct CExprDeclRef : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprDeclRef) + + P_PROP(ownerName) + p::Tag ownerName; + + P_PROP(name) + p::Tag name; + }; + + + struct CExprDeclRefId : public CExpression + { + using Super = CExpression; + P_STRUCT(CExprDeclRefId) + + P_PROP(declarationId) + p::Id declarationId = p::NoId; + }; + + + struct ExprInput + { + P_STRUCT(ExprInput) + + P_PROP(nodeId) + p::Id nodeId = p::NoId; + + P_PROP(pinId) + p::Id pinId = p::NoId; + + + ExprInput() = default; + + bool IsNone() const + { + return p::IsNone(nodeId) || p::IsNone(pinId); + } + }; + + + struct ExprOutput + { + P_STRUCT(ExprOutput) + + P_PROP(nodeId) + p::Id nodeId = p::NoId; + + P_PROP(pinId) + p::Id pinId = p::NoId; + + + ExprOutput() = default; + + bool IsNone() const + { + return p::IsNone(nodeId) || p::IsNone(pinId); + } + }; + + + struct CExprInputs + { + P_STRUCT(CExprInputs) + + P_PROP(linkedOutputs) + p::TArray linkedOutputs; + + P_PROP(pinIds) + p::TArray pinIds; + + + CExprInputs& Add(p::Id pinId) + { + linkedOutputs.Add(); + pinIds.Add(pinId); + return *this; + } + + CExprInputs& Insert(p::i32 index, p::Id pinId) + { + pinIds.Insert(index, pinId); + linkedOutputs.Insert(index); + return *this; + } + + CExprInputs& Swap(p::i32 firstIndex, p::i32 secondIndex) + { + pinIds.Swap(firstIndex, secondIndex); + linkedOutputs.Swap(firstIndex, secondIndex); + return *this; + } + + void Resize(p::i32 count) + { + linkedOutputs.Resize(count); + pinIds.Resize(count, p::NoId); + } + }; + + + struct CExprOutputs + { + P_STRUCT(CExprOutputs) + + P_PROP(pinIds) + p::TArray pinIds; + + + CExprOutputs() {} + CExprOutputs(p::Id pinId) + { + Add(pinId); + } + + CExprOutputs& Add(p::Id pinId) + { + pinIds.Add(pinId); + return *this; + } + + CExprOutputs& Insert(p::i32 index, p::Id pinId) + { + pinIds.Insert(index, pinId); + return *this; + } + + CExprOutputs& Swap(p::i32 firstIndex, p::i32 secondIndex) + { + pinIds.Swap(firstIndex, secondIndex); + return *this; + } + }; + + + struct CExprType + { + P_STRUCT(CExprType) + + P_PROP(type) + Namespace type; + + P_PROP(mode) + TypeMode mode = TypeMode::Value; + }; + + + struct CExprTypeId + { + P_STRUCT(CExprTypeId) + + P_PROP(id, p::PF_NotSerialized) + p::Id id = p::NoId; + + P_PROP(mode) + TypeMode mode = TypeMode::Value; + }; + + + static void Read(p::Reader& ct, CExprCall& val) + { + ct.Serialize(val.function); + } + static void Write(p::Writer& ct, const CExprCall& val) + { + ct.Serialize(val.function); + } + + static void Read(p::Reader& ct, CExprType& val) + { + ct.Serialize(val.type); + } + static void Write(p::Writer& ct, const CExprType& val) + { + ct.Serialize(val.type); + } +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Literals.h b/Libs/AST/Include/AST/Components/Literals.h new file mode 100644 index 00000000..9c821a53 --- /dev/null +++ b/Libs/AST/Include/AST/Components/Literals.h @@ -0,0 +1,104 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include +#include + + +namespace rift::ast +{ + enum class FloatingType : p::u8 + { + F32 = 32, + F64 = 64 + }; + + + static constexpr p::u8 literalUnsignedMask = 1 << 7; // Last bit marks type as unsigned + enum class IntegralType : p::u8 + { + S8 = 8, + S16 = 16, + S32 = 32, + S64 = 64, + U8 = S8 | literalUnsignedMask, + U16 = S16 | literalUnsignedMask, + U32 = S32 | literalUnsignedMask, + U64 = S64 | literalUnsignedMask + }; +} // namespace rift::ast + +P_ENUM(rift::ast::FloatingType) +P_ENUM(rift::ast::IntegralType) + +template<> +struct magic_enum::customize::enum_range +{ + static constexpr int min = 0; + static constexpr int max = 256; + // static constexpr bool is_flags = true; + // (max - min) must be less than UINT16_MAX. +}; + + +namespace rift::ast +{ + struct CLiteralBool + { + P_STRUCT(CLiteralBool) + + P_PROP(value) + bool value = false; + }; + + + struct CLiteralFloating + { + P_STRUCT(CLiteralFloating) + + + P_PROP(value) + double value = 0.; + + P_PROP(type) + FloatingType type = FloatingType::F32; + + + p::u8 GetSize() const + { + return static_cast>(type); + } + }; + + + struct CLiteralIntegral + { + P_STRUCT(CLiteralIntegral) + + + P_PROP(value) + p::u64 value = 0; + + P_PROP(type) + IntegralType type = IntegralType::S32; + + + bool IsSigned() const + { + return p::u8(type) & literalUnsignedMask == literalUnsignedMask; + } + p::u8 GetSize() const + { + return p::u8(type) & ~literalUnsignedMask; + } + }; + + + struct CLiteralString + { + P_STRUCT(CLiteralString) + + P_PROP(value) + p::String value; + }; +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Statements.h b/Libs/AST/Include/AST/Components/Statements.h new file mode 100644 index 00000000..1060e858 --- /dev/null +++ b/Libs/AST/Include/AST/Components/Statements.h @@ -0,0 +1,85 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + + +#include +#include + + +namespace rift::ast +{ + struct CStmtFor + { + P_STRUCT(CStmtFor) + }; + + + struct CStmtIf + { + P_STRUCT(CStmtIf) + }; + + + struct CStmtInput + { + P_STRUCT(CStmtInput) + + P_PROP(linkOutputNode) + p::Id linkOutputNode = p::NoId; + }; + + + struct CStmtOutput + { + P_STRUCT(CStmtOutput) + + P_PROP(linkInputNode) + p::Id linkInputNode = p::NoId; + }; + + + struct CStmtOutputs + { + P_STRUCT(CStmtOutputs) + + // Both arrays keep the same index to the input node and the output pin + P_PROP(pinIds) + p::TArray pinIds; + P_PROP(linkInputNodes) + p::TArray linkInputNodes; + + + CStmtOutputs() = default; + CStmtOutputs(p::TArray pins) + : pinIds{Move(pins)}, linkInputNodes(pinIds.Size(), p::NoId) + {} + }; + + + /** Represents a return expression of a function + * Return arguments are dynamically populated depending on the function this expression is + * connected to. + */ + struct CStmtReturn + { + P_STRUCT(CStmtReturn) + }; + + + static void Read(p::Reader& ct, CStmtInput& val) + { + ct.Serialize(val.linkOutputNode); + } + static void Write(p::Writer& ct, const CStmtInput& val) + { + ct.Serialize(val.linkOutputNode); + } + static void Read(p::Reader& ct, CStmtOutput& val) + { + ct.Serialize(val.linkInputNode); + } + static void Write(p::Writer& ct, const CStmtOutput& val) + { + ct.Serialize(val.linkInputNode); + } +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Tags/CChanged.h b/Libs/AST/Include/AST/Components/Tags/CChanged.h index 802f8977..4f59bed8 100644 --- a/Libs/AST/Include/AST/Components/Tags/CChanged.h +++ b/Libs/AST/Include/AST/Components/Tags/CChanged.h @@ -1,15 +1,14 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include +#include - -namespace rift::AST +namespace rift::ast { // Asigned to entities that have been modified during the last frame // Gets cleared after one frame - struct CChanged : public p::Struct + struct CChanged { - STRUCT(CChanged, p::Struct, p::Struct_NotSerialized) + P_STRUCT(CChanged, p::TF_NotSerialized) }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Tags/CDirty.h b/Libs/AST/Include/AST/Components/Tags/CDirty.h index 3179a868..56034557 100644 --- a/Libs/AST/Include/AST/Components/Tags/CDirty.h +++ b/Libs/AST/Include/AST/Components/Tags/CDirty.h @@ -1,20 +1,20 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CExprCall.h" #include "AST/Components/CFileRef.h" +#include "AST/Components/Expressions.h" -#include +#include -namespace rift::AST +namespace rift::ast { // Dirty tags are cleaned manually by the respective systems. CChanged instead gets cleared // after one frame template - struct TDirty : public p::Struct + struct TDirty { - STRUCT(TDirty, p::Struct, p::Struct_NotSerialized) + P_STRUCT(TDirty, p::TF_NotSerialized) }; using CDirty = TDirty; @@ -24,4 +24,4 @@ namespace rift::AST // Marks a type as dirty, meaning is has been modified using CCallDirty = TDirty; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Tags/CInvalid.h b/Libs/AST/Include/AST/Components/Tags/CInvalid.h index 5c1d7753..fa963f7d 100644 --- a/Libs/AST/Include/AST/Components/Tags/CInvalid.h +++ b/Libs/AST/Include/AST/Components/Tags/CInvalid.h @@ -1,13 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include +#include -namespace rift::AST +namespace rift::ast { - struct CInvalid : public p::Struct + struct CInvalid { - STRUCT(CInvalid, p::Struct) + P_STRUCT(CInvalid) }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Components/Tags/CPendingLoad.h b/Libs/AST/Include/AST/Components/Tags/CPendingLoad.h index 3deba132..52be4ba4 100644 --- a/Libs/AST/Include/AST/Components/Tags/CPendingLoad.h +++ b/Libs/AST/Include/AST/Components/Tags/CPendingLoad.h @@ -1,13 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include +#include namespace rift { - struct CPendingLoad : public p::Struct + struct CPendingLoad { - STRUCT(CPendingLoad, p::Struct) + P_STRUCT(CPendingLoad) }; } // namespace rift diff --git a/Libs/AST/Include/AST/Components/Views/CNodePosition.h b/Libs/AST/Include/AST/Components/Views/CNodePosition.h index 8ee8d7d1..678aeb32 100644 --- a/Libs/AST/Include/AST/Components/Views/CNodePosition.h +++ b/Libs/AST/Include/AST/Components/Views/CNodePosition.h @@ -1,22 +1,25 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include + +#include +#include namespace rift { - struct CNodePosition : public p::Struct + struct CNodePosition { - STRUCT(CNodePosition, p::Struct) + P_STRUCT(CNodePosition) - PROP(position) + P_PROP(position) p::v2 position; CNodePosition() = default; CNodePosition(p::v2 position) : position{position} {} }; + + static void Read(p::Reader& ct, CNodePosition& val) { ct.Serialize(val.position); diff --git a/Libs/AST/Include/AST/Id.h b/Libs/AST/Include/AST/Id.h index a5608684..3fed6daf 100644 --- a/Libs/AST/Include/AST/Id.h +++ b/Libs/AST/Include/AST/Id.h @@ -1,19 +1,15 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include -#include -#include -#include +#include +#include -namespace rift::AST +namespace rift::ast { - using namespace p; using Id = p::Id; constexpr Id NoId = p::NoId; using CParent = p::CParent; using CChild = p::CChild; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Statics/SLoadQueue.h b/Libs/AST/Include/AST/Statics/SLoadQueue.h index 549774c1..2c6a4d40 100644 --- a/Libs/AST/Include/AST/Statics/SLoadQueue.h +++ b/Libs/AST/Include/AST/Statics/SLoadQueue.h @@ -1,19 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" -#include +#include -namespace rift::AST +namespace rift::ast { // Keeps a list of entities to load from disk - struct SLoadQueue : public p::Struct + struct SLoadQueue { - STRUCT(SLoadQueue, p::Struct) + P_STRUCT(SLoadQueue) - TArray pendingSyncLoad; - TArray pendingAsyncLoad; + p::TArray pendingSyncLoad; + p::TArray pendingAsyncLoad; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Statics/SModules.h b/Libs/AST/Include/AST/Statics/SModules.h index 8e7eade5..144ce7c0 100644 --- a/Libs/AST/Include/AST/Statics/SModules.h +++ b/Libs/AST/Include/AST/Statics/SModules.h @@ -1,17 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" -#include +#include -namespace rift::AST +namespace rift::ast { - struct SModules : public p::Struct + struct SModules { - STRUCT(SModules, p::Struct) + P_STRUCT(SModules) - p::TMap modulesByPath; + p::TMap modulesByPath; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Statics/SStringLoad.h b/Libs/AST/Include/AST/Statics/SStringLoad.h index 40ec97e7..ab8921e0 100644 --- a/Libs/AST/Include/AST/Statics/SStringLoad.h +++ b/Libs/AST/Include/AST/Statics/SStringLoad.h @@ -1,26 +1,24 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" #include #include -#include +#include -namespace rift::AST +namespace rift::ast { - using namespace p::core; - // Contains loaded string data from disk - struct SStringLoad : public Struct + struct SStringLoad { - STRUCT(SStringLoad, Struct) + P_STRUCT(SStringLoad) // This buffers are always in sync with size // They bind by array index an Id, path and loaded string - TArray entities; - TArray paths; - TArray strings; + p::TArray entities; + p::TArray paths; + p::TArray strings; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Statics/STypes.h b/Libs/AST/Include/AST/Statics/STypes.h index f05e953d..2fc60fec 100644 --- a/Libs/AST/Include/AST/Statics/STypes.h +++ b/Libs/AST/Include/AST/Statics/STypes.h @@ -1,23 +1,21 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" #include -#include +#include -namespace rift::AST +namespace rift::ast { - using namespace p::core; - - struct STypes : public Struct + struct STypes { - STRUCT(STypes, Struct) + P_STRUCT(STypes) - TMap typesByName; + p::TMap typesByName; // TODO: Use StringView to point to CFileRef component's path. // Current TMap lookup of stringviews seems unconsistent - TMap typesByPath; + p::TMap typesByPath; }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Systems/FunctionsSystem.h b/Libs/AST/Include/AST/Systems/FunctionsSystem.h index 5b1abd14..acc26e9d 100644 --- a/Libs/AST/Include/AST/Systems/FunctionsSystem.h +++ b/Libs/AST/Include/AST/Systems/FunctionsSystem.h @@ -1,24 +1,22 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclFunction.h" -#include "AST/Components/CExprCall.h" -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" #include "AST/Components/CNamespace.h" +#include "AST/Components/Declarations.h" +#include "AST/Components/Expressions.h" #include "AST/Components/Tags/CInvalid.h" #include "AST/Tree.h" -#include -#include +#include +#include -namespace rift::AST +namespace rift::ast { struct Tree; } -namespace rift::AST::FunctionsSystem +namespace rift::ast::FunctionsSystem { struct CTmpInvalidKeep {}; @@ -37,4 +35,4 @@ namespace rift::AST::FunctionsSystem p::TWrite, p::TWrite, p::TWrite>; void RemoveInvalidDisconnectedArgs(InvalidDisconnectedPinAccess access); void ClearAddedTags(Tree& ast); -} // namespace rift::AST::FunctionsSystem +} // namespace rift::ast::FunctionsSystem diff --git a/Libs/AST/Include/AST/Systems/LoadSystem.h b/Libs/AST/Include/AST/Systems/LoadSystem.h index 99f7c698..d1453319 100644 --- a/Libs/AST/Include/AST/Systems/LoadSystem.h +++ b/Libs/AST/Include/AST/Systems/LoadSystem.h @@ -1,19 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Components/CFileRef.h" #include "AST/Tree.h" -#include -#include +#include +#include -namespace rift::AST +namespace rift::ast { struct Tree; } -namespace rift::AST::LoadSystem +namespace rift::ast::LoadSystem { struct ModuleTypePaths { @@ -30,18 +30,20 @@ namespace rift::AST::LoadSystem /** * @param paths of all currently unloaded modules */ - void ScanSubmodules(Tree& ast, TArray& paths); + void ScanSubmodules(Tree& ast, p::TArray& paths); /** * @param paths of all currently unloaded types */ - void ScanTypes(Tree& ast, TArray& pathsByModule); + void ScanTypes(Tree& ast, p::TArray& pathsByModule); - void CreateModulesFromPaths(Tree& ast, TArray& paths, TArray& ids); - void CreateTypesFromPaths(Tree& ast, TView pathsByModule, TArray& ids); + void CreateModulesFromPaths(Tree& ast, p::TArray& paths, p::TArray& ids); + void CreateTypesFromPaths( + Tree& ast, p::TView pathsByModule, p::TArray& ids); - void LoadFileStrings(TAccessRef access, TView nodes, TArray& strings); + void LoadFileStrings( + p::TAccessRef access, p::TView nodes, p::TArray& strings); - void DeserializeModules(Tree& ast, TView moduleIds, TView strings); - void DeserializeTypes(Tree& ast, TView typeIds, TView strings); + void DeserializeModules(Tree& ast, p::TView moduleIds, p::TView strings); + void DeserializeTypes(Tree& ast, p::TView typeIds, p::TView strings); -} // namespace rift::AST::LoadSystem +} // namespace rift::ast::LoadSystem diff --git a/Libs/AST/Include/AST/Systems/TransactionSystem.h b/Libs/AST/Include/AST/Systems/TransactionSystem.h index f5e9d167..51f7efa9 100644 --- a/Libs/AST/Include/AST/Systems/TransactionSystem.h +++ b/Libs/AST/Include/AST/Systems/TransactionSystem.h @@ -1,17 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Tree.h" -namespace rift::AST +namespace rift::ast { struct Tree; } -namespace rift::AST::TransactionSystem +namespace rift::ast::TransactionSystem { void Init(Tree& ast); void ClearTags(Tree& ast); -} // namespace rift::AST::TransactionSystem +} // namespace rift::ast::TransactionSystem diff --git a/Libs/AST/Include/AST/Systems/TypeSystem.h b/Libs/AST/Include/AST/Systems/TypeSystem.h index 09533dd5..905b1825 100644 --- a/Libs/AST/Include/AST/Systems/TypeSystem.h +++ b/Libs/AST/Include/AST/Systems/TypeSystem.h @@ -1,39 +1,30 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclType.h" -#include "AST/Components/CDeclVariable.h" -#include "AST/Components/CExprBinaryOperator.h" -#include "AST/Components/CExprDeclRef.h" -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" -#include "AST/Components/CExprType.h" -#include "AST/Components/CExprUnaryOperator.h" +#include "AST/Components/Declarations.h" +#include "AST/Components/Expressions.h" #include "AST/Components/Tags/CChanged.h" -#include +#include -namespace rift::AST +namespace rift::ast { struct Tree; } -namespace rift::AST::TypeSystem +namespace rift::ast::TypeSystem { - using namespace p; - - void Init(Tree& ast); using PropagateVariableTypesAccess = - TAccessRef>; + p::TAccessRef>; void PropagateVariableTypes(PropagateVariableTypesAccess access); - using PropagateExpressionTypesAccess = TAccessRef, CExprUnaryOperator, CExprBinaryOperator, CParent>; + using PropagateExpressionTypesAccess = p::TAccessRef, CExprUnaryOperator, CExprBinaryOperator, p::CParent>; void PropagateExpressionTypes(PropagateExpressionTypesAccess access); void ResolveExprTypeIds( - TAccessRef, CExprType, CNamespace, CParent, CChild> access); -} // namespace rift::AST::TypeSystem + p::TAccessRef, CExprType, CNamespace, p::CParent, p::CChild> access); +} // namespace rift::ast::TypeSystem diff --git a/Libs/AST/Include/AST/Tree.h b/Libs/AST/Include/AST/Tree.h index 28b08617..6102bf95 100644 --- a/Libs/AST/Include/AST/Tree.h +++ b/Libs/AST/Include/AST/Tree.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" @@ -6,26 +6,26 @@ #include #include -#include +#include -namespace rift::AST +namespace rift::ast { struct NativeTypeIds { - AST::Id voidId = AST::NoId; - AST::Id boolId = AST::NoId; - AST::Id floatId = AST::NoId; - AST::Id doubleId = AST::NoId; - AST::Id u8Id = AST::NoId; - AST::Id i8Id = AST::NoId; - AST::Id u16Id = AST::NoId; - AST::Id i16Id = AST::NoId; - AST::Id u32Id = AST::NoId; - AST::Id i32Id = AST::NoId; - AST::Id u64Id = AST::NoId; - AST::Id i64Id = AST::NoId; - AST::Id stringId = AST::NoId; + ast::Id voidId = ast::NoId; + ast::Id boolId = ast::NoId; + ast::Id floatId = ast::NoId; + ast::Id doubleId = ast::NoId; + ast::Id u8Id = ast::NoId; + ast::Id i8Id = ast::NoId; + ast::Id u16Id = ast::NoId; + ast::Id i16Id = ast::NoId; + ast::Id u32Id = ast::NoId; + ast::Id i32Id = ast::NoId; + ast::Id u64Id = ast::NoId; + ast::Id i64Id = ast::NoId; + ast::Id stringId = ast::NoId; }; @@ -51,6 +51,8 @@ namespace rift::AST static const p::TBroadcast& OnInit(); + p::String DumpPools(); + private: void CopyFrom(const Tree& other); void MoveFrom(Tree&& other); @@ -66,4 +68,4 @@ namespace rift::AST (ast.AssurePool(), ...); }); } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/TypeRef.h b/Libs/AST/Include/AST/TypeRef.h index 50810d98..d44336bf 100644 --- a/Libs/AST/Include/AST/TypeRef.h +++ b/Libs/AST/Include/AST/TypeRef.h @@ -1,26 +1,26 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclType.h" +#include "AST/Components/Declarations.h" #include "AST/Tree.h" #include -namespace rift::AST +namespace rift::ast { struct TypeRef { private: Tree& ast; - AST::Id typeId = AST::NoId; + ast::Id typeId = ast::NoId; public: - TypeRef(Tree& ast, AST::Id typeId) : ast(ast), typeId(typeId) + TypeRef(Tree& ast, ast::Id typeId) : ast(ast), typeId(typeId) { if (!IsNone(typeId)) { - Ensure(ast.Has(typeId)); + P_Ensure(ast.Has(typeId)); } } @@ -33,7 +33,7 @@ namespace rift::AST return ast; } - AST::Id GetId() const + ast::Id GetId() const { return typeId; } @@ -44,7 +44,7 @@ namespace rift::AST } - operator AST::Id() const + operator ast::Id() const { return typeId; } @@ -53,4 +53,4 @@ namespace rift::AST return IsValid(); } }; -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/Expressions.h b/Libs/AST/Include/AST/Utils/Expressions.h index d74dcc1e..8f46aaed 100644 --- a/Libs/AST/Include/AST/Utils/Expressions.h +++ b/Libs/AST/Include/AST/Utils/Expressions.h @@ -1,24 +1,22 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" -#include "AST/Components/CExprType.h" +#include "AST/Components/Expressions.h" #include "AST/Components/Tags/CInvalid.h" #include "AST/Id.h" #include "AST/Tree.h" -#include -#include +#include +#include // NOTE: In expression graphs, the Link Id is the Input Pin Id -namespace rift::AST +namespace rift::ast { - bool CanConnectExpr(TAccessRef access, + bool CanConnectExpr(p::TAccessRef access, ExprOutput output, ExprInput input); - bool TryConnectExpr(TAccessRef, CExprOutputs, CExprTypeId> access, + bool TryConnectExpr(p::TAccessRef, CExprOutputs, CExprTypeId> access, ExprOutput output, ExprInput input); // Disconnects a particular link. (Note: link ids are the same as input nodes) bool DisconnectExpr(Tree& ast, ExprInput input); @@ -29,11 +27,12 @@ namespace rift::AST * @param ids * @param ignoreRoot ignore ids's inputs and outputs and only remove from children */ - void DisconnectAllExprDeep(Tree& ast, TView ids, bool ignoreRoot = false); + void DisconnectAllExprDeep(Tree& ast, p::TView ids, bool ignoreRoot = false); - bool RemoveExprInputPin(TAccessRef> access, ExprInput id); - bool RemoveExprOutputPin(TAccessRef> access, ExprOutput id); + bool RemoveExprInputPin(p::TAccessRef> access, ExprInput id); + bool RemoveExprOutputPin( + p::TAccessRef> access, ExprOutput id); - ExprInput GetExprInputFromPin(TAccessRef access, Id pinId); - ExprOutput GetExprOutputFromPin(TAccessRef access, Id pinId); -} // namespace rift::AST + ExprInput GetExprInputFromPin(p::TAccessRef access, Id pinId); + ExprOutput GetExprOutputFromPin(p::TAccessRef access, Id pinId); +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/ModuleFileIterator.h b/Libs/AST/Include/AST/Utils/ModuleFileIterator.h new file mode 100644 index 00000000..62aac452 --- /dev/null +++ b/Libs/AST/Include/AST/Utils/ModuleFileIterator.h @@ -0,0 +1,36 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include "AST/Components/CModule.h" + +#include +#include + + +namespace rift::ast +{ + class ModuleFileIterator : public p::LambdaFileIterator + { + using Super = p::LambdaFileIterator; + + public: + using Super::Super; + + explicit ModuleFileIterator(p::StringView path) + : Super(path, [](p::StringView path) { + return p::GetFilename(path) == moduleFilename; + }) + {} + }; + + + inline ModuleFileIterator begin(ModuleFileIterator it) noexcept + { + return it; + } + + inline ModuleFileIterator end(ModuleFileIterator) noexcept + { + return {}; + } +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/ModuleIterator.h b/Libs/AST/Include/AST/Utils/ModuleIterator.h deleted file mode 100644 index 568e6033..00000000 --- a/Libs/AST/Include/AST/Utils/ModuleIterator.h +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "AST/Components/CModule.h" - -#include -#include - - -namespace rift::AST -{ - class ModuleIterator : public p::LambdaFileIterator - { - using Super = p::LambdaFileIterator; - - public: - using Super::Super; - - explicit ModuleIterator(const p::Path& path) - : Super(path, [](const auto& path) { - return path.filename() == moduleFilename; - }) - {} - }; - - - inline ModuleIterator begin(ModuleIterator it) noexcept - { - return it; - } - - inline ModuleIterator end(ModuleIterator) noexcept - { - return {}; - } -} // namespace rift::AST diff --git a/Libs/AST/Include/AST/Utils/ModuleUtils.h b/Libs/AST/Include/AST/Utils/ModuleUtils.h index 22fb89ba..e22ae556 100644 --- a/Libs/AST/Include/AST/Utils/ModuleUtils.h +++ b/Libs/AST/Include/AST/Utils/ModuleUtils.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -7,21 +7,22 @@ #include "AST/Components/CProject.h" #include "AST/Tree.h" +#include #include -#include +#include -namespace rift::AST +namespace rift::ast { struct CModule; } -namespace rift::AST +namespace rift::ast { struct ModuleBinding { p::Tag id; - p::StructType* tagType = nullptr; + p::TypeId tagType; p::String displayName; bool operator<(const ModuleBinding& other) const @@ -38,39 +39,35 @@ namespace rift::AST } }; - - using namespace p::core; - using namespace p::files; - - bool CreateProject(Tree& ast, StringView path); - bool OpenProject(Tree& ast, StringView path); + bool CreateProject(Tree& ast, p::StringView path); + bool OpenProject(Tree& ast, p::StringView path); void CloseProject(Tree& ast); - Id CreateModule(Tree& ast, StringView path); + Id CreateModule(Tree& ast, p::StringView path); Id GetProjectId(p::TAccessRef access); - Tag GetProjectName(p::TAccessRef access); + p::Tag GetProjectName(p::TAccessRef access); p::StringView GetProjectPath(p::TAccessRef access); CModule* GetProjectModule(p::TAccessRef> access); bool HasProject(Tree& ast); // Resolve a module's name - Tag GetModuleName(p::TAccessRef access, Id moduleId); + p::Tag GetModuleName(p::TAccessRef access, Id moduleId); // Resolve a module's name p::StringView GetModulePath(p::TAccessRef access, Id moduleId); - void SerializeModule(AST::Tree& ast, AST::Id id, String& data); - void DeserializeModule(AST::Tree& ast, AST::Id id, const String& data); - const TBroadcast& OnReadModulePools(); - const TBroadcast& OnWriteModulePools(); + void SerializeModule(ast::Tree& ast, ast::Id id, p::String& data); + void DeserializeModule(ast::Tree& ast, ast::Id id, const p::String& data); + const p::TBroadcast& OnReadModulePools(); + const p::TBroadcast& OnWriteModulePools(); void RegisterModuleBinding(ModuleBinding binding); void UnregisterModuleBinding(p::Tag bindingId); - void AddBindingToModule(AST::Tree& ast, AST::Id id, p::Tag bindingId); - void RemoveBindingFromModule(AST::Tree& ast, AST::Id id, p::Tag bindingId); + void AddBindingToModule(ast::Tree& ast, ast::Id id, p::Tag bindingId); + void RemoveBindingFromModule(ast::Tree& ast, ast::Id id, p::Tag bindingId); const ModuleBinding* FindModuleBinding(p::Tag id); p::TView GetModuleBindings(); @@ -84,4 +81,4 @@ namespace rift::AST OnReadModulePools().Bind(components); OnWriteModulePools().Bind(components); } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/Namespaces.h b/Libs/AST/Include/AST/Utils/Namespaces.h index 40695071..80def00f 100644 --- a/Libs/AST/Include/AST/Utils/Namespaces.h +++ b/Libs/AST/Include/AST/Utils/Namespaces.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Components/CModule.h" @@ -6,12 +6,11 @@ #include "AST/Id.h" #include -#include -#include -#include +#include +#include -namespace rift::AST +namespace rift::ast { Namespace GetNamespace(p::TAccessRef access, Id id); Namespace GetParentNamespace(p::TAccessRef access, Id id); @@ -28,15 +27,15 @@ namespace rift::AST p::Tag GetName(p::TAccessRef access, Id id); p::Tag GetNameUnsafe(p::TAccessRef access, Id id); - p::String GetFullName( - p::TAccessRef access, Id id, bool localNamespace = false); -} // namespace rift::AST + p::String GetFullName(p::TAccessRef access, Id id, + bool localNamespace = false, char separator = '.'); +} // namespace rift::ast namespace p { template<> - struct TFlags : public DefaultTFlags + struct TFlags : public DefaultTFlags { enum { diff --git a/Libs/AST/Include/AST/Utils/Paths.h b/Libs/AST/Include/AST/Utils/Paths.h index 2d7254c9..38948f74 100644 --- a/Libs/AST/Include/AST/Utils/Paths.h +++ b/Libs/AST/Include/AST/Utils/Paths.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once diff --git a/Libs/AST/Include/AST/Utils/Settings.h b/Libs/AST/Include/AST/Utils/Settings.h new file mode 100644 index 00000000..26164a19 --- /dev/null +++ b/Libs/AST/Include/AST/Utils/Settings.h @@ -0,0 +1,63 @@ +// Copyright 2015-2024 Piperift - All rights reserved + +#pragma once + +#include "AST/Utils/Settings.h" +#include "Pipe/Files/Paths.h" + +#include +#include +#include +#include + + +namespace rift +{ + template + void SaveUserSettings(); + + + p::String GetUserSettingsPath(p::StringView name); + + template + T& GetUserSettings() + { + static p::TOwnPtr instance; + if (!instance) + { + instance = p::MakeOwned(); + + p::String filePath = GetUserSettingsPath(p::GetTypeName(false)); + if (!p::Exists(filePath)) + { + SaveUserSettings(); + } + else + { + p::String data; + if (p::LoadStringFile(filePath, data)) + { + p::JsonFormatReader reader{data}; + reader.GetReader().Serialize(*instance); + } + } + } + return *instance.Get(); + } + + template + void SaveUserSettings() + { + auto& instance = GetUserSettings(); + p::JsonFormatWriter writer{}; + writer.GetWriter().Serialize(instance); + + p::String filePath = GetUserSettingsPath(p::GetTypeName(false)); + p::StringView folderPath = p::GetParentPath(filePath); + if (!p::Exists(folderPath)) + { + p::CreateFolder(folderPath); + } + p::SaveStringFile(filePath, writer.ToString()); + } +} // namespace rift diff --git a/Libs/AST/Include/AST/Utils/Statements.h b/Libs/AST/Include/AST/Utils/Statements.h index 8dbac2d0..75fc658a 100644 --- a/Libs/AST/Include/AST/Utils/Statements.h +++ b/Libs/AST/Include/AST/Utils/Statements.h @@ -1,27 +1,26 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CStmtInput.h" -#include "AST/Components/CStmtOutputs.h" +#include "AST/Components/Statements.h" #include "AST/Id.h" #include "AST/Tree.h" #include "AST/Utils/Statements.h" -#include -#include +#include +#include // NOTE: In statement graphs, the Link Id is the Input Node Id -namespace rift::AST +namespace rift::ast { bool CanConnectStmt(const Tree& ast, Id outputNode, Id outputPin, Id inputNode); - bool TryConnectStmt(Tree& ast, AST::Id outputPin, AST::Id inputNode); + bool TryConnectStmt(Tree& ast, Id outputPin, Id inputNode); // Disconnects a particular link. (Note: link ids are the same as input nodes) - bool DisconnectStmtLink(Tree& ast, AST::Id linkId); - bool DisconnectStmtFromPrevious(Tree& ast, AST::Id inputPin); - bool DisconnectStmtFromNext(Tree& ast, AST::Id outputPin, AST::Id outputNode); - bool DisconnectStmtFromNext(Tree& ast, AST::Id outputPin); + bool DisconnectStmtLink(Tree& ast, Id linkId); + bool DisconnectStmtFromPrevious(Tree& ast, Id inputPin); + bool DisconnectStmtFromNext(Tree& ast, Id outputPin, Id outputNode); + bool DisconnectStmtFromNext(Tree& ast, Id outputPin); /** * @brief Disconnects all inputs and outputs from this ids and the children nodes @@ -29,16 +28,16 @@ namespace rift::AST * @param ids * @param ignoreRoot ignore ids's inputs and outputs and only remove from children */ - void DisconnectAllStmtDeep(Tree& ast, TView ids, bool ignoreRoot = false); + void DisconnectAllStmtDeep(Tree& ast, p::TView ids, bool ignoreRoot = false); // TODO /** Check that a and b are connected (in any direction) */ - // bool AreNodesConnected(const Tree& ast, AST::Id outputNode, AST::Id inputNode); - // bool ArePinsConnected(const Tree& ast, AST::Id outputPin, AST::Id inputPin); - // bool IsOutputPinConnected(const Tree& ast, AST::Id outputPin); - // bool IsOutputPinConnected(const Tree& ast, AST::Id outputPin, AST::Id outputNode); - // bool IsInputPinConnected(const Tree& ast, AST::Id inputPin); - // bool IsInputPinConnected(const Tree& ast, AST::Id inputPin /*unused*/, AST::Id inputNode); + // bool AreNodesConnected(const Tree& ast, Id outputNode, Id inputNode); + // bool ArePinsConnected(const Tree& ast, Id outputPin, Id inputPin); + // bool IsOutputPinConnected(const Tree& ast, Id outputPin); + // bool IsOutputPinConnected(const Tree& ast, Id outputPin, Id outputNode); + // bool IsInputPinConnected(const Tree& ast, Id inputPin); + // bool IsInputPinConnected(const Tree& ast, Id inputPin /*unused*/, Id inputNode); /** Look for invalid ids and set them to NoId */ void CleanInvalidStmtIds(Tree& ast); @@ -46,13 +45,13 @@ namespace rift::AST // If two pins were to be connected, would they create a loop? bool WouldStmtLoop(const Tree& ast, Id outputNode, Id outputPin, Id inputNode); - Id GetPreviousStmt(TAccessRef access, Id stmtId); + Id GetPreviousStmt(p::TAccessRef access, Id stmtId); void GetPreviousStmts( - TAccessRef access, TView stmtIds, TArray& prevStmtIds); - TView GetNextStmts(TAccessRef access, Id stmtId); + p::TAccessRef access, p::TView stmtIds, p::TArray& prevStmtIds); + p::TView GetNextStmts(p::TAccessRef access, Id stmtId); void GetNextStmts( - TAccessRef access, TView stmtIds, TArray& nextStmtIds); + p::TAccessRef access, p::TView stmtIds, p::TArray& nextStmtIds); - void GetStmtChain(TAccessRef access, Id firstStmtId, - TArray& stmtIds, Id& splitStmtId); -} // namespace rift::AST + void GetStmtChain(p::TAccessRef access, Id firstStmtId, + p::TArray& stmtIds, Id& splitStmtId); +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/TransactionUtils.h b/Libs/AST/Include/AST/Utils/TransactionUtils.h index 80d722a6..7b8b23df 100644 --- a/Libs/AST/Include/AST/Utils/TransactionUtils.h +++ b/Libs/AST/Include/AST/Utils/TransactionUtils.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -6,12 +6,13 @@ #include "AST/Components/Tags/CChanged.h" #include "AST/Components/Tags/CDirty.h" -#include +#include -namespace rift::AST +namespace rift::ast { - using TransactionAccess = TAccessRef, TWrite, CChild, CFileRef>; + using TransactionAccess = + p::TAccessRef, p::TWrite, CChild, CFileRef>; namespace Transactions { @@ -25,16 +26,16 @@ namespace rift::AST bool active = false; ScopedTransaction() {} - ScopedTransaction(const TransactionAccess& access, TView entityIds); + ScopedTransaction(const TransactionAccess& access, p::TView entityIds); ScopedTransaction(ScopedTransaction&& other) noexcept; ~ScopedTransaction(); }; - bool PreChange(const TransactionAccess& access, TView entityIds); + bool PreChange(const TransactionAccess& access, p::TView entityIds); void PostChange(); } // namespace Transactions -} // namespace rift::AST +} // namespace rift::ast #define ScopedChange(access, entityIds) \ - rift::AST::Transactions::ScopedTransaction _transaction{access, entityIds}; + rift::ast::Transactions::ScopedTransaction _transaction{access, entityIds}; diff --git a/Libs/AST/Include/AST/Utils/TypeIterator.h b/Libs/AST/Include/AST/Utils/TypeIterator.h index 0b23e8d7..b385679c 100644 --- a/Libs/AST/Include/AST/Utils/TypeIterator.h +++ b/Libs/AST/Include/AST/Utils/TypeIterator.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Utils/Paths.h" @@ -7,18 +7,18 @@ #include -namespace rift::AST +namespace rift::ast { - class TypeIterator : public p::files::LambdaFileIterator + class TypeIterator : public p::LambdaFileIterator { - using Super = p::files::LambdaFileIterator; + using Super = p::LambdaFileIterator; public: using Super::Super; - explicit TypeIterator(const p::Path& path) - : Super(path, [](const auto& path) { - return path.extension() == Paths::typeExtension; + explicit TypeIterator(p::StringView path) + : Super(path, [](p::StringView path) { + return p::GetExtension(path) == Paths::typeExtension; }) {} }; @@ -33,4 +33,4 @@ namespace rift::AST { return {}; } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/AST/Utils/TypeUtils.h b/Libs/AST/Include/AST/Utils/TypeUtils.h index 8245c285..e7ec4e05 100644 --- a/Libs/AST/Include/AST/Utils/TypeUtils.h +++ b/Libs/AST/Include/AST/Utils/TypeUtils.h @@ -1,27 +1,21 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclFunction.h" -#include "AST/Components/CDeclType.h" -#include "AST/Components/CExprBinaryOperator.h" -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" -#include "AST/Components/CExprType.h" -#include "AST/Components/CExprUnaryOperator.h" #include "AST/Components/CFileRef.h" #include "AST/Components/CNamespace.h" -#include "AST/Components/CStmtInput.h" -#include "AST/Components/CStmtOutputs.h" +#include "AST/Components/Declarations.h" +#include "AST/Components/Expressions.h" +#include "AST/Components/Statements.h" #include "AST/Components/Tags/CChanged.h" #include "AST/Components/Tags/CDirty.h" #include "AST/Tree.h" #include "AST/TypeRef.h" -#include +#include -namespace rift::AST +namespace rift::ast { struct RiftTypeSettings { @@ -35,7 +29,7 @@ namespace rift::AST struct RiftType { p::Tag id; - p::StructType* tagType = nullptr; + p::TypeId tagType; RiftTypeSettings settings; bool operator<(const RiftType& other) const @@ -55,28 +49,28 @@ namespace rift::AST void InitTypeFromFileType(Tree& ast, Id id, p::Tag typeId); - Id CreateType(Tree& ast, p::Tag typeId, Tag name = Tag::None(), StringView path = {}); + Id CreateType(Tree& ast, p::Tag typeId, p::Tag name = p::Tag::None(), p::StringView path = {}); - void RemoveTypes(TAccessRef, TWrite, CFileRef> access, TView types, - bool removeFromDisk = false); + void RemoveTypes(p::TAccessRef, p::TWrite, CFileRef> access, + p::TView types, bool removeFromDisk = false); - void SerializeType(Tree& ast, Id id, String& data); - void DeserializeType(Tree& ast, Id id, const String& data); + void SerializeType(Tree& ast, p::Id id, p::String& data); + void DeserializeType(Tree& ast, p::Id id, const p::String& data); Id FindTypeByPath(Tree& ast, p::StringView path); - bool IsClassType(const Tree& ast, Id typeId); - bool IsStructType(const Tree& ast, Id typeId); - bool IsStaticType(const Tree& ast, Id typeId); - bool HasVariables(TAccess access, Id typeId); - bool HasFunctions(TAccess access, Id typeId); - bool HasFunctionBodies(TAccess access, Id typeId); + bool IsClassType(p::TAccessRef access, Id typeId); + bool IsStructType(p::TAccessRef access, Id typeId); + bool IsStaticType(p::TAccessRef access, Id typeId); + bool HasVariables(p::TAccessRef access, Id typeId); + bool HasFunctions(p::TAccessRef access, Id typeId); + bool HasFunctionBodies(p::TAccessRef access, Id typeId); - Id AddVariable(TypeRef type, Tag name); - Id AddFunction(TypeRef type, Tag name); + Id AddVariable(TypeRef type, p::Tag name); + Id AddFunction(TypeRef type, p::Tag name); Id AddCall(TypeRef type, Id targetFunctionId); - Id AddFunctionInput(Tree& ast, Id functionId, Tag name = Tag::None()); - Id AddFunctionOutput(Tree& ast, Id functionId, Tag name = Tag::None()); + Id AddFunctionInput(Tree& ast, Id functionId, p::Tag name = p::Tag::None()); + Id AddFunctionOutput(Tree& ast, Id functionId, p::Tag name = p::Tag::None()); Id AddIf(TypeRef type); Id AddReturn(TypeRef type); @@ -86,13 +80,15 @@ namespace rift::AST Id AddUnaryOperator(TypeRef type, UnaryOperatorType operatorType); Id AddBinaryOperator(TypeRef type, BinaryOperatorType operatorType); - Id FindChildByName(TAccessRef access, Id ownerId, Tag functionName); + Id FindChildByName(p::TAccessRef access, Id ownerId, p::Tag functionName); - using RemoveAccess = TAccess, TWrite, TWrite, - TWrite, TWrite, TWrite, CFileRef>; - void RemoveNodes(const RemoveAccess& access, TView ids); + using RemoveAccess = + p::TAccess, p::TWrite, p::TWrite, + p::TWrite, p::TWrite, p::TWrite, CFileRef>; + void RemoveNodes(const RemoveAccess& access, p::TView ids); - bool CopyExpressionType(TAccessRef> access, Id sourcePinId, Id targetPinId); + bool CopyExpressionType( + p::TAccessRef> access, Id sourcePinId, Id targetPinId); void RegisterFileType(RiftType&& descriptor); @@ -100,12 +96,12 @@ namespace rift::AST p::TView GetFileTypes(); const RiftType* FindFileType(p::Tag typeId); - const RiftType* FindFileType(p::TAccessRef access, AST::Id typeId); + const RiftType* FindFileType(p::TAccessRef access, ast::Id typeId); template void RegisterFileType(p::Tag typeId, RiftTypeSettings settings) { RegisterFileType( - {.id = typeId, .tagType = TagType::GetStaticType(), .settings = p::Move(settings)}); + {.id = typeId, .tagType = p::GetTypeId(), .settings = p::Move(settings)}); } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Include/ASTModule.h b/Libs/AST/Include/ASTModule.h index 0bf2869d..150a3b2e 100644 --- a/Libs/AST/Include/ASTModule.h +++ b/Libs/AST/Include/ASTModule.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -7,14 +7,16 @@ namespace rift { - namespace AST + namespace ast { class Tree; } class ASTModule : public Module { - CLASS(ASTModule, Module) + public: + using Super = Module; + P_CLASS(ASTModule) public: static const p::Tag structType; diff --git a/Libs/AST/Include/Compiler/Backend.h b/Libs/AST/Include/Compiler/Backend.h index 1b08ca14..18940865 100644 --- a/Libs/AST/Include/Compiler/Backend.h +++ b/Libs/AST/Include/Compiler/Backend.h @@ -1,27 +1,28 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Compiler/Compiler.h" -#include +#include namespace rift { - class Backend : public Class + class Backend : public p::Object { - CLASS(Backend, Class) - public: - virtual Tag GetName() + using Super = p::Object; + P_CLASS(Backend) + + virtual p::Tag GetName() { - return Tag::None(); + return p::Tag::None(); } virtual void Build(Compiler& compiler) { - CheckMsg(false, "Backend '{}' tried to run but Build() is not implemented.", + P_CheckMsg(false, "Backend '{}' tried to run but Build() is not implemented.", GetName().AsString()); } }; diff --git a/Libs/AST/Include/Compiler/Compiler.h b/Libs/AST/Include/Compiler/Compiler.h index ff2f5911..c039ad2b 100644 --- a/Libs/AST/Include/Compiler/Compiler.h +++ b/Libs/AST/Include/Compiler/Compiler.h @@ -1,13 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Compiler/CompilerConfig.h" -#include #include -#include -#include +#include namespace rift @@ -15,30 +13,30 @@ namespace rift class Backend; - struct CompileError : public p::Struct + struct CompileError { - STRUCT(CompileError, p::Struct) + P_STRUCT(CompileError) - PROP(text) - String text; + P_PROP(text) + p::String text; }; - struct Compiler : public p::Struct + struct Compiler { - STRUCT(Compiler, p::Struct) + P_STRUCT(Compiler) - AST::Tree& ast; + ast::Tree& ast; CompilerConfig config; - TArray errors; + p::TArray errors; public: - Compiler(AST::Tree& ast, const CompilerConfig& config) : ast{ast}, config{config} {} + Compiler(ast::Tree& ast, const CompilerConfig& config) : ast{ast}, config{config} {} // Errors - void AddError(StringView str); - const TArray& GetErrors() const + void Error(p::StringView str); + const p::TArray& GetErrors() const { return errors; } @@ -49,13 +47,13 @@ namespace rift }; - void Build(AST::Tree& tree, const CompilerConfig& config, TPtr backend); + void Build(ast::Tree& tree, const CompilerConfig& config, p::TPtr backend); - void Build(AST::Tree& ast, const CompilerConfig& config, ClassType* backendType); + void Build(ast::Tree& ast, const CompilerConfig& config, p::TypeId backendType); template - void Build(AST::Tree& ast, const CompilerConfig& config) + void Build(ast::Tree& ast, const CompilerConfig& config) { - Build(ast, config, T::GetStaticType()); + Build(ast, config, p::GetTypeId()); } } // namespace rift diff --git a/Libs/AST/Include/Compiler/CompilerConfig.h b/Libs/AST/Include/Compiler/CompilerConfig.h index 36768dd7..0791348e 100644 --- a/Libs/AST/Include/Compiler/CompilerConfig.h +++ b/Libs/AST/Include/Compiler/CompilerConfig.h @@ -1,29 +1,42 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Tree.h" -#include -#include +#include +#include namespace rift { - using namespace p; - + enum class OptimizationLevel : p::u8 + { + Zero = 0, // Only register allocator and machine code generator work + One = 1, // Additional code selection task. On this level more compact and faster code is + // generated than on zero level with practically on the same speed + Two = 2, // (Default) Additional common sub-expression elimination and sparse conditional + // constant propagation. This level is valuable if you generate bad input MIR + // code with a lot of redundancy and constants. The generation speed on level 1 + // is ~50% faster than on level 2 + Three = 3, // Additional register renaming and loop invariant code motion. The generation + // speed on level 2 is ~50% faster than on level 3 + }; - struct CompilerConfig : public p::Struct + struct CompilerConfig { - STRUCT(CompilerConfig, p::Struct) + P_STRUCT(CompilerConfig) - String buildMode{"Release"}; + OptimizationLevel optimization = OptimizationLevel::Two; - Path buildPath; - Path intermediatesPath; - Path binariesPath; + bool debug = true; + bool verbose = false; + p::String buildPath; + p::String intermediatesPath; + p::String binariesPath; - void Init(AST::Tree& ast); + void Init(ast::Tree& ast); }; } // namespace rift +P_ENUM(rift::OptimizationLevel); diff --git a/Libs/AST/Include/Compiler/Systems/OptimizationSystem.h b/Libs/AST/Include/Compiler/Systems/OptimizationSystem.h index cb5b4a5c..0b1c03c4 100644 --- a/Libs/AST/Include/Compiler/Systems/OptimizationSystem.h +++ b/Libs/AST/Include/Compiler/Systems/OptimizationSystem.h @@ -1,13 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -namespace rift::AST +namespace rift::ast { struct Tree; } namespace rift::OptimizationSystem { - void PruneDisconnectedStatements(AST::Tree& ast); - void PruneDisconnectedExpressions(AST::Tree& ast); + void PruneDisconnectedStatements(ast::Tree& ast); + void PruneDisconnectedExpressions(ast::Tree& ast); } // namespace rift::OptimizationSystem diff --git a/Libs/AST/Include/Compiler/Utils/BackendUtils.h b/Libs/AST/Include/Compiler/Utils/BackendUtils.h index 193bd40e..0e2a8118 100644 --- a/Libs/AST/Include/Compiler/Utils/BackendUtils.h +++ b/Libs/AST/Include/Compiler/Utils/BackendUtils.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -6,11 +6,11 @@ #include "Compiler/Compiler.h" #include -#include +#include namespace rift { - TArray GetBackendTypes(); - TArray> CreateBackends(); + p::TArray GetBackendTypes(); + p::TArray> CreateBackends(); } // namespace rift diff --git a/Libs/AST/Include/Module.h b/Libs/AST/Include/Module.h index 8ceca8e0..636338e2 100644 --- a/Libs/AST/Include/Module.h +++ b/Libs/AST/Include/Module.h @@ -1,12 +1,12 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "Pipe/Core/Platform.h" +#include "PipePlatform.h" #include "Rift.h" #include -#include +#include namespace rift @@ -14,9 +14,10 @@ namespace rift using namespace p; - class Module : public Class + class Module : public Object { - CLASS(Module, Class) + using Super = Object; + P_CLASS(Module) enum class State : u8 { @@ -43,7 +44,7 @@ namespace rift template void AddDependency() { - EnsureMsg(state == State::Uninitialized, + P_EnsureMsg(state == State::Uninitialized, "Should not add dependencies outside of the constructor"); EnableModule(); diff --git a/Libs/AST/Include/Rift.h b/Libs/AST/Include/Rift.h index c37ce9e6..dfb12a43 100644 --- a/Libs/AST/Include/Rift.h +++ b/Libs/AST/Include/Rift.h @@ -1,39 +1,38 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclType.h" +#include "AST/Components/Declarations.h" #include "AST/Id.h" #include "AST/Tree.h" #include "View.h" #include -#include -#include -#include +#include +#include namespace rift { - void EnableModule(p::ClassType* type); - void DisableModule(p::ClassType* type); - p::TPtr GetModule(p::ClassType* type); + void EnableModule(p::TypeId type); + void DisableModule(p::TypeId type); + p::TPtr GetModule(p::TypeId type); template void EnableModule() { - EnableModule(T::GetStaticType()); + EnableModule(p::GetTypeId()); } template void DisableModule() { - DisableModule(T::GetStaticType()); + DisableModule(p::GetTypeId()); } template p::TPtr GetModule() { - return GetModule(T::GetStaticType()).template Cast(); + return Cast(GetModule(p::GetTypeId())); } void RegisterView(View view); diff --git a/Libs/AST/Include/View.h b/Libs/AST/Include/View.h index f660facd..d1b0c0dd 100644 --- a/Libs/AST/Include/View.h +++ b/Libs/AST/Include/View.h @@ -1,19 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include "AST/Components/CDeclType.h" +#include "AST/Components/Declarations.h" #include -#include +#include namespace rift { - struct View : public p::Struct + struct View { - STRUCT(View, p::Struct) + P_STRUCT(View) - PROP(name) + P_PROP(name) p::Tag name; p::TArray supportedTypes; diff --git a/Libs/AST/Src/AST/Components/CNamespace.cpp b/Libs/AST/Src/AST/Components/CNamespace.cpp index d8154c07..c7155215 100644 --- a/Libs/AST/Src/AST/Components/CNamespace.cpp +++ b/Libs/AST/Src/AST/Components/CNamespace.cpp @@ -1,20 +1,20 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Components/CNamespace.h" -namespace rift::AST +namespace rift::ast { Namespace::Namespace(p::StringView value) { p::i32 size = 0; - const p::TChar* last = value.data() + value.size(); - const p::TChar* curr = value.data(); + const char* last = value.data() + value.size(); + const char* curr = value.data(); if (curr != last && *curr == '@') ++curr; - const p::TChar* scopeStart = curr; + const char* scopeStart = curr; while (curr != last && size < scopeCount) { if (*curr == '.') @@ -69,19 +69,23 @@ namespace rift::AST return size; } - p::String Namespace::ToString(bool isLocal) const + p::String Namespace::ToString(bool isLocal, char separator) const { p::String ns; if (!isLocal) { - ns.append("@"); const p::Tag firstScope = scopes[0]; if (!firstScope.IsNone()) { ns.append(firstScope.AsString()); - ns.append("."); + ns.push_back(separator); } } + else + { + ns.push_back('#'); + } + for (p::i32 i = 1; i < scopeCount; ++i) { const p::Tag scope = scopes[i]; @@ -90,7 +94,7 @@ namespace rift::AST break; } ns.append(scope.AsString()); - ns.append("."); + ns.push_back(separator); } if (!ns.empty()) // Remove last dot @@ -104,7 +108,7 @@ namespace rift::AST { p::u32 size = 0; ct.BeginArray(size); - size = p::math::Min(size, p::u32(Namespace::scopeCount)); + size = p::Min(size, p::u32(Namespace::scopeCount)); for (p::u32 i = 0; i < size; ++i) { ct.Next(scopes[i]); @@ -120,4 +124,4 @@ namespace rift::AST ct.Next(scopes[i]); } } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Systems/FunctionsSystem.cpp b/Libs/AST/Src/AST/Systems/FunctionsSystem.cpp index 10ea7fb7..6e0155b8 100644 --- a/Libs/AST/Src/AST/Systems/FunctionsSystem.cpp +++ b/Libs/AST/Src/AST/Systems/FunctionsSystem.cpp @@ -1,19 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Systems/FunctionsSystem.h" -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" -#include "AST/Components/CExprType.h" +#include "AST/Components/Expressions.h" #include "AST/Components/Tags/CChanged.h" #include "AST/Components/Tags/CDirty.h" #include "AST/Utils/Namespaces.h" #include "AST/Utils/TypeUtils.h" -#include +#include -namespace rift::AST::FunctionsSystem +namespace rift::ast::FunctionsSystem { struct CallToSync { @@ -23,10 +21,10 @@ namespace rift::AST::FunctionsSystem CExprInputs* functionInputs; CExprOutputs* functionOutputs; - TArray inputArgs; - TArray outputArgs; - TArray invalidArgs; - TArray unrelatedCallChildren; + p::TArray inputArgs; + p::TArray outputArgs; + p::TArray invalidArgs; + p::TArray unrelatedCallChildren; }; @@ -38,7 +36,7 @@ namespace rift::AST::FunctionsSystem } void ResolveCallFunctionIds( - TAccessRef, CExprCall, CDeclFunction, CNamespace, CParent, CChild> + p::TAccessRef, CExprCall, CDeclFunction, CNamespace, CParent, CChild> access) { auto callExprs = FindAllIdsWith(access); @@ -56,14 +54,14 @@ namespace rift::AST::FunctionsSystem void PropagateDirtyIntoCalls(Tree& ast) { - TAccess> access{ast}; + p::TAccess> access{ast}; if (access.Size() <= 0) { return; } - TArray callExprIds = FindAllIdsWith(access); - ExcludeIdsWith(access, callExprIds); + p::TArray callExprIds = p::FindAllIdsWith(access); + p::ExcludeIdsWith(access, callExprIds); for (Id id : callExprIds) { const Id functionId = access.Get(id).functionId; @@ -74,13 +72,14 @@ namespace rift::AST::FunctionsSystem } } - void PushInvalidPinsBack(TAccessRef, TWrite, CInvalid> access) + void PushInvalidPinsBack( + p::TAccessRef, p::TWrite, CInvalid> access) { - for (Id inputsId : FindAllIdsWith(access)) + for (Id inputsId : p::FindAllIdsWith(access)) { - auto& inputs = access.Get(inputsId); - i32 validSize = inputs.pinIds.Size(); - for (i32 i = 0; i < validSize;) + auto& inputs = access.Get(inputsId); + p::i32 validSize = inputs.pinIds.Size(); + for (p::i32 i = 0; i < validSize;) { Id id = inputs.pinIds[i]; if (access.Has(id)) @@ -99,11 +98,11 @@ namespace rift::AST::FunctionsSystem } } - for (Id outputsId : FindAllIdsWith(access)) + for (Id outputsId : p::FindAllIdsWith(access)) { - auto& outputs = access.Get(outputsId); - i32 validSize = outputs.pinIds.Size(); - for (i32 i = 0; i < validSize;) + auto& outputs = access.Get(outputsId); + p::i32 validSize = outputs.pinIds.Size(); + for (p::i32 i = 0; i < validSize;) { Id id = outputs.pinIds[i]; if (access.Has(id)) @@ -122,11 +121,11 @@ namespace rift::AST::FunctionsSystem void SyncCallPinsFromFunction(Tree& ast) { - TArray calls; - TAccess, TWrite, - TWrite, TWrite, TWrite> + p::TArray calls; + p::TAccess, p::TWrite, + p::TWrite, p::TWrite, p::TWrite> access{ast}; - for (Id id : FindAllIdsWith(access)) + for (Id id : p::FindAllIdsWith(access)) { const auto& call = access.Get(id); if (IsNone(call.functionId)) @@ -149,8 +148,8 @@ namespace rift::AST::FunctionsSystem // For each function pin - i32 validSize = call.functionInputs->pinIds.Size(); - for (i32 i = 0; i < validSize; ++i) + p::i32 validSize = call.functionInputs->pinIds.Size(); + for (p::i32 i = 0; i < validSize; ++i) { const Id pinId = call.functionInputs->pinIds[i]; if (access.Has(pinId)) @@ -169,13 +168,13 @@ namespace rift::AST::FunctionsSystem { Id id = ast.Create(); access.Add(id, *name); - p::Attach(ast, call.id, id); + p::AttachId(ast, call.id, id); callOutputs.Add(id); } else { // Search matching pin to 'pinId' from i to end - i32 callPinIdx = i; + p::i32 callPinIdx = i; while (callPinIdx < callOutputs.pinIds.Size()) { const Id outputPinId = callOutputs.pinIds[callPinIdx]; @@ -188,7 +187,7 @@ namespace rift::AST::FunctionsSystem { Id id = ast.Create(); access.Add(id, *name); - p::Attach(ast, call.id, id); + p::AttachId(ast, call.id, id); callOutputs.Insert(i, id); } else if (callPinIdx > i) @@ -203,12 +202,12 @@ namespace rift::AST::FunctionsSystem } // Mark as invalid all after N function params, and valid those before - const i32 firstInvalid = validSize; + const p::i32 firstInvalid = validSize; if (firstInvalid > 0) { access.Remove({callOutputs.pinIds.Data(), firstInvalid}); } - const i32 count = callOutputs.pinIds.Size() - validSize; + const p::i32 count = callOutputs.pinIds.Size() - validSize; if (count > 0) { access.AddN({callOutputs.pinIds.Data() + firstInvalid, count}); @@ -220,8 +219,8 @@ namespace rift::AST::FunctionsSystem { auto& callInputs = access.GetOrAdd(call.id); // For each function pin - i32 validSize = call.functionOutputs->pinIds.Size(); - for (i32 i = 0; i < validSize; ++i) + p::i32 validSize = call.functionOutputs->pinIds.Size(); + for (p::i32 i = 0; i < validSize; ++i) { const Id pinId = call.functionOutputs->pinIds[i]; if (access.Has(pinId)) @@ -240,13 +239,13 @@ namespace rift::AST::FunctionsSystem { Id id = ast.Create(); access.Add(id, *name); - p::Attach(ast, call.id, id); + p::AttachId(ast, call.id, id); callInputs.Add(id); } else { // Search matching pin to 'pinId' from i to end - i32 callPinIdx = i; + p::i32 callPinIdx = i; while (callPinIdx < callInputs.pinIds.Size()) { const Id pinId = callInputs.pinIds[callPinIdx]; @@ -259,7 +258,7 @@ namespace rift::AST::FunctionsSystem { Id id = ast.Create(); access.Add(id, *name); - p::Attach(ast, call.id, id); + p::AttachId(ast, call.id, id); callInputs.Insert(i, id); } else if (callPinIdx > i) @@ -274,12 +273,12 @@ namespace rift::AST::FunctionsSystem } // Mark as invalid all after N function params, and valid those before - const i32 firstInvalid = validSize; + const p::i32 firstInvalid = validSize; if (firstInvalid > 0) { access.Remove({callInputs.pinIds.Data(), firstInvalid}); } - const i32 count = callInputs.pinIds.Size() - validSize; + const p::i32 count = callInputs.pinIds.Size() - validSize; if (count > 0) { access.AddN({callInputs.pinIds.Data() + firstInvalid, count}); @@ -300,7 +299,7 @@ namespace rift::AST::FunctionsSystem for (Id id : FindAllIdsWith(access)) { const auto& inputs = access.Get(id); - for (i32 i = 0; i < inputs.pinIds.Size(); ++i) + for (p::i32 i = 0; i < inputs.pinIds.Size(); ++i) { Id pinId = inputs.pinIds[i]; const ExprOutput& output = inputs.linkedOutputs[i]; @@ -327,9 +326,9 @@ namespace rift::AST::FunctionsSystem } } - TArray pinsToRemove = FindAllIdsWith(access); + p::TArray pinsToRemove = p::FindAllIdsWith(access); ExcludeIdsWith(access, pinsToRemove); - p::Remove(access, pinsToRemove); + p::RemoveId(access, pinsToRemove); access.GetPool()->Clear(); } @@ -338,4 +337,4 @@ namespace rift::AST::FunctionsSystem { ast.AssurePool().Clear(); } -} // namespace rift::AST::FunctionsSystem +} // namespace rift::ast::FunctionsSystem diff --git a/Libs/AST/Src/AST/Systems/LoadSystem.cpp b/Libs/AST/Src/AST/Systems/LoadSystem.cpp index af8c5027..c04cca1b 100644 --- a/Libs/AST/Src/AST/Systems/LoadSystem.cpp +++ b/Libs/AST/Src/AST/Systems/LoadSystem.cpp @@ -1,29 +1,24 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Systems/LoadSystem.h" -#include "AST/Components/CDeclClass.h" -#include "AST/Components/CDeclStatic.h" -#include "AST/Components/CDeclStruct.h" -#include "AST/Components/CDeclType.h" #include "AST/Components/CModule.h" #include "AST/Components/CNamespace.h" +#include "AST/Components/Declarations.h" #include "AST/Statics/SLoadQueue.h" #include "AST/Statics/SModules.h" #include "AST/Statics/SStringLoad.h" #include "AST/Statics/STypes.h" -#include "AST/Utils/ModuleIterator.h" +#include "AST/Utils/ModuleFileIterator.h" #include "AST/Utils/ModuleUtils.h" #include "AST/Utils/TypeIterator.h" #include "AST/Utils/TypeUtils.h" -#include "Pipe/Files/Paths.h" -#include #include -#include +#include -namespace rift::AST::LoadSystem +namespace rift::ast::LoadSystem { void Init(Tree& ast) { @@ -39,54 +34,50 @@ namespace rift::AST::LoadSystem void LoadSubmodules(Tree& ast) { - TArray paths; + p::TArray paths; ScanSubmodules(ast, paths); - TArray idsToLoad; + p::TArray idsToLoad; CreateModulesFromPaths(ast, paths, idsToLoad); - TArray strings; + p::TArray strings; LoadFileStrings(ast, idsToLoad, strings); DeserializeModules(ast, idsToLoad, strings); } void LoadTypes(Tree& ast) { - TArray pathsByModule; + p::TArray pathsByModule; ScanTypes(ast, pathsByModule); - TArray idsToLoad; + p::TArray idsToLoad; CreateTypesFromPaths(ast, pathsByModule, idsToLoad); - TArray strings; + p::TArray strings; LoadFileStrings(ast, idsToLoad, strings); DeserializeTypes(ast, idsToLoad, strings); } - void ScanSubmodules(Tree& ast, TArray& paths) + void ScanSubmodules(Tree& ast, p::TArray& paths) { - ZoneScoped; - paths.Clear(); Id projectId = GetProjectId(ast); auto& projectFile = ast.Get(projectId); - for (const auto& modulePath : ModuleIterator(p::GetParentPath(projectFile.path))) + for (const auto& modulePath : ModuleFileIterator(p::GetParentPath(projectFile.path))) { paths.Add(p::ToString(modulePath)); } } - void ScanTypes(Tree& ast, TArray& pathsByModule) + void ScanTypes(Tree& ast, p::TArray& pathsByModule) { - ZoneScoped; - pathsByModule.Clear(false); // Cache module paths in a Set - TSet modulePaths; + p::TSet modulePaths; - TAccess access{ast}; + p::TAccess access{ast}; auto modules = FindAllIdsWith(access); modulePaths.Reserve(modules.Size()); @@ -100,13 +91,12 @@ namespace rift::AST::LoadSystem pathsByModule.Reserve(modules.Size()); for (Id moduleId : modules) { - Path path = AST::GetModulePath(access, moduleId); + p::StringView path = ast::GetModulePath(access, moduleId); auto& paths = pathsByModule.AddRef({moduleId}).paths; - ZoneScopedN("Iterate module files"); // Iterate all types ignoring other module paths for (const auto& typePath : - AST::TypeIterator(path /*TODO: Ignore paths | , &modulePaths*/)) + ast::TypeIterator(path /*TODO: Ignore paths | , &modulePaths*/)) { p::String path = p::ToString(typePath); if (p::GetStem(path) != "__module__") // Ignore module files @@ -117,16 +107,14 @@ namespace rift::AST::LoadSystem } } - void CreateModulesFromPaths(Tree& ast, TArray& paths, TArray& ids) + void CreateModulesFromPaths(Tree& ast, p::TArray& paths, p::TArray& ids) { - ZoneScoped; - - TAccess, TWrite, TWrite, CProject, TWrite, - TWrite> + p::TAccess, p::TWrite, p::TWrite, CProject, + p::TWrite, p::TWrite> access{ast}; // Remove existing module paths - auto moduleIds = FindAllIdsWith(access); + auto moduleIds = p::FindAllIdsWith(access); paths.RemoveIfSwap([&access, &moduleIds](const p::String& path) { bool moduleExists = false; for (Id id : moduleIds) @@ -143,24 +131,23 @@ namespace rift::AST::LoadSystem ids.Resize(paths.Size()); access.GetContext().Create(ids); - for (i32 i = 0; i < ids.Size(); ++i) + for (p::i32 i = 0; i < ids.Size(); ++i) { Id id = ids[i]; p::String& path = paths[i]; access.Add(id); access.Add(id, CNamespace{p::GetFilename(p::GetParentPath(path))}); - access.Add(id, CFileRef{Move(path)}); + access.Add(id, CFileRef{p::Move(path)}); } // Link modules to the project const Id projectId = GetProjectId(access); - p::Attach(access, projectId, ids); + p::AttachId(access, projectId, ids); } - void CreateTypesFromPaths(Tree& ast, TView pathsByModule, TArray& ids) + void CreateTypesFromPaths( + Tree& ast, p::TView pathsByModule, p::TArray& ids) { - ZoneScoped; - auto* types = ast.TryGetStatic(); if (!types) { @@ -176,35 +163,35 @@ namespace rift::AST::LoadSystem } // Create type entities - TArray typeIds; + p::TArray typeIds; for (ModuleTypePaths& modulePaths : pathsByModule) { typeIds.Resize(modulePaths.paths.Size()); ast.Create(typeIds); - for (i32 i = 0; i < typeIds.Size(); ++i) + for (p::i32 i = 0; i < typeIds.Size(); ++i) { - const Id id = typeIds[i]; - String& path = modulePaths.paths[i]; + const Id id = typeIds[i]; + p::String& path = modulePaths.paths[i]; types->typesByPath.Insert(p::Tag{path}, id); - ast.Add(id, CFileRef{Move(path)}); + ast.Add(id, CFileRef{p::Move(path)}); } - p::Attach(ast, modulePaths.moduleId, typeIds); + p::AttachId(ast, modulePaths.moduleId, typeIds); ids.Append(typeIds); } } - void LoadFileStrings(TAccessRef access, TView nodes, TArray& strings) + void LoadFileStrings( + p::TAccessRef access, p::TView nodes, p::TArray& strings) { - ZoneScoped; strings.Resize(nodes.Size()); - for (i32 i = 0; i < nodes.Size(); ++i) + for (p::i32 i = 0; i < nodes.Size(); ++i) { if (auto* file = access.TryGet(nodes[i])) [[likely]] { - if (!files::LoadStringFile(file->path, strings[i], 4)) + if (!p::LoadStringFile(file->path, strings[i], 4)) { p::Error("File could not be loaded from disk ({})", file->path); continue; @@ -213,25 +200,23 @@ namespace rift::AST::LoadSystem } } - void DeserializeModules(Tree& ast, TView moduleIds, TView strings) + void DeserializeModules(Tree& ast, p::TView moduleIds, p::TView strings) { - ZoneScoped; - Check(moduleIds.Size() == strings.Size()); + P_Check(moduleIds.Size() == strings.Size()); - for (i32 i = 0; i < moduleIds.Size(); ++i) + for (p::i32 i = 0; i < moduleIds.Size(); ++i) { DeserializeModule(ast, moduleIds[i], strings[i]); } } - void DeserializeTypes(Tree& ast, TView typeIds, TView strings) + void DeserializeTypes(Tree& ast, p::TView typeIds, p::TView strings) { - ZoneScoped; - Check(typeIds.Size() == strings.Size()); + P_Check(typeIds.Size() == strings.Size()); - for (i32 i = 0; i < typeIds.Size(); ++i) + for (p::i32 i = 0; i < typeIds.Size(); ++i) { DeserializeType(ast, typeIds[i], strings[i]); } } -} // namespace rift::AST::LoadSystem +} // namespace rift::ast::LoadSystem diff --git a/Libs/AST/Src/AST/Systems/TransactionSystem.cpp b/Libs/AST/Src/AST/Systems/TransactionSystem.cpp index b3144127..c5cf5eb3 100644 --- a/Libs/AST/Src/AST/Systems/TransactionSystem.cpp +++ b/Libs/AST/Src/AST/Systems/TransactionSystem.cpp @@ -1,15 +1,15 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Systems/TransactionSystem.h" #include "AST/Components/Tags/CChanged.h" -namespace rift::AST::TransactionSystem +namespace rift::ast::TransactionSystem { void Init(Tree& ast) {} void ClearTags(Tree& ast) { ast.AssurePool().Clear(); } -} // namespace rift::AST::TransactionSystem +} // namespace rift::ast::TransactionSystem diff --git a/Libs/AST/Src/AST/Systems/TypeSystem.cpp b/Libs/AST/Src/AST/Systems/TypeSystem.cpp index b053bd11..d5f649af 100644 --- a/Libs/AST/Src/AST/Systems/TypeSystem.cpp +++ b/Libs/AST/Src/AST/Systems/TypeSystem.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Systems/TypeSystem.h" @@ -10,14 +10,14 @@ #include "AST/Utils/Namespaces.h" #include "AST/Utils/TypeUtils.h" -#include +#include -namespace rift::AST::TypeSystem +namespace rift::ast::TypeSystem { void Init(Tree& ast) { - TAccess access{ast}; + p::TAccess access{ast}; ast.OnAdd().Bind([](auto& ast, auto ids) { auto& types = ast.template GetOrSetStatic(); @@ -57,7 +57,7 @@ namespace rift::AST::TypeSystem } } - bool PropagateUnaryOperator(TAccess> access, Id nodeId) + bool PropagateUnaryOperator(p::TAccess> access, Id nodeId) { const Id outputId = nodeId; // Output in unary operator is same as the node itself const auto& inputs = access.Get(nodeId); @@ -69,7 +69,7 @@ namespace rift::AST::TypeSystem return false; } - bool PropagateBinaryOperator(TAccess> access, Id nodeId) + bool PropagateBinaryOperator(p::TAccess> access, Id nodeId) { const auto& inputs = access.Get(nodeId); Id outputId = nodeId; // Output in binary operator is same as the node itself @@ -87,16 +87,16 @@ namespace rift::AST::TypeSystem void PropagateExpressionTypes(PropagateExpressionTypesAccess access) { - TArray dirtyTypeIds = FindAllIdsWith(access); + p::TArray dirtyTypeIds = p::FindAllIdsWith(access); - TArray dirtyNodeIds; - p::GetChildren(access, dirtyTypeIds, dirtyNodeIds); + p::TArray dirtyNodeIds; + p::GetIdChildren(access, dirtyTypeIds, dirtyNodeIds); // Make sure the nodes have inputs and outputs - ExcludeIdsWithout(access, dirtyNodeIds); + p::ExcludeIdsWithout(access, dirtyNodeIds); // Only Unary and Binary operators propagate as of right now - ExcludeIdsWith(dirtyNodeIds, [&access](Id id) { + p::ExcludeIdsWith(dirtyNodeIds, [&access](Id id) { return !access.Has(id) && !access.Has(id); }); @@ -105,7 +105,7 @@ namespace rift::AST::TypeSystem { bool anyPropagated = false; // Propagate all dirty nodes, remove successfully propagated ones - for (i32 i = dirtyNodeIds.Size() - 1; i >= 0; --i) + for (p::i32 i = dirtyNodeIds.Size() - 1; i >= 0; --i) { const Id nodeId = dirtyNodeIds[i]; @@ -135,18 +135,18 @@ namespace rift::AST::TypeSystem } void ResolveExprTypeIds( - TAccessRef, CExprType, CNamespace, CParent, CChild> access) + p::TAccessRef, CExprType, CNamespace, CParent, CChild> access) { - auto callExprs = FindAllIdsWith(access); - ExcludeIdsWith(access, callExprs); + auto callExprs = p::FindAllIdsWith(access); + p::ExcludeIdsWith(access, callExprs); for (Id id : callExprs) { auto& expr = access.Get(id); const Id typeId = FindIdFromNamespace(access, expr.type); - if (!IsNone(typeId)) + if (!p::IsNone(typeId)) { access.Add(id, CExprTypeId{.id = typeId, .mode = expr.mode}); } } } -} // namespace rift::AST::TypeSystem +} // namespace rift::ast::TypeSystem diff --git a/Libs/AST/Src/AST/Tree.cpp b/Libs/AST/Src/AST/Tree.cpp index 27010dac..e438c06d 100644 --- a/Libs/AST/Src/AST/Tree.cpp +++ b/Libs/AST/Src/AST/Tree.cpp @@ -1,19 +1,18 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Tree.h" -#include "AST/Components/CDeclNative.h" -#include "AST/Components/CDeclType.h" #include "AST/Components/CNamespace.h" +#include "AST/Components/Declarations.h" #include "AST/Statics/SModules.h" #include "AST/Statics/STypes.h" -#include +#include -namespace rift::AST +namespace rift::ast { - TBroadcast Tree::onInit{}; + p::TBroadcast Tree::onInit{}; Tree::Tree() @@ -22,28 +21,28 @@ namespace rift::AST onInit(*this); } - Tree::Tree(const Tree& other) noexcept : EntityContext(other) + Tree::Tree(const Tree& other) noexcept : p::EntityContext(other) { CopyFrom(other); } - Tree::Tree(Tree&& other) noexcept : EntityContext(Move(other)) + Tree::Tree(Tree&& other) noexcept : p::EntityContext(p::Move(other)) { - MoveFrom(Move(other)); + MoveFrom(p::Move(other)); } Tree& Tree::operator=(const Tree& other) noexcept { - EntityContext::operator=(other); + p::EntityContext::operator=(other); CopyFrom(other); return *this; } Tree& Tree::operator=(Tree&& other) noexcept { - EntityContext::operator=(Move(other)); - MoveFrom(Move(other)); + EntityContext::operator=(p::Move(other)); + MoveFrom(p::Move(other)); return *this; } - const TBroadcast& Tree::OnInit() + const p::TBroadcast& Tree::OnInit() { return onInit; } @@ -51,7 +50,7 @@ namespace rift::AST void Tree::SetupNativeTypes() { // Remove any previous native types - Destroy(FindAllIdsWith(*this)); + Destroy(p::FindAllIdsWith(*this)); nativeTypes.boolId = Create(); Add(nativeTypes.boolId); @@ -122,4 +121,20 @@ namespace rift::AST { nativeTypes = other.nativeTypes; } -} // namespace rift::AST + + p::String Tree::DumpPools() + { + p::String text; + + text.append("Pools: \n"); + for (const auto& pool : GetPools()) + { + p::TypeId type = pool.GetId(); + p::Strings::FormatTo(text, "- {} x{}\n", + type.IsValid() ? GetTypeName(type) : p::StringView{"NotReflected"}, + pool.GetPool()->Size()); + } + + return text; + } +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Utils/Expressions.cpp b/Libs/AST/Src/AST/Utils/Expressions.cpp index d86eb5eb..b6142336 100644 --- a/Libs/AST/Src/AST/Utils/Expressions.cpp +++ b/Libs/AST/Src/AST/Utils/Expressions.cpp @@ -1,17 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/Expressions.h" #include "AST/Id.h" -namespace rift::AST +namespace rift::ast { - bool WouldExprLoop( - TAccessRef access, Id outputNodeId, Id inputNodeId) + bool WouldExprLoop(p::TAccessRef access, + Id outputNodeId, Id inputNodeId) { - TArray currentNodeIds{outputNodeId}; - TArray nextNodeIds{}; + p::TArray currentNodeIds{outputNodeId}; + p::TArray nextNodeIds{}; while (!currentNodeIds.IsEmpty()) { for (Id id : currentNodeIds) @@ -38,7 +38,7 @@ namespace rift::AST return false; } - bool CanConnectExpr(TAccessRef access, + bool CanConnectExpr(p::TAccessRef access, ExprOutput output, ExprInput input) { if (output.IsNone() || input.IsNone()) @@ -91,7 +91,7 @@ namespace rift::AST return !WouldExprLoop(access, output.nodeId, input.nodeId); } - bool TryConnectExpr(TAccessRef, CExprOutputs, CExprTypeId> access, + bool TryConnectExpr(p::TAccessRef, CExprOutputs, CExprTypeId> access, ExprOutput output, ExprInput input) { if (!CanConnectExpr(access, output, input)) @@ -102,10 +102,10 @@ namespace rift::AST auto& inputs = access.Get(input.nodeId); // Find pin index - const i32 index = inputs.pinIds.FindIndex([&input](Id pinId) { + const p::i32 index = inputs.pinIds.FindIndex([&input](Id pinId) { return input.pinId == pinId; }); - if (index != NO_INDEX && Ensure(index < inputs.linkedOutputs.Size())) + if (index != p::NO_INDEX && P_Ensure(index < inputs.linkedOutputs.Size())) { inputs.linkedOutputs[index] = output; return true; @@ -123,10 +123,8 @@ namespace rift::AST auto& inputs = ast.Get(input.nodeId); // Find pin index - const i32 index = inputs.pinIds.FindIndex([&input](Id pinId) { - return input.pinId == pinId; - }); - if (index != NO_INDEX && Ensure(index < inputs.linkedOutputs.Size())) [[likely]] + const p::i32 index = inputs.pinIds.FindIndex(input.pinId); + if (index != p::NO_INDEX && P_Ensure(index < inputs.linkedOutputs.Size())) [[likely]] { ExprOutput& linked = inputs.linkedOutputs[index]; linked = {}; @@ -136,12 +134,12 @@ namespace rift::AST } - bool RemoveExprInputPin(TAccessRef> access, ExprInput input) + bool RemoveExprInputPin(p::TAccessRef> access, ExprInput input) { if (!input.IsNone()) { const auto* inputs = access.TryGet(input.nodeId); - if (inputs && inputs->pinIds.FindIndex(input.pinId) != NO_INDEX) + if (inputs && inputs->pinIds.FindIndex(input.pinId) != p::NO_INDEX) { access.Add(input.pinId); return true; @@ -150,7 +148,8 @@ namespace rift::AST return false; } - bool RemoveExprOutputPin(TAccessRef> access, ExprOutput output) + bool RemoveExprOutputPin( + p::TAccessRef> access, ExprOutput output) { if (!output.IsNone()) { @@ -163,7 +162,7 @@ namespace rift::AST return false; } - ExprInput GetExprInputFromPin(TAccessRef access, Id pinId) + ExprInput GetExprInputFromPin(p::TAccessRef access, Id pinId) { ExprInput input{}; input.pinId = pinId; @@ -171,12 +170,12 @@ namespace rift::AST input.nodeId = pinId; if (!IsNone(input.nodeId) && !access.Has(input.nodeId)) { - input.nodeId = p::GetParent(access, pinId); + input.nodeId = p::GetIdParent(access, pinId); } return input; } - ExprOutput GetExprOutputFromPin(TAccessRef access, Id pinId) + ExprOutput GetExprOutputFromPin(p::TAccessRef access, Id pinId) { ExprOutput output{}; output.pinId = pinId; @@ -184,8 +183,8 @@ namespace rift::AST output.nodeId = pinId; if (!IsNone(output.nodeId) && !access.Has(output.nodeId)) { - output.nodeId = p::GetParent(access, pinId); + output.nodeId = p::GetIdParent(access, pinId); } return output; } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Utils/ModuleUtils.cpp b/Libs/AST/Src/AST/Utils/ModuleUtils.cpp index c7f9cc40..616c33bb 100644 --- a/Libs/AST/Src/AST/Utils/ModuleUtils.cpp +++ b/Libs/AST/Src/AST/Utils/ModuleUtils.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/ModuleUtils.h" @@ -9,18 +9,16 @@ #include "AST/Systems/LoadSystem.h" #include "AST/Systems/TypeSystem.h" -#include #include #include -#include -#include +#include -namespace rift::AST +namespace rift::ast { static p::TArray gModuleBindings; - TBroadcast gOnReadModulePools; - TBroadcast gOnWriteModulePools; + p::TBroadcast gOnReadModulePools; + p::TBroadcast gOnWriteModulePools; bool ValidateModulePath(p::String& path, p::String& error) @@ -31,7 +29,7 @@ namespace rift::AST return false; } - if (files::IsFile(path)) + if (p::IsFile(path)) { if (p::GetFilename(path) != moduleFilename) { @@ -54,22 +52,22 @@ namespace rift::AST bool OpenProject(Tree& ast, p::StringView path) { - String validatedPath{path}; - String error; + p::String validatedPath{path}; + p::String error; if (!ValidateModulePath(validatedPath, error)) { p::Error("Can't open project: {}", error); return false; } - if (!files::ExistsAsFolder(validatedPath)) + if (!p::ExistsAsFolder(validatedPath)) { p::Error("Can't open project: Folder doesn't exist"); return false; } const p::String filePath = p::JoinPaths(validatedPath, moduleFilename); - if (!files::ExistsAsFile(filePath)) + if (!p::ExistsAsFile(filePath)) { p::Error("Can't open project: Folder doesn't contain a '{}' file", moduleFilename); return false; @@ -89,7 +87,7 @@ namespace rift::AST ast.Add(projectId, CFileRef{filePath}); // Load project module - TArray strings; + p::TArray strings; LoadSystem::LoadFileStrings(ast, projectId, strings); LoadSystem::DeserializeModules(ast, projectId, strings); return true; @@ -102,22 +100,22 @@ namespace rift::AST Id CreateModule(Tree& ast, p::StringView path) { - String validatedPath{path}; + p::String validatedPath{path}; - String error; + p::String error; if (!ValidateModulePath(validatedPath, error)) { p::Error("Can't create module: {}", error); return NoId; } - if (!files::ExistsAsFolder(validatedPath)) + if (!p::ExistsAsFolder(validatedPath)) { - files::CreateFolder(validatedPath, true); + p::CreateFolder(validatedPath, true); } const p::String filePath = p::JoinPaths(validatedPath, moduleFilename); - if (files::ExistsAsFile(filePath)) + if (p::ExistsAsFile(filePath)) { p::Error("Can't create module: Folder already contains a '{}' file", moduleFilename); return NoId; @@ -130,27 +128,27 @@ namespace rift::AST p::String data; SerializeModule(ast, moduleId, data); - files::SaveStringFile(filePath, data); + p::SaveStringFile(filePath, data); return moduleId; } - Id GetProjectId(TAccessRef access) + Id GetProjectId(p::TAccessRef access) { return GetFirstId(access); } - Tag GetProjectName(TAccessRef access) + p::Tag GetProjectName(p::TAccessRef access) { Id moduleId = GetProjectId(access); return GetModuleName(access, moduleId); } - p::StringView GetProjectPath(TAccessRef access) + p::StringView GetProjectPath(p::TAccessRef access) { return GetModulePath(access, GetProjectId(access)); } - CModule* GetProjectModule(TAccessRef> access) + CModule* GetProjectModule(p::TAccessRef> access) { const Id projectId = GetProjectId(access); if (projectId != NoId) @@ -165,7 +163,7 @@ namespace rift::AST return GetProjectId(ast) != NoId; } - Tag GetModuleName(TAccessRef access, Id moduleId) + p::Tag GetModuleName(p::TAccessRef access, Id moduleId) { if (!access.IsValid(moduleId)) { @@ -182,13 +180,13 @@ namespace rift::AST if (file && !file->path.empty()) { // Obtain name from project file name - const String fileName = p::ToString(file->path); - return Tag{p::GetFilename(p::GetParentPath(fileName))}; // Folder name + const p::String fileName = p::ToString(file->path); + return p::Tag{p::GetFilename(p::GetParentPath(fileName))}; // Folder name } return {}; } - p::StringView GetModulePath(TAccessRef access, Id moduleId) + p::StringView GetModulePath(p::TAccessRef access, Id moduleId) { if (const auto* file = access.TryGet(moduleId)) { @@ -197,10 +195,9 @@ namespace rift::AST return {}; } - void SerializeModule(AST::Tree& ast, AST::Id id, String& data) + void SerializeModule(ast::Tree& ast, ast::Id id, p::String& data) { - ZoneScoped; - JsonFormatWriter writer{}; + p::JsonFormatWriter writer{}; p::EntityWriter w{writer.GetWriter(), ast}; w.BeginObject(); w.SerializeSingleEntity(id, gOnWriteModulePools); @@ -208,10 +205,9 @@ namespace rift::AST data = writer.ToString(); } - void DeserializeModule(AST::Tree& ast, AST::Id id, const String& data) + void DeserializeModule(ast::Tree& ast, ast::Id id, const p::String& data) { - ZoneScoped; - JsonFormatReader formatReader{data}; + p::JsonFormatReader formatReader{data}; if (formatReader.IsValid()) { p::EntityReader r{formatReader, ast}; @@ -219,11 +215,11 @@ namespace rift::AST r.SerializeSingleEntity(id, gOnReadModulePools); } } - const TBroadcast& OnReadModulePools() + const p::TBroadcast& OnReadModulePools() { return gOnReadModulePools; } - const TBroadcast& OnWriteModulePools() + const p::TBroadcast& OnWriteModulePools() { return gOnWriteModulePools; } @@ -231,35 +227,35 @@ namespace rift::AST void RegisterModuleBinding(ModuleBinding binding) { - gModuleBindings.AddUniqueSorted(Move(binding)); + gModuleBindings.AddUniqueSorted(p::Move(binding)); } void UnregisterModuleBinding(p::Tag bindingId) { gModuleBindings.RemoveSorted(bindingId); } - void AddBindingToModule(AST::Tree& ast, AST::Id id, p::Tag bindingId) + void AddBindingToModule(ast::Tree& ast, ast::Id id, p::Tag bindingId) { if (const auto* binding = FindModuleBinding(bindingId)) { - ast.AddDefault(binding->tagType->GetId(), id); + ast.AddDefault(binding->tagType, id); } } - void RemoveBindingFromModule(AST::Tree& ast, AST::Id id, p::Tag bindingId) + void RemoveBindingFromModule(ast::Tree& ast, ast::Id id, p::Tag bindingId) { if (const auto* binding = FindModuleBinding(bindingId)) { - ast.Remove(binding->tagType->GetId(), id); + ast.Remove(binding->tagType, id); } } const ModuleBinding* FindModuleBinding(p::Tag id) { - const i32 index = gModuleBindings.FindSortedEqual(id); - return index != NO_INDEX ? gModuleBindings.Data() + index : nullptr; + const p::i32 index = gModuleBindings.FindSorted(id); + return index != p::NO_INDEX ? gModuleBindings.Data() + index : nullptr; } p::TView GetModuleBindings() { return gModuleBindings; } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Utils/Namespaces.cpp b/Libs/AST/Src/AST/Utils/Namespaces.cpp index 495fe54a..9284ac90 100644 --- a/Libs/AST/Src/AST/Utils/Namespaces.cpp +++ b/Libs/AST/Src/AST/Utils/Namespaces.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/Namespaces.h" @@ -6,16 +6,16 @@ #include "AST/Id.h" #include "Pipe/Core/StringView.h" -#include -#include +#include +#include -namespace rift::AST +namespace rift::ast { - Namespace GetNamespace(TAccessRef access, Id id) + Namespace GetNamespace(p::TAccessRef access, Id id) { Namespace ns; - TArray idChain; + p::TArray idChain; idChain.Reserve(Namespace::scopeCount); while (!IsNone(id)) @@ -25,43 +25,43 @@ namespace rift::AST { break; } - id = p::GetParent(access, id); + id = p::GetIdParent(access, id); } - i32 i, scopeIndex = 0; + p::i32 i, scopeIndex = 0; for (i = idChain.Size() - 1; i >= 0 && scopeIndex < Namespace::scopeCount; --i) { ns.scopes[scopeIndex] = GetName(access, idChain[i]); ++scopeIndex; } - CheckMsg(i < 0, "Not enough scopes to cover this namespace"); + P_CheckMsg(i < 0, "Not enough scopes to cover this namespace"); return ns; } - Namespace GetParentNamespace(TAccessRef access, Id id) + Namespace GetParentNamespace(p::TAccessRef access, Id id) { if (!IsNone(id)) { - return GetNamespace(access, p::GetParent(access, id)); + return GetNamespace(access, p::GetIdParent(access, id)); } return {}; } - Id FindIdFromNamespace(TAccessRef access, const Namespace& ns, - const TArray* rootIds) + Id FindIdFromNamespace(p::TAccessRef access, const Namespace& ns, + const p::TArray* rootIds) { - TArray localRoots; + p::TArray localRoots; if (!rootIds) { - localRoots = FindAllIdsWith(access); - ExcludeIdsWith(access, localRoots); + localRoots = p::FindAllIdsWith(access); + p::ExcludeIdsWith(access, localRoots); rootIds = &localRoots; } - const TArray* scopeIds = rootIds; - Id foundScopeId = NoId; - Tag scopeName; - i32 depth = 0; + const p::TArray* scopeIds = rootIds; + Id foundScopeId = NoId; + p::Tag scopeName; + p::i32 depth = 0; while (scopeIds && depth < Namespace::scopeCount) { scopeName = ns[depth]; @@ -84,7 +84,7 @@ namespace rift::AST if (!IsNone(foundScopeId)) { // Found matching name, check next scope - scopeIds = p::GetChildren(access, foundScopeId); + scopeIds = p::GetIdChildren(access, foundScopeId); ++depth; } else @@ -95,20 +95,20 @@ namespace rift::AST return foundScopeId; } - Tag GetName(TAccessRef access, Id id) + p::Tag GetName(p::TAccessRef access, Id id) { auto* ns = access.TryGet(id); - return ns ? ns->name : Tag::None(); + return ns ? ns->name : p::Tag::None(); } - Tag GetNameUnsafe(TAccessRef access, Id id) + p::Tag GetNameUnsafe(p::TAccessRef access, Id id) { return access.Get(id).name; } - p::String GetFullName( - TAccessRef access, Id id, bool localNamespace) + p::String GetFullName(p::TAccessRef access, Id id, + bool localNamespace, char separator) { - return GetNamespace(access, id).ToString(localNamespace); + return GetNamespace(access, id).ToString(localNamespace, separator); } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Utils/Settings.cpp b/Libs/AST/Src/AST/Utils/Settings.cpp new file mode 100644 index 00000000..4d8f182f --- /dev/null +++ b/Libs/AST/Src/AST/Utils/Settings.cpp @@ -0,0 +1,19 @@ +// Copyright 2015-2024 Piperift - All rights reserved + +#include "AST/Utils/Settings.h" + +#include +#include + + +namespace rift +{ + p::String GetUserSettingsPath(p::StringView name) + { + static p::StringView relativeSettingsPath{"Rift"}; + p::String path = + p::JoinPaths(p::PlatformPaths::GetUserSettingsPath(), relativeSettingsPath, name); + path.append(".json"); + return p::Move(path); + } +} // namespace rift diff --git a/Libs/AST/Src/AST/Utils/Statements.cpp b/Libs/AST/Src/AST/Utils/Statements.cpp index 31ca1dba..5bb0a1e4 100644 --- a/Libs/AST/Src/AST/Utils/Statements.cpp +++ b/Libs/AST/Src/AST/Utils/Statements.cpp @@ -1,11 +1,12 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/Statements.h" #include "AST/Id.h" +#include "PipeECS.h" -namespace rift::AST +namespace rift::ast { bool CanConnectStmt(const Tree& ast, Id outputNode, Id outputPin, Id inputNode) { @@ -25,20 +26,20 @@ namespace rift::AST bool TryConnectStmt(Tree& ast, Id outputPin, Id inputNode) { - if (!Ensure(!IsNone(outputPin) && !IsNone(inputNode))) + if (!P_Ensure(!IsNone(outputPin) && !IsNone(inputNode))) { return false; } // Resolve output node. Sometimes the output pin itself is the node - Id outputNode = AST::NoId; + Id outputNode = ast::NoId; if (ast.Has(outputPin)) { outputNode = outputPin; } else { - outputNode = p::GetParent(ast, outputPin); + outputNode = p::GetIdParent(ast, outputPin); if (IsNone(outputNode)) { return false; @@ -52,16 +53,16 @@ namespace rift::AST auto& inputComp = ast.Get(inputNode); - if (inputComp.linkOutputNode != AST::NoId) + if (inputComp.linkOutputNode != ast::NoId) { // Disconnect previous output connected to input if any if (auto* lastOutputComp = ast.TryGet(inputComp.linkOutputNode)) { - lastOutputComp->linkInputNode = AST::NoId; + lastOutputComp->linkInputNode = ast::NoId; } else if (auto* lastOutputsComp = ast.TryGet(inputComp.linkOutputNode)) { - lastOutputsComp->linkInputNodes.FindRef(inputNode) = AST::NoId; + lastOutputsComp->linkInputNodes.FindRef(inputNode) = ast::NoId; } } inputComp.linkOutputNode = outputNode; @@ -72,23 +73,23 @@ namespace rift::AST // Connect if single output Id& lastInputNode = outputComp->linkInputNode; // Disconnect previous input connected to output if any - if (lastInputNode != AST::NoId && ast.Has(lastInputNode)) + if (lastInputNode != ast::NoId && ast.Has(lastInputNode)) { - ast.Get(lastInputNode).linkOutputNode = AST::NoId; + ast.Get(lastInputNode).linkOutputNode = ast::NoId; } lastInputNode = inputNode; } else if (auto* outputsComp = ast.TryGet(outputNode)) { // Connect if multiple output - const i32 pinIndex = outputsComp->pinIds.FindIndex(outputPin); - if (pinIndex != NO_INDEX) + const p::i32 pinIndex = outputsComp->pinIds.FindIndex(outputPin); + if (pinIndex != p::NO_INDEX) { Id& lastInputNode = outputsComp->linkInputNodes[pinIndex]; // Disconnect previous input connected to output if any - if (lastInputNode != AST::NoId && ast.Has(lastInputNode)) + if (lastInputNode != ast::NoId && ast.Has(lastInputNode)) { - ast.Get(lastInputNode).linkOutputNode = AST::NoId; + ast.Get(lastInputNode).linkOutputNode = ast::NoId; } lastInputNode = inputNode; } @@ -112,48 +113,48 @@ namespace rift::AST // Input node is always the same id as linkId auto* inputComp = ast.TryGet(linkId); if (inputComp - && EnsureMsg(!IsNone(inputComp->linkOutputNode), + && P_EnsureMsg(!IsNone(inputComp->linkOutputNode), "Trying to disconnect a unexistant link")) [[likely]] { // We expect the other side to have outputs component auto& outputsComp = ast.Get(inputComp->linkOutputNode); if (Id* lastInputNode = outputsComp.linkInputNodes.Find(linkId)) [[likely]] { - *lastInputNode = AST::NoId; + *lastInputNode = ast::NoId; } - inputComp->linkOutputNode = AST::NoId; + inputComp->linkOutputNode = ast::NoId; return true; } return false; } - bool DisconnectStmtFromPrevious(Tree& ast, AST::Id inputPin) + bool DisconnectStmtFromPrevious(Tree& ast, ast::Id inputPin) { // NOTE: Input pin ids equal input node ids return DisconnectStmtLink(ast, inputPin); } - bool DisconnectStmtFromNext(Tree& ast, AST::Id outputPin, AST::Id outputNode) + bool DisconnectStmtFromNext(Tree& ast, ast::Id outputPin, ast::Id outputNode) { // NOTE: Can be optimized if needed since outputs is accessed twice counting // Disconnect() if (auto* outputsComp = ast.TryGet(outputNode)) { - i32 pinIndex = outputsComp->pinIds.FindIndex(outputPin); - if (pinIndex != NO_INDEX) [[likely]] + p::i32 pinIndex = outputsComp->pinIds.FindIndex(outputPin); + if (pinIndex != p::NO_INDEX) [[likely]] { return DisconnectStmtLink(ast, outputsComp->linkInputNodes[pinIndex]); } } return false; } - bool DisconnectStmtFromNext(Tree& ast, AST::Id outputPin) + bool DisconnectStmtFromNext(Tree& ast, ast::Id outputPin) { - return DisconnectStmtFromNext(ast, outputPin, p::GetParent(ast, outputPin)); + return DisconnectStmtFromNext(ast, outputPin, p::GetIdParent(ast, outputPin)); } bool WouldStmtLoop(const Tree& ast, Id outputNode, Id outputPin, Id inputNode) { - AST::Id currentNode = outputNode; + ast::Id currentNode = outputNode; while (!IsNone(currentNode)) { const auto* input = ast.TryGet(currentNode); @@ -170,7 +171,7 @@ namespace rift::AST return false; } - Id GetPreviousStmt(TAccessRef access, Id stmtIds) + Id GetPreviousStmt(p::TAccessRef access, Id stmtIds) { if (const auto* input = access.TryGet(stmtIds)) { @@ -180,7 +181,7 @@ namespace rift::AST } void GetPreviousStmts( - TAccessRef access, TView stmtIds, TArray& prevStmtIds) + p::TAccessRef access, p::TView stmtIds, p::TArray& prevStmtIds) { prevStmtIds.ReserveMore(stmtIds.Size()); for (const Id stmtId : stmtIds) @@ -192,7 +193,7 @@ namespace rift::AST } } - TView GetNextStmts(TAccessRef access, Id stmtIds) + p::TView GetNextStmts(p::TAccessRef access, Id stmtIds) { if (const auto* output = access.TryGet(stmtIds)) { @@ -202,7 +203,7 @@ namespace rift::AST } void GetNextStmts( - TAccessRef access, TView stmtIds, TArray& nextStmtIds) + p::TAccessRef access, p::TView stmtIds, p::TArray& nextStmtIds) { nextStmtIds.ReserveMore(stmtIds.Size()); for (const Id stmtId : stmtIds) @@ -214,11 +215,11 @@ namespace rift::AST } } - void GetStmtChain(TAccessRef access, Id firstStmtId, - TArray& stmtIds, Id& splitStmtId) + void GetStmtChain(p::TAccessRef access, Id firstStmtId, + p::TArray& stmtIds, Id& splitStmtId) { Id id = firstStmtId; - while (id != AST::NoId && access.Has(id)) + while (id != ast::NoId && access.Has(id)) { stmtIds.Add(id); id = access.Get(id).linkInputNode; @@ -229,4 +230,4 @@ namespace rift::AST splitStmtId = id; } } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/AST/Utils/TransactionUtils.cpp b/Libs/AST/Src/AST/Utils/TransactionUtils.cpp index 48ef94d9..4d484167 100644 --- a/Libs/AST/Src/AST/Utils/TransactionUtils.cpp +++ b/Libs/AST/Src/AST/Utils/TransactionUtils.cpp @@ -1,18 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/TransactionUtils.h" -#include "AST/Components/CDeclType.h" +#include "AST/Components/Declarations.h" -#include +#include -namespace rift::AST::Transactions +namespace rift::ast::Transactions { // Transaction being recorded static Transaction gActiveTransaction = {}; - ScopedTransaction::ScopedTransaction(const TransactionAccess& access, TView entityIds) + ScopedTransaction::ScopedTransaction( + const TransactionAccess& access, p::TView entityIds) { active = PreChange(access, entityIds); } @@ -29,9 +30,9 @@ namespace rift::AST::Transactions } } - bool PreChange(const TransactionAccess& access, TView entityIds) + bool PreChange(const TransactionAccess& access, p::TView entityIds) { - if (!EnsureMsg(!gActiveTransaction.active, + if (!P_EnsureMsg(!gActiveTransaction.active, "Tried to record a transaction while another is already being recorded")) { return false; @@ -40,8 +41,8 @@ namespace rift::AST::Transactions gActiveTransaction = Transaction{true}; // Mark files dirty - TArray parentIds; - p::GetAllParents(access, entityIds, parentIds); + p::TArray parentIds; + p::GetAllIdParents(access, entityIds, parentIds); parentIds.Append(entityIds); access.AddN(parentIds); @@ -59,10 +60,10 @@ namespace rift::AST::Transactions void PostChange() { - if (EnsureMsg(gActiveTransaction.active, + if (P_EnsureMsg(gActiveTransaction.active, "Cant finish a transaction while none is being recorded")) { gActiveTransaction = {}; } } -} // namespace rift::AST::Transactions +} // namespace rift::ast::Transactions diff --git a/Libs/AST/Src/AST/Utils/TypeUtils.cpp b/Libs/AST/Src/AST/Utils/TypeUtils.cpp index b36862ab..2b9ab5f1 100644 --- a/Libs/AST/Src/AST/Utils/TypeUtils.cpp +++ b/Libs/AST/Src/AST/Utils/TypeUtils.cpp @@ -1,27 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Utils/TypeUtils.h" -#include "AST/Components/CDeclClass.h" -#include "AST/Components/CDeclStatic.h" -#include "AST/Components/CDeclStruct.h" -#include "AST/Components/CDeclType.h" -#include "AST/Components/CDeclVariable.h" -#include "AST/Components/CExprCall.h" -#include "AST/Components/CExprDeclRef.h" -#include "AST/Components/CExprInputs.h" -#include "AST/Components/CExprOutputs.h" -#include "AST/Components/CExprType.h" #include "AST/Components/CFileRef.h" -#include "AST/Components/CLiteralBool.h" -#include "AST/Components/CLiteralFloating.h" -#include "AST/Components/CLiteralIntegral.h" -#include "AST/Components/CLiteralString.h" #include "AST/Components/CNamespace.h" -#include "AST/Components/CStmtIf.h" -#include "AST/Components/CStmtInput.h" -#include "AST/Components/CStmtOutputs.h" -#include "AST/Components/CStmtReturn.h" +#include "AST/Components/Declarations.h" +#include "AST/Components/Expressions.h" +#include "AST/Components/Literals.h" +#include "AST/Components/Statements.h" #include "AST/Components/Views/CNodePosition.h" #include "AST/Statics/STypes.h" #include "AST/Utils/Namespaces.h" @@ -31,13 +17,11 @@ #include "Rift.h" #include -#include #include -#include -#include +#include -namespace rift::AST +namespace rift::ast { static p::TArray gFileTypes; @@ -61,7 +45,7 @@ namespace rift::AST if (auto* fileType = FindFileType(typeId)) { - ast.AddDefault(fileType->tagType->GetId(), id); + ast.AddDefault(fileType->tagType, id); } } @@ -81,7 +65,7 @@ namespace rift::AST return id; } - void RemoveTypes(TAccessRef, TWrite, CFileRef> access, + void RemoveTypes(p::TAccessRef, TWrite, CFileRef> access, TView typeIds, bool removeFromDisk) { if (removeFromDisk) @@ -90,18 +74,16 @@ namespace rift::AST { if (const auto* file = access.TryGet(id)) { - files::Delete(file->path, true, false); + Delete(file->path, true, false); } } } - p::Remove(access, typeIds, true); + p::RemoveId(access, typeIds, true); } void SerializeType(Tree& ast, Id id, String& data) { - ZoneScoped; - - if (!Ensure(ast.Has(id))) + if (!P_Ensure(ast.Has(id))) { return; } @@ -118,8 +100,6 @@ namespace rift::AST void DeserializeType(Tree& ast, Id id, const String& data) { - ZoneScoped; - JsonFormatReader reader{data}; if (!reader.IsValid()) { @@ -150,22 +130,22 @@ namespace rift::AST return NoId; } - bool IsClassType(const Tree& ast, Id typeId) + bool IsClassType(p::TAccessRef access, Id typeId) { - return ast.Has(typeId); + return access.Has(typeId); } - bool IsStructType(const Tree& ast, Id typeId) + bool IsStructType(p::TAccessRef access, Id typeId) { - return ast.Has(typeId); + return access.Has(typeId); } - bool IsStaticType(const Tree& ast, Id typeId) + bool IsStaticType(p::TAccessRef access, Id typeId) { - return ast.Has(typeId); + return access.Has(typeId); } - bool HasVariables(TAccess access, Id typeId) + bool HasVariables(p::TAccessRef access, Id typeId) { if (const RiftType* fileType = FindFileType(access, typeId)) { @@ -174,7 +154,7 @@ namespace rift::AST return false; } - bool HasFunctions(TAccess access, Id typeId) + bool HasFunctions(p::TAccessRef access, Id typeId) { if (const RiftType* fileType = FindFileType(access, typeId)) { @@ -183,7 +163,7 @@ namespace rift::AST return false; } - bool HasFunctionBodies(TAccess access, Id typeId) + bool HasFunctionBodies(p::TAccessRef access, Id typeId) { if (const RiftType* fileType = FindFileType(access, typeId)) { @@ -203,7 +183,7 @@ namespace rift::AST if (type) { - p::Attach(ast, type, id); + p::AttachId(ast, type, id); } return id; } @@ -219,7 +199,7 @@ namespace rift::AST if (type) { - p::Attach(ast, type, id); + p::AttachId(ast, type, id); } return id; } @@ -236,7 +216,7 @@ namespace rift::AST if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } @@ -247,7 +227,7 @@ namespace rift::AST ast.Add(id, name); ast.Add(id); ast.Add(id); - p::Attach(ast, functionId, id); + p::AttachId(ast, functionId, id); ast.GetOrAdd(functionId).Add(id); return id; } @@ -258,7 +238,7 @@ namespace rift::AST ast.Add(id, name); ast.Add(id); ast.Add(id); - p::Attach(ast, functionId, id); + p::AttachId(ast, functionId, id); ast.GetOrAdd(functionId).Add(id); return id; } @@ -274,17 +254,17 @@ namespace rift::AST const Id valueId = ast.Create(); ast.Add(valueId, {.id = ast.GetNativeTypes().boolId}); ast.Add(id).type = GetNamespace(ast, ast.GetNativeTypes().boolId); - p::Attach(ast, id, valueId); + p::AttachId(ast, id, valueId); ast.Add(id).Add(valueId); TArray outIds(2); ast.Create(outIds); - p::Attach(ast, id, outIds); + p::AttachId(ast, id, outIds); ast.Add(id, Move(outIds)); if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } @@ -297,7 +277,7 @@ namespace rift::AST ast.Add(returnId); if (type) { - p::Attach(ast, type.GetId(), returnId); + p::AttachId(ast, type.GetId(), returnId); } return returnId; } @@ -382,7 +362,7 @@ namespace rift::AST if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } @@ -395,8 +375,8 @@ namespace rift::AST ast.Add(id); ast.Add(id).Add(id); // Types gets resolved by a system later - const Id typeId = p::GetParent(ast, declId); - Check(!IsNone(typeId)); + const Id typeId = p::GetIdParent(ast, declId); + P_Check(!IsNone(typeId)); auto& declRefExpr = ast.Add(id); declRefExpr.ownerName = ast.Get(typeId).name; declRefExpr.name = ast.Get(declId).name; @@ -405,7 +385,7 @@ namespace rift::AST if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } @@ -419,7 +399,7 @@ namespace rift::AST ast.Add(id).Add(id); if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } @@ -434,20 +414,20 @@ namespace rift::AST auto& inputs = ast.Add(id); inputs.Resize(2); ast.Create(inputs.pinIds); - p::Attach(ast, id, inputs.pinIds); + p::AttachId(ast, id, inputs.pinIds); if (type) { - p::Attach(ast, type.GetId(), id); + p::AttachId(ast, type.GetId(), id); } return id; } - Id FindChildByName(TAccessRef access, Id ownerId, Tag functionName) + Id FindChildByName(p::TAccessRef access, Id ownerId, Tag functionName) { if (!IsNone(ownerId)) { TArray children; - p::GetChildren(access, ownerId, children); + p::GetIdChildren(access, ownerId, children); for (Id childId : children) { const auto* ns = access.TryGet(childId); @@ -463,10 +443,11 @@ namespace rift::AST void RemoveNodes(const RemoveAccess& access, TView ids) { ScopedChange(access, ids); - p::Remove(access, ids, true); + p::RemoveId(access, ids, true); } - bool CopyExpressionType(TAccessRef> access, Id sourcePinId, Id targetPinId) + bool CopyExpressionType( + p::TAccessRef> access, Id sourcePinId, Id targetPinId) { auto* sourceType = access.TryGet(sourcePinId); auto* targetType = access.TryGet(targetPinId); @@ -504,16 +485,16 @@ namespace rift::AST const RiftType* FindFileType(p::Tag typeId) { - const i32 index = gFileTypes.FindSortedEqual(typeId); + const i32 index = gFileTypes.FindSorted(typeId); return index != NO_INDEX ? gFileTypes.Data() + index : nullptr; } - const RiftType* FindFileType(p::TAccessRef access, AST::Id typeId) + const RiftType* FindFileType(p::TAccessRef access, ast::Id typeId) { - if (const auto* type = access.TryGet(typeId)) + if (const auto* type = access.TryGet(typeId)) { return FindFileType(type->typeId); } return nullptr; } -} // namespace rift::AST +} // namespace rift::ast diff --git a/Libs/AST/Src/ASTModule.cpp b/Libs/AST/Src/ASTModule.cpp index 39542e49..6a53e31d 100644 --- a/Libs/AST/Src/ASTModule.cpp +++ b/Libs/AST/Src/ASTModule.cpp @@ -1,12 +1,10 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "ASTModule.h" -#include "AST/Components/CDeclClass.h" -#include "AST/Components/CDeclStatic.h" -#include "AST/Components/CDeclStruct.h" #include "AST/Components/CModule.h" #include "AST/Components/CNamespace.h" +#include "AST/Components/Declarations.h" #include "AST/Utils/ModuleUtils.h" #include "AST/Utils/TypeUtils.h" @@ -20,14 +18,14 @@ namespace rift void ASTModule::Load() { - AST::RegisterFileType( + ast::RegisterFileType( structType, {.displayName = "Struct", .hasVariables = true, .hasFunctions = false}); - AST::RegisterFileType( + ast::RegisterFileType( classType, {.displayName = "Class", .hasVariables = true, .hasFunctions = true}); - AST::RegisterFileType( + ast::RegisterFileType( staticType, {.displayName = "Static", .hasVariables = true, .hasFunctions = true}); - AST::PreAllocPools(); + ast::PreAllocPools(); - AST::RegisterSerializedModulePools(); + ast::RegisterSerializedModulePools(); } } // namespace rift diff --git a/Libs/AST/Src/Compiler/Compiler.cpp b/Libs/AST/Src/Compiler/Compiler.cpp index 12734ffd..daaa69c4 100644 --- a/Libs/AST/Src/Compiler/Compiler.cpp +++ b/Libs/AST/Src/Compiler/Compiler.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Compiler/Compiler.h" @@ -15,7 +15,7 @@ namespace rift { - void Compiler::AddError(StringView str) + void Compiler::Error(p::StringView str) { p::Error(str); CompileError newError{}; @@ -24,55 +24,52 @@ namespace rift } - void Build(AST::Tree& ast, const CompilerConfig& config, TPtr backend) + void Build(ast::Tree& ast, const CompilerConfig& config, p::TPtr backend) { - ZoneScoped; Compiler compiler{ast, config}; if (!backend) { - compiler.AddError("Invalid backend."); + compiler.Error("Invalid backend."); return; } + if (!ast::HasProject(ast)) { - ZoneScopedN("Frontend"); - - if (!AST::HasProject(ast)) - { - p::Error("No existing project to build."); - return; - } - compiler.config.Init(ast); - - if (auto* nativeBindings = GetModule().Get()) - { - p::Info("Interpret native modules"); - nativeBindings->SyncIncludes(ast); - } - - p::Info("Loading files"); - AST::LoadSystem::Run(ast); - - OptimizationSystem::PruneDisconnectedExpressions(ast); - AST::TypeSystem::PropagateVariableTypes(ast); - AST::TypeSystem::PropagateExpressionTypes(ast); + p::Error("No existing project to build."); + return; + } + + compiler.config.Init(ast); + + if (auto* nativeBindings = GetModule().Get()) + { + p::Info("Interpret native modules"); + nativeBindings->SyncIncludes(ast); } - p::Info("Building project '{}'", AST::GetProjectName(compiler.ast)); + p::Info("Loading files"); + ast::LoadSystem::Run(ast); + + OptimizationSystem::PruneDisconnectedExpressions(ast); + ast::TypeSystem::PropagateVariableTypes(ast); + ast::TypeSystem::PropagateExpressionTypes(ast); + + + p::Info("Building project '{}'", ast::GetProjectName(compiler.ast)); // Clean build folders p::Info("Cleaning previous build"); - files::Delete(compiler.config.binariesPath, true, false); - files::CreateFolder(compiler.config.binariesPath, true); + Delete(compiler.config.binariesPath, true, false); + CreateFolder(compiler.config.binariesPath, true); backend->Build(compiler); } - void Build(AST::Tree& ast, const CompilerConfig& config, ClassType* backendType) + void Build(ast::Tree& ast, const CompilerConfig& config, p::TypeId backendType) { - if (backendType) + if (backendType.IsValid()) { - TOwnPtr backend = MakeOwned(backendType); + p::TOwnPtr backend = p::MakeOwned(backendType); Build(ast, config, backend); } } diff --git a/Libs/AST/Src/Compiler/CompilerConfig.cpp b/Libs/AST/Src/Compiler/CompilerConfig.cpp index adb688be..c195e6c7 100644 --- a/Libs/AST/Src/Compiler/CompilerConfig.cpp +++ b/Libs/AST/Src/Compiler/CompilerConfig.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Compiler/CompilerConfig.h" @@ -7,10 +7,10 @@ namespace rift { - void CompilerConfig::Init(AST::Tree& ast) + void CompilerConfig::Init(ast::Tree& ast) { - buildPath = p::JoinPaths(AST::GetProjectPath(ast), "Build"); - intermediatesPath = buildPath / "Intermediates"; - binariesPath = buildPath / buildMode; + buildPath = p::JoinPaths(ast::GetProjectPath(ast), "Build"); + intermediatesPath = p::JoinPaths(buildPath, "Intermediates"); + binariesPath = p::JoinPaths(buildPath, "Binaries"); } } // namespace rift diff --git a/Libs/AST/Src/Compiler/Systems/OptimizationSystem.cpp b/Libs/AST/Src/Compiler/Systems/OptimizationSystem.cpp index 1e2a666b..35ea25eb 100644 --- a/Libs/AST/Src/Compiler/Systems/OptimizationSystem.cpp +++ b/Libs/AST/Src/Compiler/Systems/OptimizationSystem.cpp @@ -1,16 +1,16 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Compiler/Systems/OptimizationSystem.h" namespace rift::OptimizationSystem { - void PruneDisconnectedStatements(AST::Tree& ast) + void PruneDisconnectedStatements(ast::Tree& ast) { // TODO } - void PruneDisconnectedExpressions(AST::Tree& ast) + void PruneDisconnectedExpressions(ast::Tree& ast) { // TODO } diff --git a/Libs/AST/Src/Compiler/Utils/BackendUtils.cpp b/Libs/AST/Src/Compiler/Utils/BackendUtils.cpp index 4119a47f..e8eb64e6 100644 --- a/Libs/AST/Src/Compiler/Utils/BackendUtils.cpp +++ b/Libs/AST/Src/Compiler/Utils/BackendUtils.cpp @@ -1,28 +1,29 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Compiler/Utils/BackendUtils.h" +#include "PipeReflect.h" + namespace rift { - TArray GetBackendTypes() + p::TArray GetBackendTypes() { - TArray types = Backend::GetStaticType()->GetChildren(); - types.RemoveIf([](ClassType* type) { - return !type || type->HasFlag(Class_Abstract); + p::TArray types; // = Backend::GetStaticType()->GetChildren(); + types.RemoveIf([](p::TypeId type) { + return !type.IsValid() || p::HasTypeFlags(type, p::TF_Abstract); }); return Move(types); } - TArray> CreateBackends() + p::TArray> CreateBackends() { - TArray> backends; - + p::TArray> backends; auto types = GetBackendTypes(); backends.Reserve(types.Size()); - for (auto* type : types) + for (p::TypeId type : types) { - backends.Add(MakeOwned(type)); + backends.Add(p::MakeOwned(type)); } return Move(backends); } diff --git a/Libs/AST/Src/Module.cpp b/Libs/AST/Src/Module.cpp index 32bbff30..212a4ba4 100644 --- a/Libs/AST/Src/Module.cpp +++ b/Libs/AST/Src/Module.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Module.h" diff --git a/Libs/AST/Src/Rift.cpp b/Libs/AST/Src/Rift.cpp index c475a62c..335a0874 100644 --- a/Libs/AST/Src/Rift.cpp +++ b/Libs/AST/Src/Rift.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Rift.h" @@ -7,13 +7,13 @@ namespace rift { - static p::TMap> gModules{}; + static p::TMap> gModules{}; static p::TArray gViews{}; - void EnableModule(p::ClassType* type) + void EnableModule(p::TypeId type) { - Check(Module::GetStaticType()->IsParentOf(type)); + P_Check(IsTypeParentOf(GetTypeId(), type)); if (!gModules.Contains(type)) { @@ -23,12 +23,12 @@ namespace rift } } - void DisableModule(p::ClassType* type) + void DisableModule(p::TypeId type) { gModules.Remove(type); } - p::TPtr GetModule(p::ClassType* type) + p::TPtr GetModule(p::TypeId type) { if (auto* module = gModules.Find(type)) { diff --git a/Libs/Backends/LLVM/CMakeLists.txt b/Libs/Backends/LLVM/CMakeLists.txt deleted file mode 100644 index 8b0f9de6..00000000 --- a/Libs/Backends/LLVM/CMakeLists.txt +++ /dev/null @@ -1,32 +0,0 @@ -# Copyright 2015-2023 Piperift - All rights reserved - -add_library(RiftBackendLLVM STATIC) -rift_compiler_module(RiftBackendLLVM) - -target_link_libraries(RiftBackendLLVM PUBLIC RiftAST) -target_link_libraries(RiftBackendLLVM PRIVATE - RiftLLVM - RiftBindingNative -) - - -# LLVM linker -if (PLATFORM_WINDOWS) - set(RIFT_LLVM_LINKER lld-link.exe) -elseif(PLATFORM_LINUX) - set(RIFT_LLVM_LINKER ld.lld) -elseif(PLATFORM_MACOS) - set(RIFT_LLVM_LINKER ld64.lld) -endif() - -set(RIFT_LLVM_LINKER_PATH LLVM/${RIFT_LLVM_LINKER}) - -target_compile_definitions(RiftBackendLLVM PRIVATE RIFT_LLVM_LINKER="${RIFT_LLVM_LINKER}" RIFT_LLVM_LINKER_PATH="${RIFT_LLVM_LINKER_PATH}") - -add_custom_command(TARGET RiftBackendLLVM POST_BUILD COMMAND - ${CMAKE_COMMAND} -E remove_directory "${CMAKE_BINARY_DIR}/Bin/LLVM" -) -add_custom_command(TARGET RiftBackendLLVM POST_BUILD COMMAND - ${CMAKE_COMMAND} -E copy "${RIFT_LLVM_BIN_PATH}/bin/${RIFT_LLVM_LINKER}" "${CMAKE_BINARY_DIR}/Bin/LLVM/${RIFT_LLVM_LINKER}" -) - diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRFunction.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRFunction.h deleted file mode 100644 index 4659c790..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRFunction.h +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include -#include - - -namespace rift -{ - struct CIRFunction : public p::Struct - { - STRUCT(CIRFunction, p::Struct) - - llvm::Function* instance = nullptr; - - p::TArray inputs; - p::TArray inputIds; - - - CIRFunction() {} - }; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRInstruction.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRInstruction.h deleted file mode 100644 index 1329c6c3..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRInstruction.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include - - -namespace rift -{ - struct CIRInstruction : public p::Struct - { - STRUCT(CIRInstruction, p::Struct) - - llvm::Instruction* instance = nullptr; - - - CIRInstruction(llvm::Instruction* instance) : instance(instance) {} - }; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRModule.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRModule.h deleted file mode 100644 index f72e3a99..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRModule.h +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include - - -namespace rift -{ - struct CIRModule : public p::Struct - { - STRUCT(CIRModule, p::Struct) - - p::TOwnPtr instance; - - p::String objectFile; - }; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRType.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRType.h deleted file mode 100644 index 8fbb8118..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRType.h +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include - - -namespace rift -{ - using CIRType = llvm::Type*; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRValue.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRValue.h deleted file mode 100644 index ce142b53..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Components/CIRValue.h +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include - - -namespace rift -{ - using CIRValue = llvm::Value*; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/IRGeneration.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/IRGeneration.h deleted file mode 100644 index 8e565269..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/IRGeneration.h +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "LLVMBackend/Components/CIRFunction.h" -#include "LLVMBackend/Components/CIRModule.h" -#include "LLVMBackend/Components/CIRType.h" -#include "LLVMBackend/Components/CIRValue.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace rift -{ - struct CIRFunction; -} - -namespace rift -{ - struct Compiler; -} - -namespace rift::LLVM -{ - // Defines a single ecs access dfor the entire IR generation - using IRAccess = p::TAccessRef, p::TWrite, p::TWrite, AST::CLiteralBool, - AST::CLiteralIntegral, AST::CLiteralFloating, AST::CLiteralString>; - - struct ModuleIRGen - { - Compiler& compiler; - llvm::Module& module; - llvm::LLVMContext& llvm; - llvm::IRBuilder<>& builder; - }; - - void GenerateIR(Compiler& compiler, llvm::LLVMContext& llvm, llvm::IRBuilder<>& builder); - - void GenerateIRModule(Compiler& compiler, IRAccess access, AST::Id moduleId, - llvm::LLVMContext& llvm, llvm::IRBuilder<>& builder); - - void BindNativeTypes(llvm::LLVMContext& llvm, IRAccess access); - void GenerateLiterals(llvm::LLVMContext& llvm, IRAccess access); - - void DeclareStructs(ModuleIRGen& gen, IRAccess access, p::TView ids); - void DefineStructs(ModuleIRGen& gen, IRAccess access, p::TView ids); - void DeclareFunctions( - ModuleIRGen& gen, IRAccess access, p::TView ids, bool useFullName = true); - void DefineFunctions(ModuleIRGen& gen, IRAccess access, p::TView ids); - - void AddStmtBlock(ModuleIRGen& gen, IRAccess access, AST::Id firstStmtId, - llvm::BasicBlock* block, const CIRFunction& function); - llvm::Value* AddExpr(ModuleIRGen& gen, IRAccess access, const AST::ExprOutput& output); - llvm::BasicBlock* AddIf( - ModuleIRGen& gen, IRAccess access, AST::Id id, const CIRFunction& function); - void AddCall(ModuleIRGen& gen, AST::Id id, const AST::CExprCallId& call, IRAccess access); - - - AST::Id FindMainFunction(IRAccess access, p::TView functionIds); - - void CreateMain(ModuleIRGen& gen, IRAccess access, AST::Id functionId); -} // namespace rift::LLVM diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/LLVMHelpers.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/LLVMHelpers.h deleted file mode 100644 index 58e5ec19..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/LLVMHelpers.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include -#include -#include -#include - - -namespace rift::LLVM -{ - using namespace p::core; - - inline llvm::StringRef ToLLVM(p::StringView string) - { - return {string.data(), string.size()}; - } - inline llvm::StringRef ToLLVM(const p::String& string) - { - return ToLLVM(p::StringView{string}); - } - inline llvm::StringRef ToLLVM(p::Tag name) - { - return ToLLVM(p::StringView{name.AsString()}); - } - - template - inline llvm::ArrayRef ToLLVM(const p::IArray& array) - { - return {array.Data(), sizet(array.Size())}; - } -} // namespace rift::LLVM diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Linker.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Linker.h deleted file mode 100644 index 440ef013..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackend/Linker.h +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include "Compiler/Compiler.h" - - -namespace rift::LLVM -{ - void Link(Compiler& compiler); -} // namespace rift::LLVM \ No newline at end of file diff --git a/Libs/Backends/LLVM/Compiler/Include/LLVMBackendModule.h b/Libs/Backends/LLVM/Compiler/Include/LLVMBackendModule.h deleted file mode 100644 index 388c295b..00000000 --- a/Libs/Backends/LLVM/Compiler/Include/LLVMBackendModule.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include -#include - - -namespace rift -{ - class LLVMBackendModule : public Module - { - CLASS(LLVMBackendModule, Module) - - public: - LLVMBackendModule(); - }; - - - class LLVMBackend : public Backend - { - CLASS(LLVMBackend, Backend) - - public: - Tag GetName() override - { - return "LLVM"; - } - - void Build(Compiler& compiler) override; - }; -} // namespace rift diff --git a/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/IRGeneration.cpp b/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/IRGeneration.cpp deleted file mode 100644 index a1bfd59b..00000000 --- a/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/IRGeneration.cpp +++ /dev/null @@ -1,416 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved - -#include "LLVMBackend/IRGeneration.h" - -#include "Components/CDeclCStruct.h" -#include "LLVMBackend/Components/CIRFunction.h" -#include "LLVMBackend/LLVMHelpers.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace rift::LLVM -{ - void GenerateIR(Compiler& compiler, llvm::LLVMContext& llvm, llvm::IRBuilder<>& builder) - { - IRAccess access{compiler.ast}; - BindNativeTypes(llvm, access); - GenerateLiterals(llvm, access); - - for (AST::Id moduleId : FindAllIdsWith(access)) - { - GenerateIRModule(compiler, access, moduleId, llvm, builder); - } - } - - void GenerateIRModule(Compiler& compiler, IRAccess access, AST::Id moduleId, - llvm::LLVMContext& llvm, llvm::IRBuilder<>& builder) - { - ZoneScoped; - auto& ast = compiler.ast; - - const Tag name = AST::GetModuleName(compiler.ast, moduleId); - - const auto& module = compiler.ast.Get(moduleId); - CIRModule& irModule = compiler.ast.Add(moduleId); - irModule.instance = MakeOwned(ToLLVM(name), llvm); - - ModuleIRGen gen{compiler, *irModule.instance.Get(), llvm, builder}; - - AST::Id mainFunctionId = AST::NoId; - - // Get all rift types from the module - TArray typeIds; - GetChildren(ast, moduleId, typeIds); - ExcludeIdsWithout(ast, typeIds); - - { // Native declarations - TArray cStructIds = FindIdsWith(ast, typeIds); - TArray cStaticIds = FindIdsWith(ast, typeIds); - TArray cFunctionIds; - p::GetChildren(ast, cStaticIds, cFunctionIds); - ExcludeIdsWithout(ast, cFunctionIds); - DeclareStructs(gen, ast, cStructIds); - DeclareFunctions(gen, ast, cFunctionIds, false); - } - - TArray staticFunctionIds; - { // Rift declarations & definitions - TArray structIds = FindIdsWith(ast, typeIds); - TArray staticIds = FindIdsWith(ast, typeIds); - TArray classIds = FindIdsWith(ast, typeIds); - TArray classFunctionIds; - p::GetChildren(ast, staticIds, staticFunctionIds); - p::GetChildren(ast, classIds, classFunctionIds); - ExcludeIdsWithout(ast, staticFunctionIds); - ExcludeIdsWithout(ast, classFunctionIds); - TArray functionIds; - functionIds.Append(staticFunctionIds); - functionIds.Append(classFunctionIds); - - DeclareStructs(gen, ast, structIds); - DeclareStructs(gen, ast, classIds); - DeclareFunctions(gen, ast, functionIds); - - DefineStructs(gen, ast, structIds); - DefineStructs(gen, ast, classIds); - DefineFunctions(gen, ast, functionIds); - } - - if (module.target == AST::RiftModuleTarget::Executable) - { - mainFunctionId = FindMainFunction(access, staticFunctionIds); - CreateMain(gen, access, mainFunctionId); - } - } - - - void BindNativeTypes(llvm::LLVMContext& llvm, IRAccess access) - { - const auto& nativeTypes = static_cast(access.GetContext()).GetNativeTypes(); - access.Add(nativeTypes.boolId, CIRType{llvm::Type::getInt8Ty(llvm)}); - access.Add(nativeTypes.floatId, CIRType{llvm::Type::getFloatTy(llvm)}); - access.Add(nativeTypes.doubleId, CIRType{llvm::Type::getDoubleTy(llvm)}); - access.Add(nativeTypes.u8Id, CIRType{llvm::Type::getInt8Ty(llvm)}); - access.Add(nativeTypes.i8Id, CIRType{llvm::Type::getInt8Ty(llvm)}); - access.Add(nativeTypes.u16Id, CIRType{llvm::Type::getInt16Ty(llvm)}); - access.Add(nativeTypes.i16Id, CIRType{llvm::Type::getInt16Ty(llvm)}); - access.Add(nativeTypes.u32Id, CIRType{llvm::Type::getInt32Ty(llvm)}); - access.Add(nativeTypes.i32Id, CIRType{llvm::Type::getInt32Ty(llvm)}); - access.Add(nativeTypes.u64Id, CIRType{llvm::Type::getInt64Ty(llvm)}); - access.Add(nativeTypes.i64Id, CIRType{llvm::Type::getInt64Ty(llvm)}); - // access.Add(nativeTypes.stringId, {}); - } - - void GenerateLiterals(llvm::LLVMContext& llvm, IRAccess access) - { - for (AST::Id id : FindAllIdsWith(access)) - { - const auto& boolean = access.Get(id); - llvm::Value* value = llvm::ConstantInt::get(llvm, llvm::APInt(1, boolean.value, true)); - access.Add(id, CIRValue{value}); - } - for (AST::Id id : FindAllIdsWith(access)) - { - const auto& integral = access.Get(id); - llvm::Value* value = llvm::ConstantInt::get( - llvm, llvm::APInt(integral.GetSize(), integral.value, integral.IsSigned())); - access.Add(id, CIRValue{value}); - } - for (AST::Id id : FindAllIdsWith(access)) - { - const auto& floating = access.Get(id); - llvm::Value* value = - llvm::ConstantFP::get(llvm, llvm::APFloat(floating.type == AST::FloatingType::F32 - ? static_cast(floating.value) - : floating.value)); - access.Add(id, CIRValue{value}); - } - for (AST::Id id : FindAllIdsWith(access)) - { - const auto& string = access.Get(id); - access.Add( - id, CIRValue{llvm::ConstantDataArray::getString(llvm, ToLLVM(string.value))}); - } - } - - void DeclareStructs(ModuleIRGen& gen, IRAccess access, TView ids) - { - ZoneScoped; - for (AST::Id id : ids) - { - p::String name = AST::GetFullName(access, id); - access.Add(id, CIRType{llvm::StructType::create(gen.llvm, ToLLVM(name))}); - } - } - - void DefineStructs(ModuleIRGen& gen, IRAccess access, TView ids) - { - ZoneScoped; - TArray memberIds; - TArray memberTypes; - for (AST::Id id : ids) - { - auto* irStruct = static_cast(access.Get(id)); - - // Add members - memberIds.Clear(false); - memberTypes.Clear(false); - p::GetChildren(access, id, memberIds); - ExcludeIdsWithout(access, memberIds); - for (AST::Id memberId : memberIds) - { - const auto& var = access.Get(memberId); - if (auto* irType = access.TryGet(var.typeId)) - { - memberTypes.Add(*irType); - } - else - { - const Tag memberName = AST::GetName(access, memberId); - const Tag typeName = AST::GetName(access, id); - gen.compiler.AddError(Strings::Format( - "Variable '{}' in struct '{}' has an invalid type", memberName, typeName)); - } - } - irStruct->setBody(ToLLVM(memberTypes)); - } - } - - void DeclareFunctions(ModuleIRGen& gen, IRAccess access, TView ids, bool useFullName) - { - ZoneScoped; - TArray inputIds; - TArray inputTypes; - for (AST::Id id : ids) - { - auto& functionComp = access.Add(id); - - inputIds.Clear(false); - inputTypes.Clear(false); - if (auto* outputs = access.TryGet(id)) - { - for (i32 i = 0; i < outputs->pinIds.Size(); ++i) - { - AST::Id inputId = outputs->pinIds[i]; - if (access.Has(inputId)) - { - continue; - } - - inputIds.Add(inputId); - - AST::Id typeId = access.Get(inputId).id; - auto* irType = access.TryGet(typeId); - if (irType && *irType) - { - inputTypes.Add(*irType); - } - else - { - const Tag argName = AST::GetName(access, inputId); - const String functionName = AST::GetFullName(access, id); - gen.compiler.AddError(Strings::Format( - "Input '{}' in function '{}' has an invalid type. Using i32 instead.", - argName, functionName)); - inputTypes.Add(gen.builder.getInt32Ty()); - } - } - } - - // Create function - p::String name = useFullName ? AST::GetFullName(access, id) - : p::String{AST::GetName(access, id).AsString()}; - auto* functionType = - llvm::FunctionType::get(gen.builder.getVoidTy(), ToLLVM(inputTypes), false); - functionComp.instance = llvm::Function::Create( - functionType, llvm::Function::ExternalLinkage, ToLLVM(name), &gen.module); - - // Set argument names - i32 i = 0; - const auto& args = functionComp.instance->args(); - for (auto& arg : args) - { - Tag name = AST::GetName(access, inputIds[i++]); - arg.setName(ToLLVM(name)); - } - - // Cache final inputs - functionComp.inputs = {args.begin(), args.end()}; - functionComp.inputIds = inputIds; - inputIds.Clear(false); - inputTypes.Clear(false); - } - } - - void DefineFunctions(ModuleIRGen& gen, IRAccess access, TView ids) - { - ZoneScoped; - for (AST::Id id : ids) - { - const auto& irFunction = access.Get(id); - auto* block = llvm::BasicBlock::Create(gen.llvm, "entry", irFunction.instance); - - const auto& output = access.Get(id); - AddStmtBlock(gen, access, output.linkInputNode, block, irFunction); - - // Generate default return - gen.builder.CreateRet(nullptr); - - verifyFunction(*irFunction.instance); - } - } - - void AddStmtBlock(ModuleIRGen& gen, IRAccess access, AST::Id firstStmtId, - llvm::BasicBlock* block, const CIRFunction& function) - { - ZoneScoped; - gen.builder.SetInsertPoint(block); - - AST::Id splitId = AST::NoId; - TArray stmtIds; - AST::GetStmtChain(access, firstStmtId, stmtIds, splitId); - - for (AST::Id id : stmtIds) - { - if (const auto* call = access.TryGet(id)) - { - AddCall(gen, id, *call, access); - } - } - - if (splitId != AST::NoId) - { - if (access.Has(splitId)) - { - AddIf(gen, access, splitId, function); - } - } - // TODO: Resolve continuation block and generate it - } - - llvm::Value* AddExpr(ModuleIRGen& gen, IRAccess access, const AST::ExprOutput& output) - { - const auto* value = - !IsNone(output.pinId) ? access.TryGet(output.pinId) : nullptr; - if (value) - { - return *value; - } - return nullptr; - } - - llvm::BasicBlock* AddIf( - ModuleIRGen& gen, IRAccess access, AST::Id id, const CIRFunction& function) - { - const auto& outputs = access.Get(id); - const auto& connectedIds = outputs.linkInputNodes; - Check(connectedIds.Size() == 2); - const auto& exprInputs = access.Get(id); - Check(exprInputs.linkedOutputs.Size() == 1); - - llvm::Value* condV = AddExpr(gen, access, exprInputs.linkedOutputs.First()); - if (!condV) - { - // Assign false by default - condV = llvm::ConstantInt::get(gen.llvm, llvm::APInt(1, false, true)); - } - - auto* thenBlock = llvm::BasicBlock::Create(gen.llvm, "then"); - auto* elseBlock = llvm::BasicBlock::Create(gen.llvm, "else"); - auto* contBlock = llvm::BasicBlock::Create(gen.llvm, "continue"); - gen.builder.CreateCondBr(condV, thenBlock, elseBlock); - - function.instance->getBasicBlockList().push_back(thenBlock); - AddStmtBlock(gen, access, connectedIds[0], thenBlock, function); - gen.builder.CreateBr(contBlock); - - function.instance->getBasicBlockList().push_back(elseBlock); - AddStmtBlock(gen, access, connectedIds[1], elseBlock, function); - gen.builder.CreateBr(contBlock); - - function.instance->getBasicBlockList().push_back(contBlock); - return contBlock; - } - - void AddCall(ModuleIRGen& gen, AST::Id id, const AST::CExprCallId& call, IRAccess access) - { - const AST::Id functionId = call.functionId; - if (!access.IsValid(functionId)) - { - gen.compiler.AddError("Call to an unknown function"); - return; - } - const auto* function = access.TryGet(functionId); - if (!Ensure(function)) - { - gen.compiler.AddError(Strings::Format( - "Call to an invalid function: '{}'", AST::GetName(access, functionId))); - return; - } - - TArray args; - if (auto* inputs = access.TryGet(id)) - { - args.Reserve(inputs->linkedOutputs.Size()); - for (i32 i = 0; i < inputs->linkedOutputs.Size(); ++i) - { - AST::ExprOutput output = inputs->linkedOutputs[i]; - if (!output.IsNone()) - { - args.Add(AddExpr(gen, access, output)); - } - } - } - gen.builder.CreateCall(function->instance, ToLLVM(args)); - } - - - AST::Id FindMainFunction(IRAccess access, p::TView functionIds) - { - static const p::Tag mainFunctionName{"Main"}; - - for (AST::Id id : functionIds) - { - const auto* ns = access.TryGet(id); - if (ns && ns->name == mainFunctionName) - { - return id; - } - } - return AST::NoId; - } - - void CreateMain(ModuleIRGen& gen, IRAccess access, AST::Id functionId) - { - if (p::IsNone(functionId)) - { - gen.compiler.AddError( - Strings::Format("Module is executable but has no \"Main\" function")); - return; - } - - auto* customMainFunction = access.Get(functionId).instance; - - auto* mainType = llvm::FunctionType::get(gen.builder.getInt32Ty(), false); - auto* function = - llvm::Function::Create(mainType, llvm::Function::ExternalLinkage, "Main", &gen.module); - - - auto* entry = llvm::BasicBlock::Create(gen.llvm, "entry", function); - gen.builder.SetInsertPoint(entry); - gen.builder.CreateCall(customMainFunction); - - gen.builder.CreateRet(llvm::ConstantInt::get(gen.llvm, llvm::APInt(32, 0))); - } -} // namespace rift::LLVM diff --git a/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/Linker.cpp b/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/Linker.cpp deleted file mode 100644 index a9dfa21b..00000000 --- a/Libs/Backends/LLVM/Compiler/Src/LLVMBackend/Linker.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved - -#include "LLVMBackend/Linker.h" - -#include "Components/CNativeBinding.h" -#include "LLVMBackend/Components/CIRModule.h" -#include "Pipe/Core/PlatformProcess.h" -#include "Pipe/Core/String.h" - -#include -#include -#include -#include -#include -#include -#include -#include - - -namespace rift::LLVM -{ - void Link(Compiler& compiler) - { - String linkerPath{ - p::JoinPaths(PlatformProcess::GetExecutablePath(), RIFT_LLVM_LINKER_PATH)}; - - for (AST::Id moduleId : FindAllIdsWith(compiler.ast)) - { - p::Tag moduleName = AST::GetModuleName(compiler.ast, moduleId); - const auto& module = compiler.ast.Get(moduleId); - auto& irModule = compiler.ast.Get(moduleId); - if (p::files::Exists(irModule.objectFile)) - { - TArray command; - command.Add(linkerPath.c_str()); - - const char* extension = nullptr; - switch (module.target) - { - case AST::RiftModuleTarget::Executable: - command.Add("/entry:Main"); - command.Add("/subsystem:console"); - extension = "exe"; - break; - case AST::RiftModuleTarget::Shared: - command.Add("/dll"); - extension = "dll"; - break; - case AST::RiftModuleTarget::Static: - command.Add("/lib"); - extension = "lib"; - break; - } - - p::Path filePath = - compiler.config.binariesPath / Strings::Format("{}.{}", moduleName, extension); - String outParam = Strings::Format("/out:{}", p::ToString(filePath)); - p::Info("Linking '{}' from '{}'", p::ToString(filePath), irModule.objectFile); - - // Native Bindings - p::TArray binaryPaths; - if (auto* cBinding = compiler.ast.TryGet(moduleId)) - { - p::StringView modulePath = AST::GetModulePath(compiler.ast, moduleId); - p::String binaryPath; - for (const auto& nativeBinary : cBinding->binaries) - { - binaryPaths.Add(p::JoinPaths(modulePath, nativeBinary)); - command.Add(binaryPaths.Last().c_str()); - p::Info(" and '{}'", binaryPaths.Last().c_str()); - } - } - command.Add(irModule.objectFile.data()); - command.Add(outParam.data()); - - auto process = p::RunProcess(command, - SubprocessOptions::TerminateIfDestroyed | SubprocessOptions::CombinedOutErr); - i32 returnCode = 0; - p::WaitProcess(process.TryGet(), &returnCode); - if (returnCode != 0) - { - compiler.AddError("Linking failed"); - } - } - } - } -} // namespace rift::LLVM diff --git a/Libs/Backends/LLVM/Compiler/Src/LLVMBackendModule.cpp b/Libs/Backends/LLVM/Compiler/Src/LLVMBackendModule.cpp deleted file mode 100644 index ce8ee5b9..00000000 --- a/Libs/Backends/LLVM/Compiler/Src/LLVMBackendModule.cpp +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved - -#include "LLVMBackendModule.h" - -#include "LLVMBackend/Components/CIRModule.h" -#include "LLVMBackend/IRGeneration.h" -#include "LLVMBackend/Linker.h" -#include "LLVMBackend/LLVMHelpers.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#if LLVM_VERSION_MAJOR >= 14 -# include -#else -# include -#endif -#include -#include -#include -#include -#include - - -namespace rift -{ - LLVMBackendModule::LLVMBackendModule() - { - AddDependency(); - } - - namespace LLVM - { - void SaveModuleObject(Compiler& compiler, AST::Id moduleId, - llvm::TargetMachine* targetMachine, StringView targetTriple) - { - ZoneScoped; - - p::String intermediatesPath = p::ToString(compiler.config.intermediatesPath); - // files::Delete(intermediatesPath, true, false); - files::CreateFolder(intermediatesPath, true); - - auto& irModule = compiler.ast.Get(moduleId); - irModule.objectFile = Strings::Format( - "{}/{}.o", intermediatesPath, AST::GetModuleName(compiler.ast, moduleId)); - p::Info("Creating object '{}'", irModule.objectFile); - - irModule.instance->setTargetTriple(ToLLVM(targetTriple)); - irModule.instance->setDataLayout(targetMachine->createDataLayout()); - - std::error_code ec; - llvm::raw_fd_ostream file(ToLLVM(irModule.objectFile), ec, llvm::sys::fs::OF_None); - if (ec) - { - compiler.AddError( - Strings::Format("Could not open new object file: {}", ec.message())); - irModule.objectFile = {}; // File not saved - return; - } - - llvm::legacy::PassManager pm; - if (targetMachine->addPassesToEmitFile(pm, file, nullptr, llvm::CGFT_ObjectFile)) - { - compiler.AddError("Target machine can't emit a file of this type"); - irModule.objectFile = {}; // File not saved - return; - } - - pm.run(*irModule.instance.Get()); - file.flush(); - } - - void CompileIR(Compiler& compiler, llvm::LLVMContext& llvm, llvm::IRBuilder<>& builder) - { - ZoneScoped; - llvm::InitializeNativeTarget(); - llvm::InitializeNativeTargetAsmParser(); - llvm::InitializeNativeTargetAsmPrinter(); - std::string targetTriple = llvm::sys::getDefaultTargetTriple(); - - std::string error; - const llvm::Target* target = llvm::TargetRegistry::lookupTarget(targetTriple, error); - if (!target) - { - compiler.AddError(error); - return; - } - - llvm::TargetOptions options; - auto* targetMachine = target->createTargetMachine( - targetTriple, "generic", "", options, llvm::Optional()); - - // Emit LLVM IR to console - for (AST::Id moduleId : FindAllIdsWith(compiler.ast)) - { - const auto& irModule = compiler.ast.Get(moduleId).instance; - irModule->print(llvm::outs(), nullptr); - } - - for (AST::Id moduleId : FindAllIdsWith(compiler.ast)) - { - LLVM::SaveModuleObject(compiler, moduleId, targetMachine, targetTriple); - } - } - } // namespace LLVM - - void LLVMBackend::Build(Compiler& compiler) - { - ZoneScopedN("Backend: LLVM"); - - llvm::LLVMContext llvm; - llvm::IRBuilder<> builder(llvm); - - p::Info("Generating LLVM IR"); - LLVM::GenerateIR(compiler, llvm, builder); - if (compiler.HasErrors()) - return; // TODO: Report errors here - - p::Info("Build IR"); - LLVM::CompileIR(compiler, llvm, builder); - if (compiler.HasErrors()) - return; // TODO: Report errors here - - LLVM::Link(compiler); - - compiler.ast.ClearPool(); - - if (!compiler.HasErrors()) - { - p::Info("Build complete."); - } - else - { - p::Info("Build failed: {} errors", compiler.GetErrors().Size()); - } - } -} // namespace rift \ No newline at end of file diff --git a/Libs/Backends/MIR/CMakeLists.txt b/Libs/Backends/MIR/CMakeLists.txt index c2798038..4363c9c9 100644 --- a/Libs/Backends/MIR/CMakeLists.txt +++ b/Libs/Backends/MIR/CMakeLists.txt @@ -1,11 +1,6 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftBackendMIR STATIC) -rift_compiler_module(RiftBackendMIR) - -target_link_libraries(RiftBackendMIR PUBLIC RiftAST) -target_link_libraries(RiftBackendMIR PRIVATE - mir_static - RiftBindingNative -) - +add_library(RiftBackendMIRLib STATIC) +target_link_libraries(RiftBackendMIRLib PUBLIC RiftASTLib) +target_link_libraries(RiftBackendMIRLib PRIVATE RiftBindingNativeLib mir) +rift_compiler_module(RiftBackendMIRLib) diff --git a/Libs/Backends/MIR/Compiler/Include/MIRBackendModule.h b/Libs/Backends/MIR/Compiler/Include/MIRBackendModule.h index 9be89901..7def1abf 100644 --- a/Libs/Backends/MIR/Compiler/Include/MIRBackendModule.h +++ b/Libs/Backends/MIR/Compiler/Include/MIRBackendModule.h @@ -1,15 +1,21 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include #include +struct MIR_context; +struct c2mir_options; + namespace rift { + struct Input; class MIRBackendModule : public Module { - CLASS(MIRBackendModule, Module) + public: + using Super = Module; + P_CLASS(MIRBackendModule) public: MIRBackendModule(); @@ -18,7 +24,9 @@ namespace rift class MIRBackend : public Backend { - CLASS(MIRBackend, Backend) + public: + using Super = Backend; + P_CLASS(MIRBackend) public: Tag GetName() override @@ -27,5 +35,7 @@ namespace rift } void Build(Compiler& compiler) override; + + void PrintBuildFinish(Compiler& compiler) const; }; } // namespace rift diff --git a/Libs/Backends/MIR/Compiler/Src/C2MIR.cpp b/Libs/Backends/MIR/Compiler/Src/C2MIR.cpp new file mode 100644 index 00000000..2df9cac2 --- /dev/null +++ b/Libs/Backends/MIR/Compiler/Src/C2MIR.cpp @@ -0,0 +1,100 @@ +// Copyright 2015-2024 Piperift - All rights reserved + +#include "C2MIR.h" + +#include +#include +extern "C" +{ +#include +} + +namespace rift::MIR +{ + struct OptionsData + { + p::TArray headers; + p::TArray definitions; + }; + + void InitCToMIROptions( + const CompilerConfig& config, OptionsData& optionsData, c2mir_options& options) + { + // Fill defaults + options.message_file = stderr; + options.debug_p = false; + options.verbose_p = false; + options.ignore_warnings_p = false; + options.no_prepro_p = false; + options.prepro_only_p = false; + options.syntax_only_p = false; + options.pedantic_p = false; + options.asm_p = false; + options.object_p = false; + options.module_num = 0; + options.prepro_output_file = nullptr; + options.output_file_name = nullptr; + + options.macro_commands_num = 0; + options.macro_commands = nullptr; + + options.include_dirs_num = 0; + options.include_dirs = nullptr; + + // Fill from config + // options.debug_p = config.debug; + options.verbose_p = config.verbose; + + if (options.output_file_name == nullptr && options.prepro_only_p) + { + options.prepro_output_file = stdout; + } + + // TODO: Fill headers. No headers needed for now + // TODO: Fill definitions. No definitions needed for now + + options.include_dirs_num = optionsData.headers.Size(); + options.include_dirs = optionsData.headers.Data(); + options.macro_commands_num = optionsData.definitions.Size(); + options.macro_commands = optionsData.definitions.Data(); + } + + void CToMIR(Compiler& compiler, MIR_context* ctx) + { + c2mir_init(ctx); + + auto moduleIds = p::FindAllIdsWith(compiler.ast); + + OptionsData optionsData; + c2mir_options options; + InitCToMIROptions(compiler.config, optionsData, options); + + for (ast::Id moduleId : moduleIds) + { + p::Tag name = ast::GetModuleName(compiler.ast, moduleId); + auto& mirModule = compiler.ast.Get(moduleId); + CToMIRModule(compiler, ctx, options, name, mirModule); + } + + c2mir_finish(ctx); + } + + void CToMIRModule(Compiler& compiler, MIR_context* ctx, c2mir_options& options, p::Tag name, + const CMIRModule& module) + { + auto getCode = [](void* data) -> p::i32 { + const char*& codeLeft = *static_cast(data); + if (*codeLeft == '\0') + { + return EOF; + } + return *(codeLeft++); + }; + + const char* code = module.code.data(); + if (!c2mir_compile(ctx, &options, getCode, &code, name.Data(), nullptr)) + { + compiler.Error("C to MIR compilation failed"); + } + } +} // namespace rift::MIR diff --git a/Libs/Backends/MIR/Compiler/Src/C2MIR.h b/Libs/Backends/MIR/Compiler/Src/C2MIR.h new file mode 100644 index 00000000..bb6a6b15 --- /dev/null +++ b/Libs/Backends/MIR/Compiler/Src/C2MIR.h @@ -0,0 +1,29 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include "Components.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +struct c2mir_options; + +namespace rift +{ + struct Compiler; +} + +namespace rift::MIR +{ + void CToMIR(Compiler& compiler, MIR_context* ctx); + void CToMIRModule(Compiler& compiler, MIR_context* ctx, c2mir_options& options, p::Tag name, + const CMIRModule& module); +} // namespace rift::MIR diff --git a/Libs/Backends/MIR/Compiler/Src/Components.h b/Libs/Backends/MIR/Compiler/Src/Components.h index 22da0bdf..ddf9c9d5 100644 --- a/Libs/Backends/MIR/Compiler/Src/Components.h +++ b/Libs/Backends/MIR/Compiler/Src/Components.h @@ -1,12 +1,26 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include +#include namespace rift { - using CMIRModule = MIR_module_t; - using CMIRType = MIR_type_t; + struct CMIRModule + { + p::String code; + }; + struct CMIRType + { + p::Tag value; + }; + struct CMIRLiteral + { + p::Tag value; + }; + struct CMIRFunctionSignature + { + p::String value; + }; } // namespace rift diff --git a/Libs/Backends/MIR/Compiler/Src/IRGeneration.cpp b/Libs/Backends/MIR/Compiler/Src/IRGeneration.cpp index 349aec1e..8ac0936c 100644 --- a/Libs/Backends/MIR/Compiler/Src/IRGeneration.cpp +++ b/Libs/Backends/MIR/Compiler/Src/IRGeneration.cpp @@ -1,62 +1,379 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "IRGeneration.h" -#include "mir.h" - -#include #include #include #include #include -#include -#include +#include +#include namespace rift::MIR { - void GenerateIR(Compiler& compiler, MIR_context_t& ctx) + const p::TSet CGenerator::reservedNames{"class", "struct"}; + + + void GenerateC(Compiler& compiler) { MIRAccess access{compiler.ast}; - BindNativeTypes(ctx, access); + CGenerator cGen{compiler, access}; + cGen.BindNativeTypes(); + cGen.GenerateLiterals(); + for (ast::Id moduleId : FindAllIdsWith(access)) + { + cGen.GenerateModule(moduleId); + } + } + + void CGenerator::GenerateModule(ast::Id moduleId) + { + const p::Tag name = ast::GetModuleName(compiler.ast, moduleId); + CMIRModule& mirModule = compiler.ast.Add(moduleId); + code = &mirModule.code; + + + // Get all rift types from the module + p::TArray typeIds; + p::GetIdChildren(access, moduleId, typeIds); + ExcludeIdsWithout(access, typeIds); + + { // Native declarations + p::TArray cStructIds = p::FindIdsWith(access, typeIds); + p::TArray cStaticIds = p::FindIdsWith(access, typeIds); + p::TArray cFunctionIds; + p::GetIdChildren(access, cStaticIds, cFunctionIds); + ExcludeIdsWithout(access, cFunctionIds); + DeclareStructs(cStructIds); + DeclareFunctions(cFunctionIds, false); + } + + p::TArray staticFunctionIds; + { // Rift declarations & definitions + p::TArray structIds = p::FindIdsWith(access, typeIds); + p::TArray staticIds = p::FindIdsWith(access, typeIds); + p::TArray classIds = p::FindIdsWith(access, typeIds); + p::TArray classFunctionIds; + p::GetIdChildren(access, staticIds, staticFunctionIds); + p::GetIdChildren(access, classIds, classFunctionIds); + ExcludeIdsWithout(access, staticFunctionIds); + ExcludeIdsWithout(access, classFunctionIds); + p::TArray functionIds; + functionIds.Append(staticFunctionIds); + functionIds.Append(classFunctionIds); + + DeclareStructs(structIds); + DeclareStructs(classIds); + DeclareFunctions(functionIds); + + DefineStructs(structIds); + DefineStructs(classIds); + DefineFunctions(functionIds); + } + + ast::Id mainFunctionId = ast::NoId; + const auto& module = compiler.ast.Get(moduleId); + if (module.target == ast::RiftModuleTarget::Executable) + { + mainFunctionId = FindMainFunction(staticFunctionIds); + CreateMain(mainFunctionId); + } + p::Info(*code); + } + + void CGenerator::BindNativeTypes() + { + const auto& nativeTypes = static_cast(access.GetContext()).GetNativeTypes(); + access.Add(nativeTypes.boolId, CMIRType{"char"}); + access.Add(nativeTypes.floatId, CMIRType{"float"}); + access.Add(nativeTypes.doubleId, CMIRType{"double"}); + access.Add(nativeTypes.u8Id, CMIRType{"unsigned char"}); + access.Add(nativeTypes.i8Id, CMIRType{"char"}); + access.Add(nativeTypes.u16Id, CMIRType{"unsigned short"}); + access.Add(nativeTypes.i16Id, CMIRType{"short"}); + access.Add(nativeTypes.u32Id, CMIRType{"unsigned long"}); + access.Add(nativeTypes.i32Id, CMIRType{"long"}); + access.Add(nativeTypes.u64Id, CMIRType{"unsigned long long"}); + access.Add(nativeTypes.i64Id, CMIRType{"long long"}); + // access.Add(nativeTypes.stringId, {}); + } - for (AST::Id moduleId : FindAllIdsWith(access)) + void CGenerator::GenerateLiterals() + { + for (ast::Id id : FindAllIdsWith(access)) + { + const auto& boolean = access.Get(id); + access.Add(id, CMIRLiteral{.value = boolean.value ? "true" : "false"}); + } + p::String strValue; + for (ast::Id id : FindAllIdsWith(access)) + { + strValue.clear(); + const auto& integral = access.Get(id); + p::Strings::ToString(strValue, integral.value); + access.Add(id, CMIRLiteral{.value = p::Tag{strValue}}); + } + for (ast::Id id : FindAllIdsWith(access)) { - GenerateIRModule(compiler, access, moduleId, ctx); + strValue.clear(); + const auto& floating = access.Get(id); + p::Strings::ToString(strValue, floating.value); + if (floating.type == ast::FloatingType::F32) + { + strValue.push_back('f'); + } + access.Add(id, CMIRLiteral{.value = p::Tag{strValue}}); + } + for (ast::Id id : FindAllIdsWith(access)) + { + strValue.clear(); + const auto& string = access.Get(id); + strValue.push_back('\"'); + strValue.append(string.value); + strValue.push_back('\"'); + access.Add(id, CMIRLiteral{.value = p::Tag{strValue}}); } } - void GenerateIRModule( - Compiler& compiler, MIRAccess access, AST::Id moduleId, MIR_context_t& ctx) + void CGenerator::DeclareStructs(p::TView ids) { - ZoneScoped; - auto& ast = compiler.ast; + code->append("// Struct Declarations\n"); + for (ast::Id id : ids) + { + p::Tag name = ast::GetNameUnsafe(access, id); + access.Add(id, CMIRType{name}); + p::Strings::FormatTo(*code, "typedef struct {0} {0};\n", name); + } + code->push_back('\n'); + } - const Tag name = AST::GetModuleName(compiler.ast, moduleId); + void CGenerator::DefineStructs(p::TView ids) + { + code->append("// Struct Definitions\n"); + p::String membersCode; + p::TArray memberIds; + for (ast::Id id : ids) + { + membersCode.clear(); + memberIds.Clear(false); + p::GetIdChildren(access, id, memberIds); - const auto& module = compiler.ast.Get(moduleId); - compiler.ast.Add(moduleId, MIR_new_module(ctx, name.AsString().data())); + p::ExcludeIdsWithout(access, memberIds); + for (ast::Id memberId : memberIds) + { + const auto& var = access.Get(memberId); - // NOTE: Module generation here + const p::Tag memberName = ast::GetName(access, memberId); + auto* irType = access.TryGet(var.typeId); + if (!irType) [[unlikely]] + { + const p::Tag typeName = ast::GetName(access, id); + compiler.Error(p::Strings::Format( + "Variable '{}' in struct '{}' has an invalid type", memberName, typeName)); + } + else if (reservedNames.Contains(memberName)) [[unlikely]] + { + const p::Tag typeName = ast::GetName(access, id); + compiler.Error(p::Strings::Format( + "Variable name '{}' not allowed in struct '{}' ", memberName, typeName)); + } + else + { + p::Strings::FormatTo(membersCode, "{} {};\n", irType->value, memberName); + } + } - MIR_finish_module(ctx); + const auto& type = access.Get(id); + p::Strings::FormatTo(*code, "struct {0} {{\n{1}}};\n", type.value, membersCode); + } + code->push_back('\n'); } + void CGenerator::DeclareFunctions(p::TView ids, bool useFullName) + { + code->append("// Function Declarations\n"); + + for (ast::Id id : ids) + { + auto& signature = access.Add(id).value; + + signature.append("void "); + const p::String name = useFullName ? ast::GetFullName(access, id, false, '_') + : p::String{ast::GetName(access, id).AsString()}; + signature.append(name); + signature.push_back('('); - void BindNativeTypes(MIR_context_t& ctx, MIRAccess access) + if (auto* outputs = access.TryGet(id)) + { + for (p::i32 i = 0; i < outputs->pinIds.Size(); ++i) + { + ast::Id inputId = outputs->pinIds[i]; + if (access.Has(inputId)) + { + continue; + } + + p::Tag inputName = ast::GetName(access, inputId); + + auto* exprId = access.TryGet(inputId); + const auto* irType = + exprId ? access.TryGet(exprId->id) : nullptr; + if (!irType) [[unlikely]] + { + const p::String functionName = ast::GetFullName(access, id); + compiler.Error(p::Strings::Format( + "Input '{}' in function '{}' has an invalid type. Using i32 instead.", + inputName, functionName)); + } + else if (reservedNames.Contains(inputName)) [[unlikely]] + { + const p::String functionName = ast::GetFullName(access, id); + compiler.Error( + p::Strings::Format("Input name '{}' not allowed in function '{}' ", + inputName, functionName)); + } + else + { + p::Strings::FormatTo(signature, "{0} {1}, ", irType->value, inputName); + } + } + p::Strings::RemoveFromEnd(signature, ", "); + } + signature.push_back(')'); + + // Create function + code->append(signature); + code->append(";\n"); + } + code->push_back('\n'); + } + + void CGenerator::DefineFunctions(p::TView ids) { - const auto& nativeTypes = static_cast(access.GetContext()).GetNativeTypes(); - access.Add(nativeTypes.boolId, CMIRType{MIR_T_I8}); - access.Add(nativeTypes.floatId, CMIRType{MIR_T_F}); - access.Add(nativeTypes.doubleId, CMIRType{MIR_T_D}); - access.Add(nativeTypes.u8Id, CMIRType{MIR_T_U8}); - access.Add(nativeTypes.i8Id, CMIRType{MIR_T_I8}); - access.Add(nativeTypes.u16Id, CMIRType{MIR_T_U16}); - access.Add(nativeTypes.i16Id, CMIRType{MIR_T_I16}); - access.Add(nativeTypes.u32Id, CMIRType{MIR_T_U32}); - access.Add(nativeTypes.i32Id, CMIRType{MIR_T_I32}); - access.Add(nativeTypes.u64Id, CMIRType{MIR_T_U64}); - access.Add(nativeTypes.i64Id, CMIRType{MIR_T_I64}); - // access.Add(nativeTypes.stringId, {}); + code->append("// Function Definitions\n"); + for (ast::Id id : ids) + { + const p::String& signature = access.Get(id).value; + code->append(signature); + code->append(" {\n"); + + const auto& output = access.Get(id); + AddStmtBlock(output.linkInputNode); + + code->append("}\n"); + } + code->push_back('\n'); + } + + void CGenerator::AddStmtBlock(ast::Id firstStmtId) + { + ast::Id splitId = ast::NoId; + p::TArray stmtIds; + ast::GetStmtChain(access, firstStmtId, stmtIds, splitId); + + for (ast::Id id : stmtIds) + { + if (const auto* call = access.TryGet(id)) + { + AddCall(id, *call); + } + } + + if (splitId != ast::NoId) + { + if (access.Has(splitId)) + { + AddStmtIf(splitId); + } + } + // TODO: Resolve continuation block and generate it + } + + void CGenerator::AddExpr(const ast::ExprOutput& output) + { + const auto* value = + !IsNone(output.pinId) ? access.TryGet(output.pinId) : nullptr; + // TODO + } + + void CGenerator::AddStmtIf(ast::Id id) + { + const auto& outputs = access.Get(id); + const auto& connectedIds = outputs.linkInputNodes; + P_Check(connectedIds.Size() == 2); + const auto& exprInputs = access.Get(id); + P_Check(exprInputs.linkedOutputs.Size() == 1); + + code->append("if ("); + AddExpr(exprInputs.linkedOutputs.First()); + code->append("){\n"); + AddStmtBlock(connectedIds[0]); + code->append("} else {\n"); + AddStmtBlock(connectedIds[1]); + code->append("}\n"); + } + + void CGenerator::AddCall(ast::Id id, const ast::CExprCallId& call) + { + const ast::Id functionId = call.functionId; + if (!access.IsValid(functionId)) + { + compiler.Error("Call to an unknown function"); + return; + } + if (!P_Ensure(access.Has(functionId))) + { + compiler.Error(p::Strings::Format( + "Call to an invalid function: '{}'", ast::GetFullName(access, functionId))); + return; + } + + if (auto* inputs = access.TryGet(id)) + { + for (p::i32 i = 0; i < inputs->linkedOutputs.Size(); ++i) + { + ast::ExprOutput output = inputs->linkedOutputs[i]; + if (!output.IsNone()) + { + AddExpr(output); + code->push_back(','); + } + else + { + // TODO: Error? or assign default value? + } + } + p::Strings::RemoveFromEnd(*code, ", "); + } + code->push_back(')'); + } + + void CGenerator::CreateMain(ast::Id functionId) + { + if (p::IsNone(functionId)) + { + compiler.Error(p::Strings::Format("Module is executable but has no \"Main\" function")); + return; + } + + // auto* customMainFunction = access.Get(functionId).instance; + + code->append("int main() {\nProject_Main_Main();\nreturn 0;\n}\n"); + } + + ast::Id CGenerator::FindMainFunction(p::TView functionIds) + { + static const p::Tag mainFunctionName{"Main"}; + + for (ast::Id id : functionIds) + { + const auto* ns = access.TryGet(id); + if (ns && ns->name == mainFunctionName) + { + return id; + } + } + return ast::NoId; } } // namespace rift::MIR diff --git a/Libs/Backends/MIR/Compiler/Src/IRGeneration.h b/Libs/Backends/MIR/Compiler/Src/IRGeneration.h index 48b849ba..00e64a2f 100644 --- a/Libs/Backends/MIR/Compiler/Src/IRGeneration.h +++ b/Libs/Backends/MIR/Compiler/Src/IRGeneration.h @@ -1,36 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Components.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include +#include +#include +#include #include -#include -#include +#include +#include +#include +#include -namespace rift -{ - struct CIRFunction; -} - namespace rift { struct Compiler; @@ -39,23 +22,42 @@ namespace rift namespace rift::MIR { // Defines a single ecs access dfor the entire IR generation - using MIRAccess = p::TAccessRef, AST::CLiteralBool, AST::CLiteralIntegral, AST::CLiteralFloating, - AST::CLiteralString>; + using MIRAccess = p::TAccessRef, p::TWrite, + p::TWrite>; + + void GenerateC(Compiler& compiler); + - struct ModuleIRGen + struct CGenerator { + static const p::TSet reservedNames; + Compiler& compiler; - MIR_context_t& ctx; - MIR_module_t& module; - }; + MIRAccess access; + p::String* code = nullptr; + - void GenerateIR(Compiler& compiler, MIR_context_t& ctx); + void GenerateModule(ast::Id moduleId); - void GenerateIRModule( - Compiler& compiler, MIRAccess access, AST::Id moduleId, MIR_context_t& ctx); + void BindNativeTypes(); + void GenerateLiterals(); + + void DeclareStructs(p::TView ids); + void DefineStructs(p::TView ids); + void DeclareFunctions(p::TView ids, bool useFullName = true); + void DefineFunctions(p::TView ids); + + void AddStmtBlock(ast::Id firstStmtId); + void AddStmtIf(ast::Id id); + void AddExpr(const ast::ExprOutput& output); + void AddCall(ast::Id id, const ast::CExprCallId& call); + void CreateMain(ast::Id functionId); + ast::Id FindMainFunction(p::TView functionIds); + }; - void BindNativeTypes(MIR_context_t& ctx, MIRAccess access); } // namespace rift::MIR diff --git a/Libs/Backends/MIR/Compiler/Src/MIRBackendModule.cpp b/Libs/Backends/MIR/Compiler/Src/MIRBackendModule.cpp index 0c51fc83..42413da6 100644 --- a/Libs/Backends/MIR/Compiler/Src/MIRBackendModule.cpp +++ b/Libs/Backends/MIR/Compiler/Src/MIRBackendModule.cpp @@ -1,36 +1,323 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "MIRBackendModule.h" +#include "C2MIR.h" +#include "Compiler/CompilerConfig.h" +#include "IRGeneration.h" + #include -#include #include #include #include +#include +#include + + +extern "C" +{ +#include +#include +} + + +#ifndef _WIN32 + #include + #if defined(__unix__) || defined(__APPLE__) + #include + #endif +#else + #define WIN32_LEAN_AND_MEAN + #include +#endif namespace rift { + struct Lib + { + const char* name = nullptr; + void* handler = nullptr; + }; + + // clang-format off + static Lib gStdLibs[] { + #if defined(_WIN32) + {"C:\\Windows\\System32\\msvcrt.dll"}, + {"C:\\Windows\\System32\\kernel32.dll"}, + {"C:\\Windows\\System32\\ucrtbase.dll"}, + #elif defined(__APPLE__) + {"/usr/lib/libc.dylib"}, + {"/usr/lib/libm.dylib"}, + #elif defined(__unix__) + #if UINTPTR_MAX == 0xffffffff + {"/lib/libc.so.6"}, + {"/lib32/libc.so.6"}, + {"/lib/libm.so.6"}, + {"/lib32/libm.so.6"}, + {"/lib/libpthread.so.0"}, + {"/lib32/libpthread.so.0"}, + #elif UINTPTR_MAX == 0xffffffffffffffff + #if defined(__x86_64__) + {"/lib64/libc.so.6"}, + {"/lib/x86_64-linux-gnu/libc.so.6"}, + {"/lib64/libm.so.6"}, + {"/lib/x86_64-linux-gnu/libm.so.6"}, + {"/usr/lib64/libpthread.so.0"}, + {"/lib/x86_64-linux-gnu/libpthread.so.0"}, + {"/usr/lib/libc.so"}, + #elif (__aarch64__) + {"/lib64/libc.so.6"}, {"/lib/aarch64-linux-gnu/libc.so.6"}, + {"/lib64/libm.so.6"}, + {"/lib/aarch64-linux-gnu/libm.so.6"}, + {"/lib64/libpthread.so.0"}, + {"/lib/aarch64-linux-gnu/libpthread.so.0"}, + #elif (__PPC64__) + {"/lib64/libc.so.6"}, + {"/lib64/libm.so.6"}, + {"/lib64/libpthread.so.0"}, + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + {"/lib/powerpc64le-linux-gnu/libc.so.6"}, + {"/lib/powerpc64le-linux-gnu/libm.so.6"}, + {"/lib/powerpc64le-linux-gnu/libpthread.so.0"}, + #else + {"/lib/powerpc64-linux-gnu/libc.so.6"}, + {"/lib/powerpc64-linux-gnu/libm.so.6"}, + {"/lib/powerpc64-linux-gnu/libpthread.so.0"}, + #endif + #elif (__s390x__) + {"/lib64/libc.so.6"}, + {"/lib/s390x-linux-gnu/libc.so.6"}, + {"/lib64/libm.so.6"}, + {"/lib/s390x-linux-gnu/libm.so.6"}, + {"/lib64/libpthread.so.0"}, + {"/lib/s390x-linux-gnu/libpthread.so.0"}, + #elif (__riscv) + {"/lib64/libc.so.6"}, + {"/lib/riscv64-linux-gnu/libc.so.6"}, + {"/lib64/libm.so.6"}, + {"/lib/riscv64-linux-gnu/libm.so.6"}, + {"/lib64/libpthread.so.0"}, + {"/lib/riscv64-linux-gnu/libpthread.so.0"}, + #else + #error Cannot recognize 32- or 64-bit target + #endif + #endif + #endif + }; + + #if defined(__unix__) + static const char* gStdLibDirs[] + { + #if UINTPTR_MAX == 0xffffffff + "/lib", + "/lib32" + #elif UINTPTR_MAX == 0xffffffffffffffff + #if defined(__x86_64__) + "/lib64", + "/lib/x86_64-linux-gnu" + #elif (__aarch64__) + "/lib64", + "/lib/aarch64-linux-gnu" + #elif (__PPC64__) + "/lib64", + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + "/lib/powerpc64le-linux-gnu", + #else + "/lib/powerpc64-linux-gnu", + #endif + #elif (__s390x__) + "/lib64", + "/lib/s390x-linux-gnu" + #elif (__riscv) + "/lib64", + "/lib/riscv64-linux-gnu" + #endif + #endif + }; + static const char* gLibSuffix = ".so"; + #elif defined(__APPLE__) + static const char* gStdLibDirs[]{"/usr/lib"}; + static const char* gLibSuffix = ".dylib"; + #elif defined(_WIN32) + static const char* gStdLibDirs[]{"C:\\Windows\\System32"}; + static const char* gLibSuffix = ".dll"; + #define dlopen(n, f) LoadLibrary(n) + #define dlclose(h) FreeLibrary(HMODULE(h)) + #define dlsym(h, s) GetProcAddress(HMODULE(h), s) + #endif + // clang-format on + + + static void OpenSTDLibs() + { + for (Lib& stdLib : gStdLibs) + { + stdLib.handler = dlopen(stdLib.name, RTLD_LAZY); + } + } + + static void CloseSTDLibs() + { + for (Lib& stdLib : gStdLibs) + { + if (stdLib.handler) + { + dlclose(stdLib.handler); + } + } + } + + static void* ImportResolver(const char* name) + { + void *handler, *sym = nullptr; + + for (Lib& stdLib : gStdLibs) + { + handler = stdLib.handler; + if (handler) + { + sym = dlsym(handler, name); + if (sym) + { + break; + } + } + } + + if (sym == nullptr) + { +#ifdef _WIN32 + if (strcmp(name, "LoadLibrary") == 0) + return LoadLibrary; + if (strcmp(name, "FreeLibrary") == 0) + return FreeLibrary; + if (strcmp(name, "GetProcAddress") == 0) + return GetProcAddress; +#else + if (strcmp(name, "dlopen") == 0) + return (void*)dlopen; + if (strcmp(name, "dlerror") == 0) + return (void*)dlerror; + if (strcmp(name, "dlclose") == 0) + return (void*)dlclose; + if (strcmp(name, "dlsym") == 0) + return (void*)dlsym; + if (strcmp(name, "stat") == 0) + return (void*)stat; + if (strcmp(name, "lstat") == 0) + return (void*)lstat; + if (strcmp(name, "fstat") == 0) + return (void*)fstat; + #if defined(__APPLE__) && defined(__aarch64__) + if (strcmp(name, "__nan") == 0) + return __nan; + if (strcmp(name, "_MIR_set_code") == 0) + return _MIR_set_code; + #endif +#endif + fprintf(stderr, "can not load symbol %s\n", name); + CloseSTDLibs(); + exit(1); + } + return sym; + } + + MIRBackendModule::MIRBackendModule() { AddDependency(); } + using EntryFunctionPtr = p::i32 (*)(); void MIRBackend::Build(Compiler& compiler) { - ZoneScopedN("Backend: MIR"); + MIR::GenerateC(compiler); + + if (compiler.HasErrors()) + { + PrintBuildFinish(compiler); + return; + } + + MIR_context* ctx = MIR_init(); - MIR_context_t ctx = MIR_init(); + MIR::CToMIR(compiler, ctx); + + p::i32 nGen = 1; + MIR_item_t func, mainFunc = nullptr; + + { // Find main + for (MIR_module_t module = DLIST_HEAD(MIR_module_t, *MIR_get_module_list(ctx)); + module != nullptr; module = DLIST_NEXT(MIR_module_t, module)) + { + for (func = DLIST_HEAD(MIR_item_t, module->items); func != nullptr; + func = DLIST_NEXT(MIR_item_t, func)) + { + if (func->item_type == MIR_func_item && strcmp(func->u.func->name, "main") == 0) + { + mainFunc = func; + } + } + MIR_load_module(ctx, module); + } + + if (!mainFunc) + { + compiler.Error("Main function not found in MIR generated code."); + } + } + + if (compiler.HasErrors()) + { + PrintBuildFinish(compiler); + return; + } + OpenSTDLibs(); + MIR_gen_init(ctx, nGen); + for (p::i32 i = 0; i < nGen; ++i) + { + if (compiler.config.optimization != OptimizationLevel::Zero) + { + MIR_gen_set_optimize_level(ctx, i, (unsigned)compiler.config.optimization); + } + // if (gen_debug_level >= 0) + //{ + // MIR_gen_set_debug_file(ctx, i, stderr); + // MIR_gen_set_debug_level(ctx, i, gen_debug_level); + // } + } + MIR_link( + ctx, nGen > 1 ? MIR_set_parallel_gen_interface : MIR_set_gen_interface, ImportResolver); + + auto entry = EntryFunctionPtr(nGen > 1 ? MIR_gen(ctx, 0, mainFunc) : mainFunc->addr); + + p::DateTime startTime = p::DateTime::Now(); + p::i32 resultCode = entry(); // Run! + MIR_gen_finish(ctx); + + if (compiler.config.verbose) + { + p::Info(" execution -- {:.3f}s\n", + (p::DateTime::Now() - startTime).GetTotalSeconds()); + p::Info("exit code: {}\n", resultCode); + } + PrintBuildFinish(compiler); + + CloseSTDLibs(); + MIR_finish(ctx); + } + + void MIRBackend::PrintBuildFinish(Compiler& compiler) const + { if (!compiler.HasErrors()) { p::Info("Build complete."); } else { - p::Info("Build failed: {} errors", compiler.GetErrors().Size()); + p::Error("Build failed: {} errors", compiler.GetErrors().Size()); } - - MIR_finish(ctx); } } // namespace rift \ No newline at end of file diff --git a/Libs/Bindings/Native/CMakeLists.txt b/Libs/Bindings/Native/CMakeLists.txt index f71a7696..ad5ac041 100644 --- a/Libs/Bindings/Native/CMakeLists.txt +++ b/Libs/Bindings/Native/CMakeLists.txt @@ -1,13 +1,12 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftBindingNative STATIC) +add_library(RiftBindingNativeLib STATIC) -target_link_libraries(RiftBindingNative PUBLIC RiftAST) -target_link_libraries(RiftBindingNative PRIVATE RiftClang) +target_link_libraries(RiftBindingNativeLib PUBLIC RiftASTLib) -rift_compiler_module(RiftBindingNative) +rift_compiler_module(RiftBindingNativeLib) -add_library(RiftBindingNativeEditor STATIC) -rift_editor_module(RiftBindingNativeEditor) -target_link_libraries(RiftBindingNativeEditor PUBLIC RiftEditor RiftBindingNative) +add_library(RiftBindingNativeEditorLib STATIC) +rift_editor_module(RiftBindingNativeEditorLib) +target_link_libraries(RiftBindingNativeEditorLib PUBLIC RiftEditorLib RiftBindingNativeLib) diff --git a/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStatic.h b/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStatic.h deleted file mode 100644 index 0b215665..00000000 --- a/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStatic.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift -{ - struct CDeclCStatic : public AST::CDeclRecord - { - STRUCT(CDeclCStatic, CDeclRecord) - }; -} // namespace rift diff --git a/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStruct.h b/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStruct.h deleted file mode 100644 index f14cdfe7..00000000 --- a/Libs/Bindings/Native/Compiler/Include/Components/CDeclCStruct.h +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2015-2023 Piperift - All rights reserved -#pragma once - -#include - - -namespace rift -{ - struct CDeclCStruct : public AST::CDeclRecord - { - STRUCT(CDeclCStruct, CDeclRecord) - }; -} // namespace rift diff --git a/Libs/Bindings/Native/Compiler/Include/Components/CNativeBinding.h b/Libs/Bindings/Native/Compiler/Include/Components/CNativeBinding.h index e646822c..5a65b40a 100644 --- a/Libs/Bindings/Native/Compiler/Include/Components/CNativeBinding.h +++ b/Libs/Bindings/Native/Compiler/Include/Components/CNativeBinding.h @@ -1,20 +1,20 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include +#include namespace rift { - struct CNativeBinding : public p::Struct + struct CNativeBinding { - STRUCT(CNativeBinding, p::Struct) + P_STRUCT(CNativeBinding) - PROP(binaries) + P_PROP(binaries) p::TArray binaries; - PROP(autoGenerateDefinitions) + P_PROP(autoGenerateDefinitions) bool autoGenerateDefinitions = false; }; } // namespace rift diff --git a/Libs/Bindings/Native/Compiler/Include/Components/Declarations.h b/Libs/Bindings/Native/Compiler/Include/Components/Declarations.h new file mode 100644 index 00000000..4e4afbbb --- /dev/null +++ b/Libs/Bindings/Native/Compiler/Include/Components/Declarations.h @@ -0,0 +1,21 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include +#include + + +namespace rift +{ + struct CDeclCStruct : public ast::CDeclRecord + { + using Super = CDeclRecord; + P_STRUCT(CDeclCStruct) + }; + + struct CDeclCStatic : public ast::CDeclRecord + { + using Super = CDeclRecord; + P_STRUCT(CDeclCStatic) + }; +} // namespace rift diff --git a/Libs/Bindings/Native/Compiler/Include/HeaderIterator.h b/Libs/Bindings/Native/Compiler/Include/HeaderIterator.h index 5d59a0c3..fff1716d 100644 --- a/Libs/Bindings/Native/Compiler/Include/HeaderIterator.h +++ b/Libs/Bindings/Native/Compiler/Include/HeaderIterator.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Utils/Paths.h" @@ -9,18 +9,18 @@ namespace rift { - class HeaderIterator : public p::LambdaFileIterator + class HeaderIterator : public p::LambdaFileIterator { - using Super = p::LambdaFileIterator; + using Super = p::LambdaFileIterator; public: using Super::Super; static constexpr p::StringView headerExtension = ".h"; - explicit HeaderIterator(const p::Path& path) - : Super(path, [](const auto& path) { - return path.extension() == headerExtension; + explicit HeaderIterator(StringView path) + : Super(path, [](StringView path) { + return p::GetExtension(path) == headerExtension; }) {} }; diff --git a/Libs/Bindings/Native/Compiler/Include/NativeBindingModule.h b/Libs/Bindings/Native/Compiler/Include/NativeBindingModule.h index a07afca9..866a5ecd 100644 --- a/Libs/Bindings/Native/Compiler/Include/NativeBindingModule.h +++ b/Libs/Bindings/Native/Compiler/Include/NativeBindingModule.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -7,16 +7,18 @@ namespace rift { - namespace AST + namespace ast { class Tree; } class NativeBindingModule : public Module { - CLASS(NativeBindingModule, Module) + public: + using Super = Module; + P_CLASS(NativeBindingModule) void Load() override; - void SyncIncludes(AST::Tree& ast); + void SyncIncludes(ast::Tree& ast); }; } // namespace rift diff --git a/Libs/Bindings/Native/Compiler/Src/NativeBindingModule.cpp b/Libs/Bindings/Native/Compiler/Src/NativeBindingModule.cpp index 818de8bd..2a221d49 100644 --- a/Libs/Bindings/Native/Compiler/Src/NativeBindingModule.cpp +++ b/Libs/Bindings/Native/Compiler/Src/NativeBindingModule.cpp @@ -1,10 +1,9 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "NativeBindingModule.h" -#include "Components/CDeclCStatic.h" -#include "Components/CDeclCStruct.h" #include "Components/CNativeBinding.h" +#include "Components/Declarations.h" #include "HeaderIterator.h" #include @@ -13,61 +12,46 @@ #include #include #include -#include -#include -#include - - -// P_OVERRIDE_NEW_DELETE +#include +#include namespace rift { struct ParsedModule { - AST::Id id = AST::NoId; - CXIndex index = clang_createIndex(0, 0); + ast::Id id = ast::NoId; TArray headers; - TArray units; - - ~ParsedModule() - { - for (auto unit : units) - { - clang_disposeTranslationUnit(unit); - } - clang_disposeIndex(index); - } }; void NativeBindingModule::Load() { // Register types - AST::RiftTypeSettings typeSettings{.category = "Bindings"}; + ast::RiftTypeSettings typeSettings{.category = "Bindings"}; typeSettings.displayName = "C Struct"; typeSettings.hasVariables = true; typeSettings.hasFunctions = false; - AST::RegisterFileType("CStruct", typeSettings); + ast::RegisterFileType("CStruct", typeSettings); typeSettings.displayName = "C Static"; typeSettings.hasVariables = true; typeSettings.hasFunctions = true; typeSettings.hasFunctionBodies = false; - AST::RegisterFileType("CStatic", typeSettings); - AST::PreAllocPools(); + ast::RegisterFileType("CStatic", typeSettings); + ast::PreAllocPools(); // Register module binding - AST::RegisterModuleBinding( - {.id = "C", .tagType = CNativeBinding::GetStaticType(), .displayName = "C"}); - AST::RegisterSerializedModulePools(); - AST::PreAllocPools(); + ast::RegisterModuleBinding( + {.id = "C", .tagType = p::GetTypeId(), .displayName = "C"}); + ast::RegisterSerializedModulePools(); + ast::PreAllocPools(); } - void FindHeaders(AST::Tree& ast, TView parsedModules) + void FindHeaders(ast::Tree& ast, TView parsedModules) { - p::TAccess access{ast}; + p::TAccess access{ast}; for (auto& module : parsedModules) { - Path path = AST::GetModulePath(access, module.id); + StringView path = ast::GetModulePath(access, module.id); for (const auto& headerPath : HeaderIterator(path)) { module.headers.Add(p::ToString(headerPath)); @@ -75,32 +59,10 @@ namespace rift } } - void ParseHeaders(AST::Tree& ast, TView parsedModules) - { - for (auto& module : parsedModules) - { - for (i32 i = 0; i < module.headers.Size(); ++i) - { - const StringView include = module.headers[i]; - const CXTranslationUnit unit = - clang_parseTranslationUnit(module.index, include.data(), nullptr, 0, nullptr, 0, - CXTranslationUnit_DetailedPreprocessingRecord); - if (!unit) - { - module.headers.RemoveAt(i, false); - --i; - p::Error("Unable to parse module header '{}'", include); - continue; - } - module.units.Add(unit); - } - } - } - - void NativeBindingModule::SyncIncludes(AST::Tree& ast) + void NativeBindingModule::SyncIncludes(ast::Tree& ast) { - TArray moduleIds; - p::FindAllIdsWith(ast, moduleIds); + TArray moduleIds; + p::FindAllIdsWith(ast, moduleIds); // Only use automatic native bindings on modules marked as such moduleIds.RemoveIfSwap([ast](auto id) { @@ -115,7 +77,6 @@ namespace rift parsed.id = moduleIds[i]; } FindHeaders(ast, parsedModules); - ParseHeaders(ast, parsedModules); // TODO: Generate Rift interface } } // namespace rift diff --git a/Libs/Bindings/Native/Editor/Include/NativeBindingEditorModule.h b/Libs/Bindings/Native/Editor/Include/NativeBindingEditorModule.h index ca9dfc64..fe64df1a 100644 --- a/Libs/Bindings/Native/Editor/Include/NativeBindingEditorModule.h +++ b/Libs/Bindings/Native/Editor/Include/NativeBindingEditorModule.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -9,6 +9,8 @@ namespace rift { class NativeBindingEditorModule : public Module { - CLASS(NativeBindingEditorModule, Module) + public: + using Super = Module; + P_CLASS(NativeBindingEditorModule) }; } // namespace rift diff --git a/Libs/Bindings/Native/Editor/Src/NativeBindingEditorModule.cpp b/Libs/Bindings/Native/Editor/Src/NativeBindingEditorModule.cpp index bc871902..6bad9b90 100644 --- a/Libs/Bindings/Native/Editor/Src/NativeBindingEditorModule.cpp +++ b/Libs/Bindings/Native/Editor/Src/NativeBindingEditorModule.cpp @@ -1,3 +1,3 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "NativeBindingEditorModule.h" diff --git a/Libs/CMakeLists.txt b/Libs/CMakeLists.txt index 90036f0a..af69be59 100644 --- a/Libs/CMakeLists.txt +++ b/Libs/CMakeLists.txt @@ -1,7 +1,6 @@ # Copyright 2015-2023 Piperift - All rights reserved add_subdirectory(AST) -add_subdirectory(Backends/LLVM) add_subdirectory(Backends/MIR) add_subdirectory(Bindings/Native) diff --git a/Libs/Editor/CMakeLists.txt b/Libs/Editor/CMakeLists.txt index 514b0359..6614b82d 100644 --- a/Libs/Editor/CMakeLists.txt +++ b/Libs/Editor/CMakeLists.txt @@ -1,19 +1,18 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftEditor STATIC) +add_library(RiftEditorLib STATIC) -target_include_directories(RiftEditor PUBLIC Include) -file(GLOB_RECURSE RiftEditor_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) -target_sources(RiftEditor PRIVATE ${RiftEditor_SOURCE_FILES}) +target_include_directories(RiftEditorLib PUBLIC Include) +file(GLOB_RECURSE RiftEditorLib_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) +target_sources(RiftEditorLib PRIVATE ${RiftEditorLib_SOURCE_FILES}) -target_link_libraries(RiftEditor PUBLIC - RiftAST - RiftBackendLLVM - RiftBackendMIR - RiftUI +target_link_libraries(RiftEditorLib PUBLIC + RiftASTLib + RiftBackendMIRLib + RiftUILib CLI11 ) -rift_module(RiftEditor) -rift_enable_module_resources(RiftEditor) -set_icon(RiftEditor ../../Resources/Icon.ico) +rift_module(RiftEditorLib) +rift_enable_module_resources(RiftEditorLib) +set_target_properties(RiftEditorLib PROPERTIES OUTPUT_NAME "RiftEditor") diff --git a/Libs/Editor/Include/Components/CDeclRename.h b/Libs/Editor/Include/Components/CDeclRename.h index 7fa7bfcc..cc7d44ea 100644 --- a/Libs/Editor/Include/Components/CDeclRename.h +++ b/Libs/Editor/Include/Components/CDeclRename.h @@ -1,21 +1,21 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Assets/TypePropertiesPanel.h" #include "DockSpaceLayout.h" #include "NodeGraph/NodeGraphPanel.h" -#include #include -namespace rift::Editor + +namespace rift::editor { - struct CDeclRename : public p::Struct + struct CDeclRename { - STRUCT(CDeclRename, p::Struct, p::Struct_NotSerialized) + P_STRUCT(CDeclRename, p::TF_NotSerialized) // Renaming uses this buffer to temporarely store the name being edited p::String buffer; }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Components/CModuleEditor.h b/Libs/Editor/Include/Components/CModuleEditor.h index cfab5b7f..43df7b7d 100644 --- a/Libs/Editor/Include/Components/CModuleEditor.h +++ b/Libs/Editor/Include/Components/CModuleEditor.h @@ -1,20 +1,20 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "DockSpaceLayout.h" #include -#include #include #include -namespace rift::Editor + +namespace rift::editor { - struct CModuleEditor : public p::Struct + struct CModuleEditor { - STRUCT(CModuleEditor, p::Struct, p::Struct_NotSerialized) + P_STRUCT(CModuleEditor, p::TF_NotSerialized) bool pendingFocus = false; }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Components/CTypeEditor.h b/Libs/Editor/Include/Components/CTypeEditor.h index 96e7fd1e..2e945820 100644 --- a/Libs/Editor/Include/Components/CTypeEditor.h +++ b/Libs/Editor/Include/Components/CTypeEditor.h @@ -1,19 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "DockSpaceLayout.h" #include -#include +#include #include #include -namespace rift::Editor +namespace rift::editor { - struct CTypeEditor : public p::Struct + struct CTypeEditor { - STRUCT(CTypeEditor, p::Struct, p::Struct_NotSerialized) + P_STRUCT(CTypeEditor, p::TF_NotSerialized) static const Tag rightTopNode; static const Tag rightBottomNode; @@ -27,8 +27,8 @@ namespace rift::Editor bool showElements = true; bool showDetails = true; - AST::Id selectedPropertyId = AST::NoId; - AST::Id pendingDeletePropertyId = AST::NoId; + ast::Id selectedPropertyId = ast::NoId; + ast::Id pendingDeletePropertyId = ast::NoId; Nodes::EditorContext nodesEditor; ImGuiTextFilter elementsFilter; @@ -37,4 +37,4 @@ namespace rift::Editor inline const Tag CTypeEditor::rightTopNode{"rightTopNode"}; inline const Tag CTypeEditor::rightBottomNode{"rightBottomNode"}; inline const Tag CTypeEditor::centralNode{"centralNode"}; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/DockSpaceLayout.h b/Libs/Editor/Include/DockSpaceLayout.h index 58ded73b..1b365a29 100644 --- a/Libs/Editor/Include/DockSpaceLayout.h +++ b/Libs/Editor/Include/DockSpaceLayout.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include @@ -7,7 +7,7 @@ #include -namespace rift::Editor +namespace rift::editor { using namespace p; @@ -75,4 +75,4 @@ namespace rift::Editor return idPtr ? *idPtr : 0; } }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Editor.h b/Libs/Editor/Include/Editor.h index 0067fa9f..e2ce1992 100644 --- a/Libs/Editor/Include/Editor.h +++ b/Libs/Editor/Include/Editor.h @@ -1,25 +1,28 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once +#include "PipeFiles.h" + #include #include -#include +#include -namespace rift::Editor +namespace rift::editor { - using namespace p; - class Editor { - FrameTime frameTime; + p::FrameTime frameTime; bool configFileChanged = false; - String configFile; + p::String configFile; + + ast::Tree ast; - AST::Tree ast; + p::FileWatcher fileWatcher; public: + bool filesDirty = true; #if P_DEBUG bool showDemo = false; bool showMetrics = false; @@ -32,11 +35,11 @@ namespace rift::Editor ~Editor(); - int Run(StringView projectPath = {}); + int Run(p::StringView projectPath = {}); void Tick(); - void SetUIConfigFile(Path path); + void SetUIConfigFile(p::StringView path); static Editor& Get() { @@ -44,17 +47,19 @@ namespace rift::Editor return instance; } - static AST::Tree& GetContext() + static ast::Tree& GetContext() { return Get().ast; } bool CreateProject(p::StringView path, bool closeFirst = true); bool OpenProject(p::StringView path, bool closeFirst = true); + void CloseProject(); + // Close the editor void Close(); protected: void UpdateConfig(); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Panels/FileExplorerPanel.h b/Libs/Editor/Include/Panels/FileExplorerPanel.h index 1fab7ea0..5a50e165 100644 --- a/Libs/Editor/Include/Panels/FileExplorerPanel.h +++ b/Libs/Editor/Include/Panels/FileExplorerPanel.h @@ -1,19 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Components/CProject.h" -#include #include #include #include +#include #include #include -#include -#include +#include +#include -namespace rift::Editor +namespace rift::editor { // Forward declarations class ProjectEditor; @@ -32,7 +32,7 @@ namespace rift::Editor struct Item { - AST::Id id = AST::NoId; + ast::Id id = ast::NoId; p::String path; bool isFolder = false; }; @@ -43,14 +43,14 @@ namespace rift::Editor }; private: - AST::Id projectModuleId = AST::NoId; + ast::Id projectModuleId = ast::NoId; p::TMap folders; bool open = true; bool dirty = true; Filter filter = Filter::All; - AST::Id renameId = AST::NoId; + ast::Id renameId = ast::NoId; p::String renameBuffer; bool renameHasFocused = false; @@ -61,26 +61,26 @@ namespace rift::Editor FileExplorerPanel() {} void BuildLayout(); - void Draw(AST::Tree& ast); + void Draw(ast::Tree& ast); - void DrawList(AST::Tree& ast); + void DrawList(ast::Tree& ast); - void DrawContextMenu(AST::Tree& ast, p::StringView path, AST::Id itemId); + void DrawContextMenu(ast::Tree& ast, p::StringView path, ast::Id itemId); void CacheProjectFiles( - p::TAccessRef access); + p::TAccessRef access); void SortFolder(Folder& folder); private: void InsertItem(const Item& item); - void DrawItem(AST::Tree& ast, const Item& item); - // void DrawFile(AST::Tree& ast, File& file); + void DrawItem(ast::Tree& ast, const Item& item); + // void DrawFile(ast::Tree& ast, File& file); - void DrawModuleActions(AST::Id id, struct AST::CModule& module); - void DrawTypeActions(AST::Id id, struct AST::CDeclType& type); + void DrawModuleActions(ast::Id id, struct ast::CModule& module); + void DrawTypeActions(ast::Id id, struct ast::CDeclType& type); - void CreateType(AST::Tree& ast, p::StringView title, p::Tag typeId, p::StringView path); + void CreateType(ast::Tree& ast, p::StringView title, p::Tag typeId, p::StringView path); }; @@ -88,4 +88,4 @@ namespace rift::Editor { return static_cast(filter); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Statics/EditorSettings.h b/Libs/Editor/Include/Statics/EditorSettings.h new file mode 100644 index 00000000..50490fc9 --- /dev/null +++ b/Libs/Editor/Include/Statics/EditorSettings.h @@ -0,0 +1,16 @@ +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include + + +namespace rift::editor +{ + struct EditorSettings + { + P_STRUCT(EditorSettings) + + P_PROP(recentProjects) + p::TArray recentProjects; + }; +} // namespace rift::editor diff --git a/Libs/Editor/Include/Statics/SEditor.h b/Libs/Editor/Include/Statics/SEditor.h index d9530af8..69a5c1a0 100644 --- a/Libs/Editor/Include/Statics/SEditor.h +++ b/Libs/Editor/Include/Statics/SEditor.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Id.h" @@ -9,21 +9,16 @@ #include "Tools/MemoryDebugger.h" #include "Tools/ReflectionDebugger.h" -#include #include -#include +#include #include -namespace rift::Editor +namespace rift::editor { - using namespace p::core; - using namespace p::files; - - - struct SEditor : public Struct + struct SEditor { - STRUCT(SEditor, Struct) + P_STRUCT(SEditor) ImGuiID dockspaceID = 0; DockSpaceLayout layout; @@ -31,13 +26,12 @@ namespace rift::Editor static const Tag centralNode; String currentProjectPath; - TArray pendingTypesToClose; + TArray pendingTypesToClose; - FileWatcher fileWatcher; FileExplorerPanel fileExplorer{}; ReflectionDebugger reflectionDebugger; - ASTDebugger astDebugger; + ASTDebugger ASTDebugger; MemoryDebugger memoryDebugger; GraphPlayground graphPlayground; @@ -46,4 +40,4 @@ namespace rift::Editor inline const Tag SEditor::leftNode{"leftNode"}; inline const Tag SEditor::centralNode{"centralNode"}; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Systems/EditorSystem.h b/Libs/Editor/Include/Systems/EditorSystem.h index 821f7931..1f45e9b0 100644 --- a/Libs/Editor/Include/Systems/EditorSystem.h +++ b/Libs/Editor/Include/Systems/EditorSystem.h @@ -1,11 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -namespace rift::Editor::EditorSystem +namespace rift::editor::EditorSystem { - void Init(AST::Tree& ast); - void Draw(AST::Tree& ast); -} // namespace rift::Editor::EditorSystem + void Init(ast::Tree& ast); + void Draw(ast::Tree& ast); +} // namespace rift::editor::EditorSystem diff --git a/Libs/Editor/Include/Tools/ASTDebugger.h b/Libs/Editor/Include/Tools/ASTDebugger.h index 315eddc1..d1c36da9 100644 --- a/Libs/Editor/Include/Tools/ASTDebugger.h +++ b/Libs/Editor/Include/Tools/ASTDebugger.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Tree.h" @@ -6,33 +6,51 @@ #include #include #include -#include #include -#include -#include -#include -#include +#include +#include +#include +#include #include -namespace rift::Editor +namespace rift::editor { + struct InspectorPanel + { + ast::Id id = ast::NoId; + bool pendingFocus = true; + bool open = true; + + bool operator==(const InspectorPanel& other) const + { + return id == other.id; + } + }; + struct ASTDebugger { bool open = false; bool showHierarchy = true; - AST::Id selectedNode = AST::NoId; + ast::Id selectedNode = ast::NoId; ImGuiTextFilter filter; + // First inspector is the main inspector + InspectorPanel mainInspector; + p::TArray secondaryInspectors; + ASTDebugger(); - void Draw(AST::Tree& ast); + void Draw(ast::Tree& ast); private: - using DrawNodeAccess = - p::TAccessRef; - void DrawNode(DrawNodeAccess access, AST::Id nodeId, bool showChildren); + void OnInspectEntity(ast::Id id); + + void DrawEntityInspector(p::StringView label, p::StringView id, ast::Tree& ast, + InspectorPanel& inspector, bool* open = nullptr); + + void OpenAvailableSecondaryInspector(ast::Id id); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Tools/BigBestFitArenaDebugger.h b/Libs/Editor/Include/Tools/BigBestFitArenaDebugger.h index c64fe6a8..0024ae0d 100644 --- a/Libs/Editor/Include/Tools/BigBestFitArenaDebugger.h +++ b/Libs/Editor/Include/Tools/BigBestFitArenaDebugger.h @@ -1,14 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include #include -#include -#include -#include +#include +#include +#include -namespace rift::Editor +namespace rift::editor { using namespace p; @@ -16,11 +15,11 @@ namespace rift::Editor { static constexpr v2 unitSize{4.f, 4.f}; // Size of each grid point - u32 memoryScale = 8; // Each gridpoint will equal N bytes - u32 numColumns = 0; - u32 bytesPerRow = 0; - u32 numRows = 0; - const p::Memory::Block* block = nullptr; + u32 memoryScale = 8; // Each gridpoint will equal N bytes + u32 numColumns = 0; + u32 bytesPerRow = 0; + u32 numRows = 0; + const p::ArenaBlock* block = nullptr; MemoryGrid() = default; @@ -60,4 +59,4 @@ namespace rift::Editor BigBestFitArenaDebugger(); void Draw(); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Tools/GraphPlayground.h b/Libs/Editor/Include/Tools/GraphPlayground.h index 493a4568..d19734a8 100644 --- a/Libs/Editor/Include/Tools/GraphPlayground.h +++ b/Libs/Editor/Include/Tools/GraphPlayground.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Tree.h" @@ -7,7 +7,7 @@ #include -namespace rift::Editor +namespace rift::editor { struct GraphPlayground { @@ -18,6 +18,6 @@ namespace rift::Editor GraphPlayground() {} - void Draw(AST::Tree& ast, struct DockSpaceLayout& layout); + void Draw(ast::Tree& ast, struct DockSpaceLayout& layout); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Tools/MemoryDebugger.h b/Libs/Editor/Include/Tools/MemoryDebugger.h index 3337310f..d56f0e21 100644 --- a/Libs/Editor/Include/Tools/MemoryDebugger.h +++ b/Libs/Editor/Include/Tools/MemoryDebugger.h @@ -1,14 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include #include -#include -#include -#include +#include +#include +#include -namespace rift::Editor +namespace rift::editor { using namespace p; @@ -21,4 +20,4 @@ namespace rift::Editor MemoryDebugger(); void Draw(); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Tools/ReflectionDebugger.h b/Libs/Editor/Include/Tools/ReflectionDebugger.h index 905d5f78..a6c2bcff 100644 --- a/Libs/Editor/Include/Tools/ReflectionDebugger.h +++ b/Libs/Editor/Include/Tools/ReflectionDebugger.h @@ -1,12 +1,13 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "AST/Tree.h" +#include "PipeReflect.h" #include -namespace rift::Editor +namespace rift::editor { using namespace p; @@ -15,16 +16,13 @@ namespace rift::Editor { bool open = false; - Type* selectedType = nullptr; + TypeId selectedType; ImGuiTextFilter filter; - TypeCategory categoryFilter = TypeCategory::All; + TypeFlags typeFlagsFilter = p::TF_Native | p::TF_Enum | p::TF_Struct | p::TF_Object; ReflectionDebugger(); - void Draw(); - - private: - void DrawType(Type* type); + void Draw(ast::Tree& ast); }; -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/UserSettings.h b/Libs/Editor/Include/UserSettings.h new file mode 100644 index 00000000..cf16cffc --- /dev/null +++ b/Libs/Editor/Include/UserSettings.h @@ -0,0 +1,18 @@ + +// Copyright 2015-2024 Piperift - All rights reserved +#pragma once + +#include + + +namespace rift +{ + + class UserSettings : p::Class + { + private: + static TOwnPtr instance; + + static UserSettings* Get(); + }; +} // namespace rift diff --git a/Libs/Editor/Include/Utils/DetailsPanel.h b/Libs/Editor/Include/Utils/DetailsPanel.h index 5876d605..ac02d1c8 100644 --- a/Libs/Editor/Include/Utils/DetailsPanel.h +++ b/Libs/Editor/Include/Utils/DetailsPanel.h @@ -1,23 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include #include #include #include -#include +#include -namespace rift::Editor +namespace rift::editor { - void DrawDetailsPanel(AST::Tree& ast, AST::Id typeId); -} // namespace rift::Editor + void DrawDetailsPanel(ast::Tree& ast, ast::Id typeId); +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/EditorStyle.h b/Libs/Editor/Include/Utils/EditorStyle.h index a2bf9f5e..06539cb0 100644 --- a/Libs/Editor/Include/Utils/EditorStyle.h +++ b/Libs/Editor/Include/Utils/EditorStyle.h @@ -1,62 +1,64 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once +#include "Pipe/Core/TypeTraits.h" + #include -#include -#include +#include +#include #include -namespace rift::Editor +namespace rift::editor { using namespace p; - constexpr Color selectedColor{Color::FromHEX(0xdba43f)}; - constexpr Color executionColor{Color::FromHEX(0xdbdbdb)}; + constexpr Color selectedColor{Color::FromHex(0xdba43f)}; + constexpr Color executionColor{Color::FromHex(0xdbdbdb)}; - constexpr Color functionColor{Color::FromHEX(0xCC3D33)}; + constexpr Color functionColor{Color::FromHex(0xCC3D33)}; constexpr Color returnColor{functionColor.Shade(0.1f)}; - constexpr Color callColor{Color::FromHEX(0x3366CC)}; + constexpr Color callColor{Color::FromHex(0x3366CC)}; constexpr Color flowColor{UI::GetNeutralColor(4)}; - constexpr Color invalidColor{Color::FromHEX(0xF95040)}; + constexpr Color invalidColor{Color::FromHex(0xF95040)}; template constexpr Color GetTypeColor() { if constexpr (IsSame) { - return Color::FromHEX(0xBF4A41); + return Color::FromHex(0xBF4A41); } else if constexpr (FloatingPoint) { - return Color::FromHEX(0x54BFA6); + return Color::FromHex(0x54BFA6); } else if constexpr (SignedIntegral) { - return Color::FromHEX(0x63BF54); + return Color::FromHex(0x63BF54); } else if constexpr (UnsignedIntegral) { - return Color::FromHEX(0x54BF79); + return Color::FromHex(0x54BF79); } else if constexpr (IsSame) { - return Color::FromHEX(0xBF54AE); + return Color::FromHex(0xBF54AE); } - else if constexpr (IsSame) + else if constexpr (IsObject) { - return Color::FromHEX(0x545FBF); + return Color::FromHex(0x545FBF); } - else if constexpr (IsSame) + else if constexpr (IsStructOrClass) { - return Color::FromHEX(0x548CBF); + return Color::FromHex(0x548CBF); } return Color::Gray(); }; - const Color GetTypeColor(const AST::Tree& ast, AST::Id id); + const Color GetTypeColor(const ast::Tree& ast, ast::Id id); void PushNodeTitleColor(Color color); @@ -64,4 +66,4 @@ namespace rift::Editor void PushNodeBackgroundColor(Color color); void PopNodeBackgroundColor(); -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/ElementsPanel.h b/Libs/Editor/Include/Utils/ElementsPanel.h index cb4e27c1..0877e7e4 100644 --- a/Libs/Editor/Include/Utils/ElementsPanel.h +++ b/Libs/Editor/Include/Utils/ElementsPanel.h @@ -1,23 +1,17 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include #include #include #include -#include +#include -namespace rift::Editor +namespace rift::editor { struct CTypeEditor; @@ -29,14 +23,14 @@ namespace rift::Editor }; using TVariableAccessRef = - p::TAccessRef, p::TWrite, AST::CDeclType, - AST::CDeclNative, AST::CDeclStruct, AST::CDeclClass, AST::CParent>; + p::TAccessRef, p::TWrite, ast::CDeclType, + ast::CDeclNative, ast::CDeclStruct, ast::CDeclClass, ast::CParent>; - void DrawField(AST::Tree& ast, CTypeEditor& editor, AST::Id functionId, AST::Id fieldId, + void DrawField(ast::Tree& ast, CTypeEditor& editor, ast::Id functionId, ast::Id fieldId, DrawFieldFlags flags = DrawFieldFlags::None); - void DrawVariable(TVariableAccessRef access, CTypeEditor& editor, AST::Id variableId); - void DrawFunction(AST::Tree& ast, CTypeEditor& editor, AST::Id functionId); + void DrawVariable(TVariableAccessRef access, CTypeEditor& editor, ast::Id variableId); + void DrawFunction(ast::Tree& ast, CTypeEditor& editor, ast::Id functionId); - void DrawElementsPanel(AST::Tree& ast, AST::Id typeId); -} // namespace rift::Editor + void DrawElementsPanel(ast::Tree& ast, ast::Id typeId); +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/FunctionGraph.h b/Libs/Editor/Include/Utils/FunctionGraph.h index 8a732931..658ec124 100644 --- a/Libs/Editor/Include/Utils/FunctionGraph.h +++ b/Libs/Editor/Include/Utils/FunctionGraph.h @@ -1,11 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Components/CTypeEditor.h" #include -#include +#include namespace rift @@ -13,7 +13,7 @@ namespace rift struct DockSpaceLayout; } -namespace rift::Editor::Graph +namespace rift::editor::Graph { struct Settings { @@ -37,12 +37,12 @@ namespace rift::Editor::Graph inline Settings settings{}; - void DrawLiteralBool(AST::Tree& ast, AST::Id id, bool& value); - void DrawLiteralInt(AST::Tree& ast, AST::Id id, String& value); - void DrawLiteralString(AST::Tree& ast, AST::Id id, String& value); + void DrawLiteralBool(ast::Tree& ast, ast::Id id, bool& value); + void DrawLiteralInt(ast::Tree& ast, ast::Id id, String& value); + void DrawLiteralString(ast::Tree& ast, ast::Id id, String& value); - void DrawFunctionDecl(AST::Tree& ast, AST::Id functionId); - void DrawCallNode(AST::Tree& ast, AST::Id id, StringView name, StringView ownerName); + void DrawFunctionDecl(ast::Tree& ast, ast::Id functionId); + void DrawCallNode(ast::Tree& ast, ast::Id id, StringView name, StringView ownerName); void Init(); void Shutdown(); @@ -52,10 +52,10 @@ namespace rift::Editor::Graph void PushInnerNodeStyle(); void PopInnerNodeStyle(); - void DrawTypeGraph(AST::Tree& ast, AST::Id typeId, CTypeEditor& typeEditor); + void DrawTypeGraph(ast::Tree& ast, ast::Id typeId, CTypeEditor& typeEditor); - void SetNodePosition(AST::Id id, v2 position); - v2 GetNodePosition(AST::Id id); + void SetNodePosition(ast::Id id, v2 position); + v2 GetNodePosition(ast::Id id); void SnapNodeDimensionsToGrid(); -} // namespace rift::Editor::Graph +} // namespace rift::editor::Graph diff --git a/Libs/Editor/Include/Utils/FunctionGraphContextMenu.h b/Libs/Editor/Include/Utils/FunctionGraphContextMenu.h index 9e99fa4c..8e92fcb9 100644 --- a/Libs/Editor/Include/Utils/FunctionGraphContextMenu.h +++ b/Libs/Editor/Include/Utils/FunctionGraphContextMenu.h @@ -1,14 +1,14 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include +#include -namespace rift::Editor::Graph +namespace rift::editor::Graph { - void DrawNodesContextMenu(AST::Tree& ast, AST::Id typeId, p::TView nodeIds); - void DrawGraphContextMenu(AST::Tree& ast, AST::Id typeId, AST::Id hoveredNodeId); + void DrawNodesContextMenu(ast::Tree& ast, ast::Id typeId, p::TView nodeIds); + void DrawGraphContextMenu(ast::Tree& ast, ast::Id typeId, ast::Id hoveredNodeId); void DrawContextMenu( - AST::Tree& ast, AST::Id typeId, AST::Id hoveredNodeId, AST::Id hoveredLinkId); -} // namespace rift::Editor::Graph + ast::Tree& ast, ast::Id typeId, ast::Id hoveredNodeId, ast::Id hoveredLinkId); +} // namespace rift::editor::Graph diff --git a/Libs/Editor/Include/Utils/ModuleUtils.h b/Libs/Editor/Include/Utils/ModuleUtils.h index 1a828b1c..0a4a11ed 100644 --- a/Libs/Editor/Include/Utils/ModuleUtils.h +++ b/Libs/Editor/Include/Utils/ModuleUtils.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -9,9 +9,9 @@ #include -namespace rift::Editor +namespace rift::editor { - void OpenModuleEditor(TAccessRef, AST::CModule> access, AST::Id id); - void CloseModuleEditor(TAccessRef, AST::CModule> access, AST::Id id); - bool IsEditingModule(TAccessRef access, AST::Id id); -} // namespace rift::Editor + void OpenModuleEditor(p::TAccessRef, ast::CModule> access, ast::Id id); + void CloseModuleEditor(p::TAccessRef, ast::CModule> access, ast::Id id); + bool IsEditingModule(p::TAccessRef access, ast::Id id); +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/Nodes.h b/Libs/Editor/Include/Utils/Nodes.h index e33f70dd..163f8502 100644 --- a/Libs/Editor/Include/Utils/Nodes.h +++ b/Libs/Editor/Include/Utils/Nodes.h @@ -1,15 +1,15 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include #include -#include -#include +#include +#include #include #ifdef IMNODES_USER_CONFIG -# include IMNODES_USER_CONFIG + #include IMNODES_USER_CONFIG #endif struct ImGuiContext; @@ -298,7 +298,7 @@ namespace rift::Nodes void SetEditorContext(EditorContext*); v2 GetPanning(); void ResetPanning(const v2& pos); - void MoveToNode(AST::Id nodeId, v2 offset = v2::Zero()); + void MoveToNode(ast::Id nodeId, v2 offset = v2::Zero()); IO& GetIO(); @@ -339,10 +339,10 @@ namespace rift::Nodes // id can be any positive or negative integer, but INT_MIN is currently reserved for // internal use. - void BeginNode(AST::Id id); + void BeginNode(ast::Id id); void EndNode(); - v2 GetNodeDimensions(AST::Id id); + v2 GetNodeDimensions(ast::Id id); // Place your node title bar content (such as the node title, using ImGui::Text) between the // following function calls. These functions have to be called before adding any attributes, @@ -390,22 +390,22 @@ namespace rift::Nodes // Use the following functions to get and set the node's coordinates in these coordinate // systems. - void SetNodeScreenSpacePos(AST::Id nodeId, const v2& screen_space_pos); - void SetNodeEditorSpacePos(AST::Id nodeId, const v2& editor_space_pos); - void SetNodeGridSpacePos(AST::Id nodeId, const v2& grid_pos); + void SetNodeScreenSpacePos(ast::Id nodeId, const v2& screen_space_pos); + void SetNodeEditorSpacePos(ast::Id nodeId, const v2& editor_space_pos); + void SetNodeGridSpacePos(ast::Id nodeId, const v2& grid_pos); - v2 GetNodeScreenSpacePos(AST::Id nodeId); - v2 GetNodeEditorSpacePos(AST::Id nodeId); - v2 GetNodeGridSpacePos(AST::Id nodeId); + v2 GetNodeScreenSpacePos(ast::Id nodeId); + v2 GetNodeEditorSpacePos(ast::Id nodeId); + v2 GetNodeGridSpacePos(ast::Id nodeId); // Returns true if the current node editor canvas is being hovered over by the mouse, and is // not blocked by any other windows. bool IsEditorHovered(); - AST::Id GetHoveredNode(); - AST::Id GetHoveredLink(); + ast::Id GetHoveredNode(); + ast::Id GetHoveredLink(); - bool IsNodeHovered(AST::Id nodeId); - bool IsLinkHovered(AST::Id linkId); + bool IsNodeHovered(ast::Id nodeId); + bool IsLinkHovered(ast::Id linkId); bool IsPinHovered(Id* attributeId); // Use The following two functions to query the number of selected nodes or links in the @@ -414,8 +414,8 @@ namespace rift::Nodes // Get the selected node/link ids. The pointer argument should point to an integer array // with at least as many elements as the respective NumSelectedNodes/NumSelectedLinks // function call returned. - const TArray& GetSelectedNodes(); - bool GetSelectedLinks(TArray& linkIds); + const TArray& GetSelectedNodes(); + bool GetSelectedLinks(TArray& linkIds); // Clears the list of selected nodes/links. Useful if you want to delete a selected node or // link. void ClearNodeSelection(); @@ -426,11 +426,11 @@ namespace rift::Nodes // considered unselected. Clear-functions has the precondition that the object is currently // considered selected. Preconditions listed above can be checked via // IsNodeSelected/IsLinkSelected if not already known. - void ClearNodeSelection(AST::Id nodeId); + void ClearNodeSelection(ast::Id nodeId); void ClearLinkSelection(Id linkId); - void SelectNode(AST::Id nodeId); + void SelectNode(ast::Id nodeId); void SelectLink(Id linkId); - bool IsNodeSelected(AST::Id nodeId); + bool IsNodeSelected(ast::Id nodeId); bool IsLinkSelected(Id linkId); bool IsLinkSelectedByIdx(i32 linkIdx); @@ -456,7 +456,7 @@ namespace rift::Nodes Id* outputId = nullptr, Id* inputId = nullptr, bool includingDetachedLinks = true); // Did the user finish creating a new link? bool IsLinkCreated(Id& outputPinId, Id& inputPinId, bool* createdFromSnap = nullptr); - bool IsLinkCreated(AST::Id& outputNodeId, Id& outputPinId, AST::Id& inputNodeId, Id& inputPinId, + bool IsLinkCreated(ast::Id& outputNodeId, Id& outputPinId, ast::Id& inputNodeId, Id& inputPinId, bool* createdFromSnap = nullptr); // Was an existing link detached from a pin by the user? The detached link's id is assigned diff --git a/Libs/Editor/Include/Utils/NodesInternal.h b/Libs/Editor/Include/Utils/NodesInternal.h index 2ad7be87..117591c3 100644 --- a/Libs/Editor/Include/Utils/NodesInternal.h +++ b/Libs/Editor/Include/Utils/NodesInternal.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "UI/UIImgui.h" @@ -10,8 +10,8 @@ #include #include #include -#include -#include +#include +#include // the structure of this file: @@ -91,18 +91,18 @@ namespace rift::Nodes template struct TIndexedArray { - using Iterator = TArray::Iterator; - using ConstIterator = TArray::ConstIterator; + using Iterator = TArray::Iterator; + using ConstIterator = TArray::ConstIterator; - TArray frameIds; + TArray frameIds; TArray data; - TArray lastFrameIds; - TArray invalidIds; + TArray lastFrameIds; + TArray invalidIds; public: - T& GetOrAdd(AST::Id id, bool* outAdded = nullptr) + T& GetOrAdd(ast::Id id, bool* outAdded = nullptr) { const u32 index = GetIdIndex(id); bool added; @@ -125,17 +125,17 @@ namespace rift::Nodes return *GetByIndex(index); } - T& Get(AST::Id id) + T& Get(ast::Id id) { return *GetByIndex(GetIdIndex(id)); } - const T& Get(AST::Id id) const + const T& Get(ast::Id id) const { return const_cast*>(this)->Get(id); } - T* TryGet(AST::Id id) + T* TryGet(ast::Id id) { if (Contains(id)) { @@ -144,16 +144,16 @@ namespace rift::Nodes return nullptr; } - bool Contains(AST::Id id) const + bool Contains(ast::Id id) const { return frameIds.ContainsSorted(id); } - T& operator[](AST::Id id) + T& operator[](ast::Id id) { return Get(id); } - const T& operator[](AST::Id id) const + const T& operator[](ast::Id id) const { return Get(id); } @@ -161,7 +161,7 @@ namespace rift::Nodes void CacheInvalidIds() { invalidIds.Clear(false); - for (AST::Id id : lastFrameIds) + for (ast::Id id : lastFrameIds) { if (!frameIds.ContainsSorted(id)) { @@ -190,7 +190,7 @@ namespace rift::Nodes private: T* GetByIndex(u32 index) { - Check(data.IsValidIndex(index)); + P_Check(data.IsValidIndex(index)); return data.Data() + index; } }; @@ -198,10 +198,10 @@ namespace rift::Nodes template struct NodeArray : public TIndexedArray { - TArray depthOrder; + TArray depthOrder; - T& GetOrAdd(AST::Id id, bool* outAdded = nullptr) + T& GetOrAdd(ast::Id id, bool* outAdded = nullptr) { bool added = false; T& node = TIndexedArray::GetOrAdd(id, &added); @@ -217,7 +217,7 @@ namespace rift::Nodes return node; } - void PushToTheFront(AST::Id id) + void PushToTheFront(ast::Id id) { depthOrder.Remove(id, false); depthOrder.Add(id); @@ -225,7 +225,7 @@ namespace rift::Nodes void ClearDepthOrder() { - depthOrder.RemoveIf([this](AST::Id id) { + depthOrder.RemoveIf([this](ast::Id id) { return TIndexedArray::invalidIds.ContainsSorted(id); }); } @@ -316,7 +316,7 @@ namespace rift::Nodes struct PinData { Id id; - AST::Id parentNodeId = AST::NoId; + ast::Id parentNodeId = ast::NoId; Rect rect; PinShape Shape = PinShape_CircleFilled; v2 position; // screen-space coordinates @@ -405,7 +405,7 @@ namespace rift::Nodes // Nodes::EndNode() call. Rect gridContentBounds; - TArray selectedNodeIds; + TArray selectedNodeIds; ImVector selectedLinkIndices; // Relative origins of selected nodes for snapping of dragged nodes @@ -458,8 +458,8 @@ namespace rift::Nodes // Canvas draw list and helper state ImDrawList* CanvasDrawList; ImGuiStorage NodeIdxToSubmissionIdx; - ImVector nodeSubmissionOrder; - ImVector nodeIdsOverlappingWithMouse; + ImVector nodeSubmissionOrder; + ImVector nodeIdsOverlappingWithMouse; ImVector occludedPinIndices; // Canvas extents @@ -480,11 +480,11 @@ namespace rift::Nodes ImVector pinFlagStack; // UI element state - AST::Id currentNodeId; + ast::Id currentNodeId; PinIdx CurrentPinIdx; i32 CurrentPinId; - AST::Id hoveredNodeId; + ast::Id hoveredNodeId; OptionalIndex HoveredLinkIdx; PinIdx HoveredPinIdx; @@ -561,7 +561,7 @@ namespace rift::Nodes if (objects.availableIds.IsEmpty()) { index = objects.pool.Size(); - Check(objects.pool.Size() == objects.inUse.Size()); + P_Check(objects.pool.Size() == objects.inUse.Size()); const i32 newSize = objects.pool.Size() + 1; objects.pool.Resize(newSize); objects.inUse.Resize(newSize); diff --git a/Libs/Editor/Include/Utils/NodesMiniMap.h b/Libs/Editor/Include/Utils/NodesMiniMap.h index 5e87965b..4442eab3 100644 --- a/Libs/Editor/Include/Utils/NodesMiniMap.h +++ b/Libs/Editor/Include/Utils/NodesMiniMap.h @@ -1,10 +1,10 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include -#include +#include +#include namespace rift::Nodes @@ -24,7 +24,7 @@ namespace rift::Nodes struct MiniMap { - using NodeHoveringCallback = void (*)(AST::Id, void*); + using NodeHoveringCallback = void (*)(ast::Id, void*); using NodeHoveringCallbackUserData = void*; @@ -44,7 +44,7 @@ namespace rift::Nodes bool IsHovered() const; void CalculateLayout(); - void DrawNode(EditorContext& editor, const AST::Id nodeId); + void DrawNode(EditorContext& editor, const ast::Id nodeId); void DrawLink(EditorContext& editor, const i32 linkIdx); void Update(); }; diff --git a/Libs/Editor/Include/Utils/ProjectManager.h b/Libs/Editor/Include/Utils/ProjectManager.h index e3834b2c..47fb0d9b 100644 --- a/Libs/Editor/Include/Utils/ProjectManager.h +++ b/Libs/Editor/Include/Utils/ProjectManager.h @@ -1,12 +1,12 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/ElementsPanel.h" #include -namespace rift::Editor +namespace rift::editor { - void DrawProjectManager(AST::Tree& ast); + void DrawProjectManager(ast::Tree& ast); void OpenProjectManager(); -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/TypeUtils.h b/Libs/Editor/Include/Utils/TypeUtils.h index fc02b5ce..3aa0258f 100644 --- a/Libs/Editor/Include/Utils/TypeUtils.h +++ b/Libs/Editor/Include/Utils/TypeUtils.h @@ -1,97 +1,96 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "Components/CTypeEditor.h" -#include -#include -#include +#include +#include #include -#include +#include -namespace rift::Editor +namespace rift::editor { - void OpenType(TAccessRef, AST::CDeclType> access, AST::Id id); - void CloseType(TAccessRef, AST::CDeclType> access, AST::Id id); - bool IsTypeOpen(TAccessRef access, AST::Id id); + void OpenType(p::TAccessRef, ast::CDeclType> access, ast::Id id); + void CloseType(p::TAccessRef, ast::CDeclType> access, ast::Id id); + bool IsTypeOpen(p::TAccessRef access, ast::Id id); - constexpr StringView GetUnaryOperatorName(AST::UnaryOperatorType type) + constexpr StringView GetUnaryOperatorName(ast::UnaryOperatorType type) { switch (type) { - case AST::UnaryOperatorType::Not: return "!"; - case AST::UnaryOperatorType::Negation: return "-"; - case AST::UnaryOperatorType::Increment: return "++"; - case AST::UnaryOperatorType::Decrement: return "--"; - case AST::UnaryOperatorType::BitNot: return "~"; + case ast::UnaryOperatorType::Not: return "!"; + case ast::UnaryOperatorType::Negation: return "-"; + case ast::UnaryOperatorType::Increment: return "++"; + case ast::UnaryOperatorType::Decrement: return "--"; + case ast::UnaryOperatorType::BitNot: return "~"; } return ""; } - constexpr StringView GetUnaryOperatorLongName(AST::UnaryOperatorType type) + constexpr StringView GetUnaryOperatorLongName(ast::UnaryOperatorType type) { switch (type) { - case AST::UnaryOperatorType::Not: return "not"; - case AST::UnaryOperatorType::Negation: return "negation"; - case AST::UnaryOperatorType::Increment: return "increment"; - case AST::UnaryOperatorType::Decrement: return "decrement"; - case AST::UnaryOperatorType::BitNot: return "bitwise not / one's complement"; + case ast::UnaryOperatorType::Not: return "not"; + case ast::UnaryOperatorType::Negation: return "negation"; + case ast::UnaryOperatorType::Increment: return "increment"; + case ast::UnaryOperatorType::Decrement: return "decrement"; + case ast::UnaryOperatorType::BitNot: return "bitwise not / one's complement"; } return ""; } - constexpr StringView GetBinaryOperatorName(AST::BinaryOperatorType type) + constexpr StringView GetBinaryOperatorName(ast::BinaryOperatorType type) { switch (type) { - case AST::BinaryOperatorType::Add: return "+"; - case AST::BinaryOperatorType::Sub: return "-"; - case AST::BinaryOperatorType::Mul: return "*"; - case AST::BinaryOperatorType::Div: return "/"; - case AST::BinaryOperatorType::Mod: return "%"; + case ast::BinaryOperatorType::Add: return "+"; + case ast::BinaryOperatorType::Sub: return "-"; + case ast::BinaryOperatorType::Mul: return "*"; + case ast::BinaryOperatorType::Div: return "/"; + case ast::BinaryOperatorType::Mod: return "%"; - case AST::BinaryOperatorType::Equal: return "=="; - case AST::BinaryOperatorType::NotEqual: return "!="; - case AST::BinaryOperatorType::Greater: return ">"; - case AST::BinaryOperatorType::Less: return "<"; - case AST::BinaryOperatorType::GreaterOrEqual: return ">="; - case AST::BinaryOperatorType::LessOrEqual: return "<="; + case ast::BinaryOperatorType::Equal: return "=="; + case ast::BinaryOperatorType::NotEqual: return "!="; + case ast::BinaryOperatorType::Greater: return ">"; + case ast::BinaryOperatorType::Less: return "<"; + case ast::BinaryOperatorType::GreaterOrEqual: return ">="; + case ast::BinaryOperatorType::LessOrEqual: return "<="; - case AST::BinaryOperatorType::And: return "&&"; - case AST::BinaryOperatorType::Or: return "||"; - case AST::BinaryOperatorType::BitAnd: return "&"; - case AST::BinaryOperatorType::BitOr: return "|"; - case AST::BinaryOperatorType::Xor: return "^"; + case ast::BinaryOperatorType::And: return "&&"; + case ast::BinaryOperatorType::Or: return "||"; + case ast::BinaryOperatorType::BitAnd: return "&"; + case ast::BinaryOperatorType::BitOr: return "|"; + case ast::BinaryOperatorType::Xor: return "^"; } return ""; } - constexpr StringView GetBinaryOperatorLongName(AST::BinaryOperatorType type) + constexpr StringView GetBinaryOperatorLongName(ast::BinaryOperatorType type) { switch (type) { - case AST::BinaryOperatorType::Add: return "add"; - case AST::BinaryOperatorType::Sub: return "subtract"; - case AST::BinaryOperatorType::Mul: return "multiply"; - case AST::BinaryOperatorType::Div: return "divide"; - case AST::BinaryOperatorType::Mod: return "module"; + case ast::BinaryOperatorType::Add: return "add"; + case ast::BinaryOperatorType::Sub: return "subtract"; + case ast::BinaryOperatorType::Mul: return "multiply"; + case ast::BinaryOperatorType::Div: return "divide"; + case ast::BinaryOperatorType::Mod: return "module"; - case AST::BinaryOperatorType::Equal: return "equal"; - case AST::BinaryOperatorType::NotEqual: return "not equal"; - case AST::BinaryOperatorType::Greater: return "greater"; - case AST::BinaryOperatorType::Less: return "less"; - case AST::BinaryOperatorType::GreaterOrEqual: return "greater or equal"; - case AST::BinaryOperatorType::LessOrEqual: return "less or equal"; + case ast::BinaryOperatorType::Equal: return "equal"; + case ast::BinaryOperatorType::NotEqual: return "not equal"; + case ast::BinaryOperatorType::Greater: return "greater"; + case ast::BinaryOperatorType::Less: return "less"; + case ast::BinaryOperatorType::GreaterOrEqual: return "greater or equal"; + case ast::BinaryOperatorType::LessOrEqual: return "less or equal"; - case AST::BinaryOperatorType::And: return "and"; - case AST::BinaryOperatorType::Or: return "or"; - case AST::BinaryOperatorType::BitAnd: return "bitwise and"; - case AST::BinaryOperatorType::BitOr: return "bitwise or"; - case AST::BinaryOperatorType::Xor: return "exclusive or"; + case ast::BinaryOperatorType::And: return "and"; + case ast::BinaryOperatorType::Or: return "or"; + case ast::BinaryOperatorType::BitAnd: return "bitwise and"; + case ast::BinaryOperatorType::BitOr: return "bitwise or"; + case ast::BinaryOperatorType::Xor: return "exclusive or"; } return ""; } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Include/Utils/Widgets.h b/Libs/Editor/Include/Utils/Widgets.h index 9eadc326..05677d96 100644 --- a/Libs/Editor/Include/Utils/Widgets.h +++ b/Libs/Editor/Include/Utils/Widgets.h @@ -1,23 +1,20 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include -#include -#include #include +#include #include #include -#include +#include -namespace rift::Editor +namespace rift::editor { - bool TypeCombo(AST::TAccessRef + bool TypeCombo(p::TAccessRef access, - p::StringView label, AST::Id& selectedTypeId); + p::StringView label, ast::Id& selectedTypeId); - bool InputLiteralValue(AST::Tree& ast, p::StringView label, AST::Id literalId); -} // namespace rift::Editor + bool InputLiteralValue(ast::Tree& ast, p::StringView label, ast::Id literalId); +} // namespace rift::editor diff --git a/Libs/Editor/Resources/Editor/Icons/Icon.png b/Libs/Editor/Resources/Editor/Icons/Icon.png deleted file mode 100644 index 838837b5..00000000 Binary files a/Libs/Editor/Resources/Editor/Icons/Icon.png and /dev/null differ diff --git a/Libs/Editor/Resources/Editor/Icons/Logo_128.png b/Libs/Editor/Resources/Editor/Icons/Logo_128.png new file mode 100644 index 00000000..ac590cff Binary files /dev/null and b/Libs/Editor/Resources/Editor/Icons/Logo_128.png differ diff --git a/Libs/Editor/Resources/Editor/Icons/Logo_256.png b/Libs/Editor/Resources/Editor/Icons/Logo_256.png new file mode 100644 index 00000000..64b6bcc6 Binary files /dev/null and b/Libs/Editor/Resources/Editor/Icons/Logo_256.png differ diff --git a/Libs/Editor/Resources/Editor/Icons/Logo_64.png b/Libs/Editor/Resources/Editor/Icons/Logo_64.png new file mode 100644 index 00000000..b279d951 Binary files /dev/null and b/Libs/Editor/Resources/Editor/Icons/Logo_64.png differ diff --git a/Libs/Editor/Src/DockSpaceLayout.cpp b/Libs/Editor/Src/DockSpaceLayout.cpp index 4fb96fe5..cbbfcb71 100644 --- a/Libs/Editor/Src/DockSpaceLayout.cpp +++ b/Libs/Editor/Src/DockSpaceLayout.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "DockSpaceLayout.h" @@ -7,7 +7,7 @@ #include -namespace rift::Editor +namespace rift::editor { const Tag DockSpaceLayout::rootNodeId{"root"}; @@ -34,14 +34,14 @@ namespace rift::Editor ImGuiDockNodeFlags& DockSpaceLayout::Builder::GetNodeLocalFlags(Tag nodeId) { const ImGuiID dockNodeId = layout.GetDockNodeId(nodeId); - Check(dockNodeId > 0); + P_Check(dockNodeId > 0); return ImGui::DockBuilderGetNode(dockNodeId)->LocalFlags; } ImGuiDockNodeFlags& DockSpaceLayout::Builder::GetNodeSharedFlags(Tag nodeId) { const ImGuiID dockNodeId = layout.GetDockNodeId(nodeId); - Check(dockNodeId > 0); + P_Check(dockNodeId > 0); return ImGui::DockBuilderGetNode(dockNodeId)->SharedFlags; } @@ -103,4 +103,4 @@ namespace rift::Editor } ImGui::DockBuilderFinish(dockSpaceID); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Editor.cpp b/Libs/Editor/Src/Editor.cpp index dac535b6..4eac0127 100644 --- a/Libs/Editor/Src/Editor.cpp +++ b/Libs/Editor/Src/Editor.cpp @@ -1,9 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Editor.h" #include "AST/Systems/FunctionsSystem.h" #include "AST/Utils/Namespaces.h" +#include "AST/Utils/Settings.h" +#include "Statics/EditorSettings.h" #include "Statics/SEditor.h" #include "Systems/EditorSystem.h" #include "Utils/FunctionGraph.h" @@ -15,38 +17,49 @@ #include #include #include -#include #include #include #include -namespace rift::Editor +namespace rift::editor { void RegisterKeyValueInspections() { - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { - UI::DrawKeyValue(label, data, GetType::Entity>()); + UI::RegisterCustomInspection([](p::StringView label, void* data, p::TypeId type) { + auto* id = static_cast(data); + // UI::DrawKeyValue(label, data, GetType::Entity>()); + UI::TableNextRow(); + UI::TableSetColumnIndex(0); + UI::AlignTextToFramePadding(); + UI::Text(label); + UI::TableSetColumnIndex(1); + String asString = p::ToString(*id); + if (UI::InputText("##value", asString)) + { + *id = p::IdFromString(asString, nullptr); + } }); - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { + UI::RegisterCustomInspection( + [](p::StringView label, void* data, p::TypeId type) { UI::TableNextRow(); UI::TableSetColumnIndex(0); UI::AlignTextToFramePadding(); UI::Text(label); UI::TableSetColumnIndex(1); - auto* ns = static_cast(data); + auto* ns = static_cast(data); String asString = ns->ToString(); if (UI::InputText("##value", asString)) { - *ns = AST::Namespace{asString}; + *ns = ast::Namespace{asString}; } }); } int Editor::Run(StringView projectPath) { - FileWatcher::StartAsync(); + fileWatcher.StartWatchingAsync(); // Setup window p::Info("Initializing editor..."); @@ -73,9 +86,11 @@ namespace rift::Editor UI::Render(); frameTime.PostTick(); - FrameMark; } + // Close the current project (if any) + CloseProject(); + Graph::Shutdown(); UI::Shutdown(); return 0; @@ -88,21 +103,25 @@ namespace rift::Editor void Editor::Tick() { - if (AST::HasProject(ast)) + if (ast::HasProject(ast)) { - AST::FunctionsSystem::ClearAddedTags(ast); - AST::TransactionSystem::ClearTags(ast); + ast::FunctionsSystem::ClearAddedTags(ast); + ast::TransactionSystem::ClearTags(ast); - AST::LoadSystem::Run(ast); - AST::FunctionsSystem::ResolveCallFunctionIds(ast); - AST::TypeSystem::ResolveExprTypeIds(ast); + if (filesDirty) + { + ast::LoadSystem::Run(ast); + filesDirty = false; + } + ast::FunctionsSystem::ResolveCallFunctionIds(ast); + ast::TypeSystem::ResolveExprTypeIds(ast); EditorSystem::Draw(ast); - AST::TypeSystem::PropagateVariableTypes(ast); - AST::FunctionsSystem::PropagateDirtyIntoCalls(ast); - AST::FunctionsSystem::PushInvalidPinsBack(ast); - AST::FunctionsSystem::SyncCallPinsFromFunction(ast); - AST::TypeSystem::PropagateExpressionTypes(ast); + ast::TypeSystem::PropagateVariableTypes(ast); + ast::FunctionsSystem::PropagateDirtyIntoCalls(ast); + ast::FunctionsSystem::PushInvalidPinsBack(ast); + ast::FunctionsSystem::SyncCallPinsFromFunction(ast); + ast::TypeSystem::PropagateExpressionTypes(ast); } else { @@ -110,28 +129,28 @@ namespace rift::Editor } } - void Editor::SetUIConfigFile(Path path) + void Editor::SetUIConfigFile(p::StringView path) { if (UI::GetWindow()) { configFileChanged = true; - configFile = p::ToString(path); + configFile = path; ImGui::GetIO().IniFilename = configFile.c_str(); } } bool Editor::CreateProject(p::StringView path, bool closeFirst) { - if (!closeFirst && AST::HasProject(ast)) + if (!closeFirst && ast::HasProject(ast)) { return false; } - if (AST::CreateProject(ast, path) && AST::OpenProject(ast, path)) + if (ast::CreateProject(ast, path) && ast::OpenProject(ast, path)) { ast.SetStatic(); EditorSystem::Init(ast); - SetUIConfigFile(p::JoinPaths(AST::GetProjectPath(ast), "Saved/UI.ini")); + SetUIConfigFile(p::JoinPaths(ast::GetProjectPath(ast), "Saved/UI.ini")); return true; } return false; @@ -139,21 +158,44 @@ namespace rift::Editor bool Editor::OpenProject(p::StringView path, bool closeFirst) { - if (!closeFirst && AST::HasProject(ast)) + if (!closeFirst && ast::HasProject(ast)) { return false; } - if (AST::OpenProject(ast, path)) + if (ast::OpenProject(ast, path)) { ast.SetStatic(); EditorSystem::Init(ast); - SetUIConfigFile(p::JoinPaths(AST::GetProjectPath(ast), "Saved/UI.ini")); + auto projectPath = ast::GetProjectPath(ast); + SetUIConfigFile(p::JoinPaths(projectPath, "Saved/UI.ini")); + + // Start watching the project folder for file changes + ast.Add(GetProjectId(ast), fileWatcher.ListenPath(projectPath, true, + [](FileWatchId id, StringView path, StringView filename, + FileWatchAction action, StringView oldFilename) { + Editor::Get().filesDirty = true; + })); + + + auto& editorSettings = GetUserSettings(); + editorSettings.recentProjects.AddUnique(p::String(projectPath)); + SaveUserSettings(); return true; } return false; } + void Editor::CloseProject() + { + Id id = GetProjectId(ast); + if (ast.IsValid(id) && ast.Has(id)) + { + fileWatcher.StopListening(ast.Get(id)); + } + ast::CloseProject(ast); + } + void Editor::Close() { rift::UI::Close(); @@ -169,7 +211,7 @@ namespace rift::Editor return; } - if (files::ExistsAsFile(configFile)) + if (ExistsAsFile(configFile)) { // FIX: Delay this until new frame (essentially, not while already drawing) ImGui::LoadIniSettingsFromDisk(configFile.c_str()); @@ -181,4 +223,4 @@ namespace rift::Editor configFileChanged = false; } } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Panels/FileExplorerPanel.cpp b/Libs/Editor/Src/Panels/FileExplorerPanel.cpp index 76d54509..8e5faa37 100644 --- a/Libs/Editor/Src/Panels/FileExplorerPanel.cpp +++ b/Libs/Editor/Src/Panels/FileExplorerPanel.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Panels/FileExplorerPanel.h" @@ -18,26 +18,25 @@ #include #include #include -#include -#include #include -#include #include #include +#include #include +#include #include #include #include -namespace rift::Editor +namespace rift::editor { - void FileExplorerPanel::Draw(AST::Tree& ast) + void FileExplorerPanel::Draw(ast::Tree& ast) { // Open recently created types if (!pendingOpenCreatedPath.empty()) { - AST::Id typeId = AST::FindTypeByPath(ast, pendingOpenCreatedPath); + ast::Id typeId = ast::FindTypeByPath(ast, pendingOpenCreatedPath); if (!IsNone(typeId)) { OpenType(ast, typeId); @@ -68,9 +67,8 @@ namespace rift::Editor UI::End(); } - void FileExplorerPanel::DrawList(AST::Tree& ast) + void FileExplorerPanel::DrawList(ast::Tree& ast) { - ZoneScoped; // if (dirty) { CacheProjectFiles(ast); @@ -79,13 +77,12 @@ namespace rift::Editor UI::BeginChild("Files"); if (UI::BeginPopupContextWindow()) { - String projectPath{AST::GetProjectPath(ast)}; - DrawContextMenu(ast, projectPath, AST::NoId); + String projectPath{ast::GetProjectPath(ast)}; + DrawContextMenu(ast, projectPath, ast::NoId); UI::EndPopup(); } { - ZoneScopedN("Draw Files"); for (auto& item : folders[{}].items) { DrawItem(ast, item); @@ -94,11 +91,11 @@ namespace rift::Editor UI::EndChild(); } - void FileExplorerPanel::DrawContextMenu(AST::Tree& ast, StringView path, AST::Id itemId) + void FileExplorerPanel::DrawContextMenu(ast::Tree& ast, StringView path, ast::Id itemId) { const bool hasId = ast.IsValid(itemId); - const bool isType = hasId && ast.Has(itemId); - const bool isModule = hasId && ast.Has(itemId); + const bool isType = hasId && ast.Has(itemId); + const bool isModule = hasId && ast.Has(itemId); if (hasId) { @@ -125,7 +122,7 @@ namespace rift::Editor if (isType && UI::MenuItem("Delete")) { - AST::RemoveTypes(ast, itemId, true); + ast::RemoveTypes(ast, itemId, true); } UI::Separator(); @@ -135,9 +132,9 @@ namespace rift::Editor { if (UI::BeginMenu("Create type")) { - TArray types; - types.Reserve(AST::GetFileTypes().Size()); - for (const auto& type : AST::GetFileTypes()) + TArray types; + types.Reserve(ast::GetFileTypes().Size()); + for (const auto& type : ast::GetFileTypes()) { types.Add(&type); } @@ -172,13 +169,13 @@ namespace rift::Editor if (UI::MenuItem("Create folder")) { - p::CreateFolder(p::ToPath(path) / "NewFolder"); + p::CreateFolder(p::JoinPaths(path, "NewFolder")); } } if (UI::MenuItem("Show in Explorer")) { - PlatformProcess::ShowFolder(path); + PlatformPaths::ShowFolder(path); } } @@ -201,7 +198,7 @@ namespace rift::Editor parentPath = p::GetParentPath(parentPath); parentName = p::Tag{parentPath}; - const Item newItem{.id = AST::NoId, .path = p::String{lastPath}, .isFolder = true}; + const Item newItem{.id = ast::NoId, .path = p::String{lastPath}, .isFolder = true}; if (Folder* parent = folders.Find(parentName)) { parent->items.Add(newItem); @@ -213,9 +210,8 @@ namespace rift::Editor } void FileExplorerPanel::CacheProjectFiles( - TAccessRef access) + TAccessRef access) { - ZoneScoped; dirty = false; folders.Clear(); @@ -223,27 +219,27 @@ namespace rift::Editor // Set root folder (not displayed) folders.InsertDefaulted({}); - projectModuleId = AST::GetProjectId(access); + projectModuleId = ast::GetProjectId(access); // Create module folders - TArray modules = FindAllIdsWith(access); - TMap moduleFolders; + TArray modules = FindAllIdsWith(access); + TMap moduleFolders; moduleFolders.Reserve(modules.Size()); - for (AST::Id moduleId : modules) + for (ast::Id moduleId : modules) { - auto& file = access.Get(moduleId); + auto& file = access.Get(moduleId); p::StringView folderPath = p::GetParentPath(file.path); folders.InsertDefaulted(p::Tag{folderPath}); moduleFolders.Insert(moduleId, folderPath); } // Create folders between modules - for (AST::Id oneId : modules) + for (ast::Id oneId : modules) { bool insideOther = false; const p::StringView path = moduleFolders[oneId]; - for (AST::Id otherId : modules) + for (ast::Id otherId : modules) { if (oneId != otherId && Strings::StartsWith(path, moduleFolders[otherId])) // Is relative @@ -266,9 +262,9 @@ namespace rift::Editor } // Create items - for (AST::Id typeId : FindAllIdsWith(access)) + for (ast::Id typeId : FindAllIdsWith(access)) { - auto& file = access.Get(typeId); + auto& file = access.Get(typeId); if (!file.path.empty()) { InsertItem(Item{typeId, file.path}); @@ -288,26 +284,24 @@ namespace rift::Editor }); } - void FileExplorerPanel::DrawItem(AST::Tree& ast, const Item& item) + void FileExplorerPanel::DrawItem(ast::Tree& ast, const Item& item) { const String path = p::ToString(item.path); const StringView fileName = p::GetFilename(path); + const StringView dirty = + (item.id != ast::NoId && ast.Has(item.id)) ? " *" : ""; + if (Folder* folder = folders.Find(p::Tag{item.path})) { ImGuiTreeNodeFlags flags = 0; - if (folder->items.IsEmpty()) - { - flags |= ImGuiTreeNodeFlags_Bullet; - } - - auto* module = item.id != AST::NoId ? ast.TryGet(item.id) : nullptr; + auto* module = item.id != ast::NoId ? ast.TryGet(item.id) : nullptr; if (module) { // TODO: Display module name - const String text = Strings::Format(ICON_FA_BOX " {}", fileName); + const String text = Strings::Format(ICON_FA_TH_LARGE " {}{}", fileName, dirty); - UI::PushHeaderColor(UI::primaryColor); + UI::PushHeaderColor(UI::GetNeutralColor(1)); UI::PushStyleCompact(); const bool isProject = item.id == projectModuleId; if (item.id == projectModuleId) // Is project @@ -365,13 +359,21 @@ namespace rift::Editor else { String text; - if (fileName == AST::moduleFilename) + if (fileName == ast::moduleFilename) { - text = Strings::Format(ICON_FA_FILE_ALT " {}", fileName); + text = Strings::Format(ICON_FA_TH_LARGE " {}{}", fileName, dirty); } else if (Strings::EndsWith(fileName, ".rf")) { - text = Strings::Format(ICON_FA_FILE_CODE " {}", fileName.data()); + StringView icon; + if (ast::IsStructType(ast, item.id)) + icon = ICON_FA_FILE_ALT; + else if (ast::IsClassType(ast, item.id)) + icon = ICON_FA_FILE_INVOICE; + else if (ast::IsStaticType(ast, item.id)) + icon = ICON_FA_FILE_WORD; + + text = Strings::Format("{} {}{}", icon, fileName, dirty); } else { @@ -382,7 +384,7 @@ namespace rift::Editor { UI::TreeNodeEx( text.c_str(), ImGuiTreeNodeFlags_Leaf | ImGuiTreeNodeFlags_NoTreePushOnOpen); - if (UI::IsItemHovered() && UI::IsKeyReleased(GLFW_KEY_F2)) + if (UI::IsItemHovered() && UI::IsKeyReleased(ImGuiKey_F2)) { renameId = item.id; renameBuffer = Strings::RemoveFromEnd(fileName, ".rf"); @@ -398,10 +400,11 @@ namespace rift::Editor } UI::InputText("##newname", renameBuffer, ImGuiInputTextFlags_AutoSelectAll); - const StringView parsedNewName = Strings::RemoveFromEnd(renameBuffer, ".rf"); - const bool nameIsEmpty = parsedNewName.empty(); + const StringView parsedNewName = + Strings::RemoveFromEnd(p::StringView{renameBuffer}, ".rf"); + const bool nameIsEmpty = parsedNewName.empty(); const Id sameNameFuncId = - AST::FindChildByName(ast, p::GetParent(ast, item.id), Tag{parsedNewName}); + ast::FindChildByName(ast, p::GetIdParent(ast, item.id), Tag{parsedNewName}); if (nameIsEmpty || (!IsNone(sameNameFuncId) && item.id != sameNameFuncId)) { UI::PushTextColor(LinearColor::Red()); @@ -418,27 +421,27 @@ namespace rift::Editor p::ReplaceExtension(destination, "rf"); // TODO: Move this into systems. Renaming a type shouldnt require so many // manual steps - if (files::Rename(p::ToPath(path), destination)) + if (Rename(path, destination)) { - if (auto* file = ast.TryGet(item.id)) + if (auto* file = ast.TryGet(item.id)) { file->path = destination; } - auto& types = ast.GetOrSetStatic(); + auto& types = ast.GetOrSetStatic(); types.typesByPath.Remove(p::Tag{item.path}); types.typesByPath.Insert(p::Tag{destination}, item.id); - ast.Add(item.id, Tag{parsedNewName}); + ast.Add(item.id, Tag{parsedNewName}); } - renameId = AST::NoId; + renameId = ast::NoId; renameBuffer = ""; renameHasFocused = false; } else if (UI::IsItemDeactivated()) { - renameId = AST::NoId; + renameId = ast::NoId; renameBuffer = ""; renameHasFocused = false; } @@ -462,30 +465,30 @@ namespace rift::Editor if (IsTypeOpen(ast, item.id)) { - UI::SameLine(ImGui::GetContentRegionAvailWidth(), 0); + UI::SameLine(ImGui::GetContentRegionAvail().x, 0); UI::Bullet(); UI::NewLine(); } } } - void FileExplorerPanel::DrawModuleActions(AST::Id id, AST::CModule& module) {} - void FileExplorerPanel::DrawTypeActions(AST::Id id, AST::CDeclType& type) {} + void FileExplorerPanel::DrawModuleActions(ast::Id id, ast::CModule& module) {} + void FileExplorerPanel::DrawTypeActions(ast::Id id, ast::CDeclType& type) {} void FileExplorerPanel::CreateType( - AST::Tree& ast, StringView title, p::Tag typeId, p::StringView folderPath) + ast::Tree& ast, StringView title, p::Tag typeId, p::StringView folderPath) { - const p::String path = files::SaveFileDialog(title, folderPath, + const p::String path = p::SaveFileDialog(title, folderPath, { {"Rift Type", Strings::Format("*.{}", Paths::typeExtension)} }, true); - AST::Id id = AST::CreateType(ast, typeId, Tag::None(), path); + ast::Id id = ast::CreateType(ast, typeId, Tag::None(), path); String data; - AST::SerializeType(ast, id, data); - files::SaveStringFile(path, data); + ast::SerializeType(ast, id, data); + SaveStringFile(StringView{path}, data); // Destroy the temporal type after saving it ast.Destroy(id); @@ -493,4 +496,4 @@ namespace rift::Editor // Mark path to be opened later once the type has loaded pendingOpenCreatedPath = path; } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Systems/EditorSystem.cpp b/Libs/Editor/Src/Systems/EditorSystem.cpp index 23ab782a..85fdd95e 100644 --- a/Libs/Editor/Src/Systems/EditorSystem.cpp +++ b/Libs/Editor/Src/Systems/EditorSystem.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Systems/EditorSystem.h" @@ -19,26 +19,27 @@ #include "Utils/ProjectManager.h" #include "Utils/TypeUtils.h" -#include #include #include +#include #include #include #include -#include -#include +#include #include -#include -#include +#include +#include +#include +#include #include #include #include #include -namespace rift::Editor::EditorSystem +namespace rift::editor::EditorSystem { - void OnProjectEditorOpen(AST::Tree& ast) + void OnProjectEditorOpen(ast::Tree& ast) { auto& editor = ast.GetStatic(); editor.layout.OnBuild([](auto& builder) { @@ -61,7 +62,7 @@ namespace rift::Editor::EditorSystem editor.layout.Reset(); } - void OnTypeEditorOpen(AST::Tree& ast, AST::Id typeId) + void OnTypeEditorOpen(ast::Tree& ast, ast::Id typeId) { auto& typeEditor = ast.Get(typeId); typeEditor.layout.OnBuild([](auto& builder) { @@ -89,13 +90,13 @@ namespace rift::Editor::EditorSystem typeEditor.layout.Reset(); } - void Init(AST::Tree& ast) + void Init(ast::Tree& ast) { OnProjectEditorOpen(ast); ast.OnAdd().Bind([](auto& ast, auto ids) { - for (AST::Id id : ids) + for (ast::Id id : ids) { - OnTypeEditorOpen(static_cast(ast), id); + OnTypeEditorOpen(static_cast(ast), id); } }); } @@ -104,25 +105,23 @@ namespace rift::Editor::EditorSystem void CreateRootDockspace(SEditor& editor); void CreateTypeDockspace(CTypeEditor& editor, const char* id); void CreateModuleDockspace(CModuleEditor& editor, const char* id); - void DrawMenuBar(AST::Tree& ast); + void DrawMenuBar(ast::Tree& ast); // Project Editor - void DrawProject(AST::Tree& ast); - void DrawProjectMenuBar(AST::Tree& ast, SEditor& editorData); + void DrawProject(ast::Tree& ast); + void DrawProjectMenuBar(ast::Tree& ast, SEditor& editorData); // Module Editors - void DrawModuleEditors(AST::Tree& ast, SEditor& editor); + void DrawModuleEditors(ast::Tree& ast, SEditor& editor); // Type Editors - void DrawTypeMenuBar(AST::Tree& ast, AST::Id typeId); - void DrawTypes(AST::Tree& ast, SEditor& editor); + void DrawTypeMenuBar(ast::Tree& ast, ast::Id typeId); + void DrawTypes(ast::Tree& ast, SEditor& editor); - void Draw(AST::Tree& ast) + void Draw(ast::Tree& ast) { - ZoneScoped; - - if (AST::HasProject(ast)) + if (ast::HasProject(ast)) { DrawProject(ast); } @@ -158,7 +157,6 @@ namespace rift::Editor::EditorSystem void CreateRootDockspace(SEditor& editor) { - ZoneScoped; ImGuiDockNodeFlags dockingFlags = ImGuiDockNodeFlags_None; const auto& viewport = UI::GetMainViewport(); @@ -193,7 +191,6 @@ namespace rift::Editor::EditorSystem void CreateTypeDockspace(CTypeEditor& editor, const char* id) { - ZoneScoped; ImGuiDockNodeFlags dockingFlags = ImGuiDockNodeFlags_None; editor.dockspaceID = UI::GetID(id); @@ -201,7 +198,7 @@ namespace rift::Editor::EditorSystem UI::DockSpace(editor.dockspaceID, ImVec2(0.0f, 0.0f), dockingFlags, nullptr); } - void DrawMenuBar(AST::Tree& ast) + void DrawMenuBar(ast::Tree& ast) { if (UI::BeginMainMenuBar()) { @@ -219,18 +216,16 @@ namespace rift::Editor::EditorSystem } } - void DrawProject(AST::Tree& ast) + void DrawProject(ast::Tree& ast) { - ZoneScoped; - - if (!Ensure(ast.HasStatic())) + if (!P_Ensure(ast.HasStatic())) { return; } auto& editor = ast.GetStatic(); - const auto& path = AST::GetProjectPath(ast); - UI::PushID(Hash()(path)); + const auto& path = ast::GetProjectPath(ast); + UI::PushID(p::GetHash(path)); DrawProjectMenuBar(ast, editor); @@ -246,8 +241,8 @@ namespace rift::Editor::EditorSystem DrawModuleEditors(ast, editor); DrawTypes(ast, editor); - editor.reflectionDebugger.Draw(); - editor.astDebugger.Draw(ast); + editor.reflectionDebugger.Draw(ast); + editor.ASTDebugger.Draw(ast); editor.memoryDebugger.Draw(); editor.fileExplorer.Draw(ast); editor.graphPlayground.Draw(ast, editor.layout); @@ -255,7 +250,7 @@ namespace rift::Editor::EditorSystem UI::PopID(); } - void DrawProjectMenuBar(AST::Tree& ast, SEditor& editorData) + void DrawProjectMenuBar(ast::Tree& ast, SEditor& editorData) { if (UI::BeginMainMenuBar()) { @@ -263,8 +258,8 @@ namespace rift::Editor::EditorSystem { if (UI::MenuItem("Open Project")) { - const p::String folder = - files::SelectFolderDialog("Select project folder", p::GetCurrentPath()); + const p::String folder = p::SelectFolderDialog( + "Select project folder", p::PlatformPaths::GetCurrentPath()); if (Editor::Get().OpenProject(folder)) { editorData.skipFrameAfterMenu = true; @@ -272,42 +267,42 @@ namespace rift::Editor::EditorSystem } if (UI::MenuItem("Close current")) { - AST::CloseProject(ast); + Editor::Get().CloseProject(); editorData.skipFrameAfterMenu = true; } UI::Separator(); if (UI::MenuItem("Open File")) {} if (UI::MenuItem(ICON_FA_SAVE " Save All", "CTRL+SHFT+S")) { - TArray> fileDatas; + TArray> fileDatas; // Path to file data auto dirtyTypeIds = - FindAllIdsWith( + FindAllIdsWith( ast); - for (AST::Id typeId : dirtyTypeIds) + for (ast::Id typeId : dirtyTypeIds) { - auto& file = ast.Get(typeId); + auto& file = ast.Get(typeId); auto& fileData = fileDatas.AddRef({file.path, ""}); - AST::SerializeType(ast, typeId, fileData.second); + ast::SerializeType(ast, typeId, fileData.second); } auto dirtyModuleIds = - FindAllIdsWith( + FindAllIdsWith( ast); - for (AST::Id moduleId : dirtyModuleIds) + for (ast::Id moduleId : dirtyModuleIds) { - auto& file = ast.Get(moduleId); + auto& file = ast.Get(moduleId); auto& fileData = fileDatas.AddRef({file.path, ""}); - AST::SerializeModule(ast, moduleId, fileData.second); + ast::SerializeModule(ast, moduleId, fileData.second); } for (auto& fileData : fileDatas) { - files::SaveStringFile(fileData.first, fileData.second); + SaveStringFile(fileData.first, fileData.second); } - ast.Remove(dirtyTypeIds); - ast.Remove(dirtyModuleIds); + ast.Remove(dirtyTypeIds); + ast.Remove(dirtyModuleIds); UI::AddNotification({UI::ToastType::Success, 1.f, !fileDatas.IsEmpty() ? Strings::Format("Saved {} files", fileDatas.Size()) @@ -320,15 +315,15 @@ namespace rift::Editor::EditorSystem { if (UI::MenuItem("Build current")) { - AST::Tree compileAST{ast}; // Intentional copy + ast::Tree compileAST{ast}; // Intentional copy CompilerConfig config; - Build(compileAST, config); + Build(compileAST, config); } if (UI::MenuItem("Build all")) { - AST::Tree compileAST{ast}; // Intentional copy + ast::Tree compileAST{ast}; // Intentional copy CompilerConfig config; - Build(compileAST, config); + Build(compileAST, config); } UI::EndMenu(); } @@ -361,7 +356,8 @@ namespace rift::Editor::EditorSystem if (UI::BeginMenu("Debug")) { UI::MenuItem("Reflection", nullptr, &editorData.reflectionDebugger.open); - UI::MenuItem("Abstract Syntax Tree", nullptr, &editorData.astDebugger.open); + UI::MenuItem( + " " ICON_FA_BUG " AST Debugger", nullptr, &editorData.ASTDebugger.open); UI::MenuItem("Memory", nullptr, &editorData.memoryDebugger.open); UI::MenuItem("Graph Playground", nullptr, &editorData.graphPlayground.open); UI::EndMenu(); @@ -375,7 +371,7 @@ namespace rift::Editor::EditorSystem { editorData.layout.Reset(); - for (AST::Id typeId : FindAllIdsWith(ast)) + for (ast::Id typeId : FindAllIdsWith(ast)) { auto& editor = ast.Get(typeId); editor.layout.Reset(); @@ -387,18 +383,18 @@ namespace rift::Editor::EditorSystem } } - void DrawModuleMenuBar(AST::Tree& ast, AST::Id moduleId) + void DrawModuleMenuBar(ast::Tree& ast, ast::Id moduleId) { if (UI::BeginMenuBar()) { if (UI::MenuItem(ICON_FA_SAVE, "CTRL+S")) { - auto& file = ast.Get(moduleId); + auto& file = ast.Get(moduleId); String data; - AST::SerializeModule(ast, moduleId, data); + ast::SerializeModule(ast, moduleId, data); - files::SaveStringFile(file.path, data); - ast.Remove(moduleId); + SaveStringFile(StringView(file.path), data); + ast.Remove(moduleId); UI::AddNotification({UI::ToastType::Success, 1.f, Strings::Format("Saved file {}", p::GetFilename(file.path))}); @@ -407,23 +403,22 @@ namespace rift::Editor::EditorSystem } } - void DrawModuleEditors(AST::Tree& ast, SEditor& editor) + void DrawModuleEditors(ast::Tree& ast, SEditor& editor) { - TAccess, TWrite, TWrite, AST::CFileRef> + TAccess, TWrite, TWrite, ast::CFileRef> moduleEditors{ast}; - for (AST::Id moduleId : - FindAllIdsWith(moduleEditors)) + for (ast::Id moduleId : + FindAllIdsWith(moduleEditors)) { - ZoneScopedN("Draw Type"); - auto& moduleEditor = moduleEditors.Get(moduleId); - const auto& file = moduleEditors.Get(moduleId); + const auto& file = moduleEditors.Get(moduleId); bool isOpen = true; const String path = p::ToString(file.path); const StringView filename = p::GetFilename(path); - const StringView dirty = ast.Has(moduleId) ? "*" : ""; - const String windowName = Strings::Format("{}{}###{}", filename, dirty, moduleId); + const StringView dirty = ast.Has(moduleId) ? " *" : ""; + const String windowName = + Strings::Format(ICON_FA_TH_LARGE " {}{}###{}", filename, dirty, moduleId); if (moduleEditor.pendingFocus) { @@ -444,20 +439,20 @@ namespace rift::Editor::EditorSystem if (UI::BeginInspector("ModuleInspector")) { - auto& module = moduleEditors.Get(moduleId); + auto& module = moduleEditors.Get(moduleId); UI::InspectStruct(&module); - if (UI::BeginInspectHeader("Bindings")) + if (UI::BeginCategory("Bindings", true)) { - for (const auto& binding : AST::GetModuleBindings()) + for (const auto& binding : ast::GetModuleBindings()) { - auto* pool = ast.GetPool(binding.tagType->GetId()); + auto* pool = ast.GetPool(binding.tagType); if (void* data = pool ? pool->TryGetVoid(moduleId) : nullptr) { - if (UI::BeginInspectHeader(binding.displayName)) + if (UI::BeginCategory(binding.displayName, true)) { - UI::InspectProperties(data, binding.tagType); - UI::EndInspectHeader(); + UI::InspectChildrenProperties({data, binding.tagType}); + UI::EndCategory(); } } else @@ -470,12 +465,12 @@ namespace rift::Editor::EditorSystem if (UI::Button(addText.c_str(), ImVec2(-FLT_MIN, 0.0f))) { ScopedChange(ast, moduleId); - AST::AddBindingToModule(ast, moduleId, binding.id); + ast::AddBindingToModule(ast, moduleId, binding.id); } UI::PopStyleCompact(); } } - UI::EndInspectHeader(); + UI::EndCategory(); } UI::EndInspector(); } @@ -493,19 +488,19 @@ namespace rift::Editor::EditorSystem } } - void DrawTypeMenuBar(AST::Tree& ast, AST::Id typeId) + void DrawTypeMenuBar(ast::Tree& ast, ast::Id typeId) { auto& typeEditor = ast.Get(typeId); if (UI::BeginMenuBar()) { if (UI::MenuItem(ICON_FA_SAVE, "CTRL+S")) { - auto& file = ast.Get(typeId); + auto& file = ast.Get(typeId); String data; - AST::SerializeType(ast, typeId, data); + ast::SerializeType(ast, typeId, data); - files::SaveStringFile(file.path, data); - ast.Remove(typeId); + SaveStringFile(StringView(file.path), data); + ast.Remove(typeId); UI::AddNotification({UI::ToastType::Success, 1.f, Strings::Format("Saved file {}", p::GetFilename(file.path))}); @@ -513,7 +508,7 @@ namespace rift::Editor::EditorSystem if (UI::BeginMenu("View")) { - if (AST::HasFunctions(ast, typeId)) + if (ast::HasFunctions(ast, typeId)) { UI::MenuItem("Graph", nullptr, &typeEditor.showGraph); } @@ -525,23 +520,31 @@ namespace rift::Editor::EditorSystem } } - void DrawTypes(AST::Tree& ast, SEditor& editor) + void DrawTypes(ast::Tree& ast, SEditor& editor) { - ZoneScoped; - - TAccess, AST::CDeclType, AST::CFileRef> access{ast}; - for (AST::Id typeId : FindAllIdsWith(access)) + TAccess, ast::CDeclType, ast::CFileRef, ast::CDeclClass, + ast::CDeclStruct, ast::CDeclStatic> + access{ast}; + for (ast::Id typeId : FindAllIdsWith(access)) { - ZoneScopedN("Draw Type"); - auto& typeEditor = access.Get(typeId); - const auto& file = access.Get(typeId); + const auto& file = access.Get(typeId); + + + StringView icon; + if (ast::IsStructType(access, typeId)) + icon = ICON_FA_FILE_ALT; + else if (ast::IsClassType(access, typeId)) + icon = ICON_FA_FILE_INVOICE; + else if (ast::IsStaticType(access, typeId)) + icon = ICON_FA_FILE_WORD; bool isOpen = true; const String path = p::ToString(file.path); const StringView filename = p::GetFilename(path); - const StringView dirty = ast.Has(typeId) ? "*" : ""; - const String windowName = Strings::Format("{}{}###{}", filename, dirty, typeId); + const StringView dirty = ast.Has(typeId) ? " *" : ""; + const String windowName = + Strings::Format("{} {}{}###{}", icon, filename, dirty, typeId); if (typeEditor.pendingFocus) { @@ -562,12 +565,12 @@ namespace rift::Editor::EditorSystem CreateTypeDockspace(typeEditor, windowName.c_str()); - if (AST::HasFunctionBodies(ast, typeId)) + if (ast::HasFunctionBodies(ast, typeId)) { Graph::DrawTypeGraph(ast, typeId, typeEditor); } - if (AST::HasVariables(ast, typeId) || AST::HasFunctions(ast, typeId)) + if (ast::HasVariables(ast, typeId) || ast::HasFunctions(ast, typeId)) { typeEditor.layout.BindNextWindowToNode( CTypeEditor::rightBottomNode, ImGuiCond_Appearing); @@ -590,4 +593,4 @@ namespace rift::Editor::EditorSystem } } } -} // namespace rift::Editor::EditorSystem +} // namespace rift::editor::EditorSystem diff --git a/Libs/Editor/Src/Tools/ASTDebugger.cpp b/Libs/Editor/Src/Tools/ASTDebugger.cpp index def818d3..982e9efc 100644 --- a/Libs/Editor/Src/Tools/ASTDebugger.cpp +++ b/Libs/Editor/Src/Tools/ASTDebugger.cpp @@ -1,70 +1,29 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Tools/ASTDebugger.h" -#include +#include "imgui.h" +#include "PipeReflect.h" +#include "UI/Widgets.h" + +#include #include #include #include #include #include -#include +#include #include #include -namespace rift::Editor -{ - using namespace p::core; +#define P_DEBUG_IMPLEMENTATION +#include - void DrawEntityInspector(AST::Tree& ast, AST::Id entityId, bool* open = nullptr) - { - p::String name = "Entity Inspector"; - if (!IsNone(entityId)) - p::Strings::FormatTo(name, " (id:{})", entityId); - p::Strings::FormatTo(name, "###Entity Inspector"); - UI::Begin(name.c_str(), open); - if (IsNone(entityId)) - { - UI::End(); - return; - } - const auto& registry = AST::TypeRegistry::Get(); - for (const auto& poolInstance : ast.GetPools()) - { - AST::Type* type = registry.FindType(poolInstance.componentId); - if (!type || !poolInstance.GetPool()->Has(entityId)) - { - continue; - } - - void* data = poolInstance.GetPool()->TryGetVoid(entityId); - static p::String typeName; - typeName = type->GetName(); - - ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen; - if (!data) - { - flags |= ImGuiTreeNodeFlags_Leaf; - } - if (UI::CollapsingHeader(typeName.c_str(), flags)) - { - UI::Indent(); - auto* dataType = Cast(type); - if (data && dataType && UI::BeginInspector("EntityInspector")) - { - UI::InspectProperties(data, dataType); - UI::EndInspector(); - } - UI::Unindent(); - } - } - - UI::End(); - } - - void DrawTypesDebug(AST::Tree& ast) +namespace rift::editor +{ + void DrawTypesDebug(ast::Tree& ast) { if (!UI::CollapsingHeader("Types")) { @@ -74,10 +33,10 @@ namespace rift::Editor static const ImGuiTableFlags flags = ImGuiTableFlags_Reorderable | ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_SizingStretchProp; - if (auto* types = ast.TryGetStatic()) + if (auto* types = ast.TryGetStatic()) { UI::BeginChild("typesTableChild", - ImVec2(0.f, p::math::Min(250.f, UI::GetContentRegionAvail().y - 20.f))); + ImVec2(0.f, p::Min(250.f, UI::GetContentRegionAvail().y - 20.f))); if (UI::BeginTable("typesTable", 2, flags, ImVec2(0.f, UI::GetContentRegionAvail().y))) { UI::TableSetupColumn("Name"); @@ -107,195 +66,156 @@ namespace rift::Editor ASTDebugger::ASTDebugger() {} - void ASTDebugger::Draw(AST::Tree& ast) + void ASTDebugger::Draw(ast::Tree& ast) { if (!open) { return; } - UI::Begin("Abstract Syntax Tree", &open); - - DrawTypesDebug(ast); + auto& dbgContext = ast.GetOrSetStatic(); + dbgContext.ctx = * + p::BeginDebug(dbgContext); + p::DrawIdRegistry(" " ICON_FA_BUG " AST Debugger", &open); + p::EndDebug(); + } - if (UI::CollapsingHeader("Nodes")) + void ASTDebugger::OnInspectEntity(ast::Id id) + { + bool bOpenNewInspector = false; + if (ImGui::GetIO().KeyCtrl) // Inspector found and Ctrl? Open a new one { - if (ImGui::BeginPopup("Options")) - { - ImGui::Checkbox("Show hierarchy", &showHierarchy); - ImGui::EndPopup(); - } - - if (UI::Button("Options")) + OpenAvailableSecondaryInspector(id); + } + else + { + bool wasInspected = secondaryInspectors.RemoveIf([id](const auto& inspector) { + return inspector.id == id; + }) > 0; + if (mainInspector.id == id) { - UI::OpenPopup("Options"); + mainInspector.id = ast::NoId; + wasInspected = true; } - UI::SameLine(); - filter.Draw("##Filter", -100.0f); - - static ImGuiTableFlags flags = ImGuiTableFlags_Reorderable | ImGuiTableFlags_Resizable - | ImGuiTableFlags_Hideable - | ImGuiTableFlags_SizingStretchProp; - ImGui::BeginChild("nodesTableChild", {0.f, UI::GetContentRegionAvail().y - 20.f}); - if (UI::BeginTable("nodesTable", 5, flags)) + if (!wasInspected) { - UI::TableSetupColumn("", ImGuiTableColumnFlags_IndentDisable - | ImGuiTableColumnFlags_WidthFixed - | ImGuiTableColumnFlags_NoResize); // Inspect - UI::TableSetupColumn( - "Id", ImGuiTableColumnFlags_NoHide | ImGuiTableColumnFlags_IndentEnable); - UI::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 1.f); - UI::TableSetupColumn("Path", - ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide, 1.2f); - UI::TableSetupColumn("Namespace", - ImGuiTableColumnFlags_WidthStretch | ImGuiTableColumnFlags_DefaultHide, 1.2f); - UI::TableHeadersRow(); - - DrawNodeAccess access{ast}; - if (showHierarchy && !filter.IsActive()) - { - p::TArray roots; - p::GetRoots(access, roots); - for (auto root : roots) - { - DrawNode(access, root, true); - } - - p::TArray orphans = p::FindAllIdsWith(access); - p::ExcludeIdsWith(access, orphans); - p::ExcludeIdsWith(access, orphans); - for (auto orphan : orphans) - { - DrawNode(access, orphan, true); - } - } - else - { - ast.Each([this, &access](AST::Id id) { - DrawNode(access, id, false); - }); - } - UI::EndTable(); + mainInspector.id = id; + mainInspector.pendingFocus = true; } - UI::EndChild(); - UI::Separator(); } - UI::End(); - - DrawEntityInspector(ast, selectedNode, &open); } - void ASTDebugger::DrawNode(DrawNodeAccess access, AST::Id nodeId, bool showChildren) + void ASTDebugger::DrawEntityInspector(p::StringView label, p::StringView id, ast::Tree& ast, + InspectorPanel& inspector, bool* open) { - static p::String idText; - idText.clear(); - if (nodeId == AST::NoId) - { - idText = "No Id"; - } - else if (auto version = p::GetIdVersion(nodeId); version > 0) - { - p::Strings::FormatTo(idText, "{} (v{})", p::GetIdIndex(nodeId), version); - } - else - { - p::Strings::FormatTo(idText, "{}", p::GetIdIndex(nodeId)); - } + const bool valid = ast.IsValid(inspector.id); + const bool removed = ast.WasRemoved(inspector.id); + bool clone = false; + ast::Id changedId = inspector.id; + + p::String name; + p::Strings::FormatTo( + name, "{}: {}{}###{}", label, inspector.id, removed ? " (removed)" : "", id); - static p::String name; - name.clear(); - if (const auto* id = access.TryGet(nodeId)) + if (inspector.pendingFocus) { - name = id->name.AsString(); + ImGui::SetNextWindowFocus(); + inspector.pendingFocus = false; } - static p::String path; - path.clear(); - if (const auto* file = access.TryGet(nodeId)) + UI::SetNextWindowPos(ImGui::GetCursorScreenPos() + ImVec2(20, 20), ImGuiCond_Appearing); + UI::SetNextWindowSizeConstraints(ImVec2(300.f, 200.f), ImVec2(800, FLT_MAX)); + UI::BeginOuterStyle(); + UI::PushTextColor(valid && !removed ? UI::whiteTextColor : UI::errorColor); + ImGui::Begin(name.c_str(), open, ImGuiWindowFlags_MenuBar); + UI::PopTextColor(); + + if (ImGui::BeginMenuBar()) { - path = p::ToString(file->path); + if (ImGui::BeginMenu(ICON_FA_BARS)) + { + ImGui::AlignTextToFramePadding(); + ImGui::Text("Id"); + ImGui::SameLine(); + p::String asString = p::ToString(inspector.id); + ImGui::SetNextItemWidth(100.f); + if (UI::InputText("##IdValue", asString, + ImGuiInputTextFlags_EnterReturnsTrue | ImGuiInputTextFlags_EscapeClearsAll)) + { + changedId = p::IdFromString(asString, &ast); + } + ImGui::EndMenu(); + } - p::StringView filename = p::GetFilename(path); - p::Strings::FormatTo(name, name.empty() ? "file: {}" : " (file: {})", filename); + ImGui::SetCursorPosX(ImGui::GetCursorPosX() + ImGui::GetContentRegionAvail().x - 40.f); + if (ImGui::MenuItem("Clone")) + { + clone = true; + } + ImGui::EndMenuBar(); } - if (!filter.PassFilter(idText.c_str(), idText.c_str() + idText.size()) - && !filter.PassFilter(name.c_str(), name.c_str() + name.size())) - { - return; - } + UI::BeginInnerStyle(); - ImGui::TableNextRow(); - ImGui::TableNextColumn(); - static p::String inspectLabel; - inspectLabel.clear(); - p::Strings::FormatTo(inspectLabel, ICON_FA_SEARCH "##{}", nodeId); - UI::PushButtonColor(UI::GetNeutralColor(1)); - UI::PushTextColor( - selectedNode == nodeId ? UI::whiteTextColor : UI::whiteTextColor.Translucency(0.3f)); - if (UI::Button(inspectLabel.c_str())) + if (valid) { - selectedNode = nodeId; - } - UI::PopTextColor(); - UI::PopButtonColor(); + for (const auto& poolInstance : ast.GetPools()) + { + p::TypeId type = poolInstance.componentId; + if (!type.IsValid() || !poolInstance.GetPool()->Has(inspector.id)) + { + continue; + } + void* data = poolInstance.GetPool()->TryGetVoid(inspector.id); + static p::String typeName; + typeName = p::GetTypeName(type); - ImGui::TableNextColumn(); - bool hasChildren; - const AST::CParent* parent = nullptr; - if (showChildren) - { - parent = access.TryGet(nodeId); - hasChildren = parent && !parent->children.IsEmpty(); - } - else - { - hasChildren = false; + ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen; + if (!data) + { + flags |= ImGuiTreeNodeFlags_Leaf; + } + if (UI::CollapsingHeader(typeName.c_str(), flags)) + { + UI::Indent(); + if (p::HasTypeFlags(type, p::TF_Struct) + && UI::BeginInspector("EntityInspector")) + { + UI::InspectChildrenProperties({data, type}); + UI::EndInspector(); + } + UI::Unindent(); + } + } } + UI::End(); - bool open = false; - static Tag font{"WorkSans"}; - UI::PushFont(font, UI::FontMode::Bold); - if (hasChildren) - { - open = UI::TreeNodeEx(idText.c_str(), ImGuiTreeNodeFlags_SpanFullWidth); - } - else + // Update after drawing + if (changedId != inspector.id) { - UI::Indent(10.f); - UI::Text(idText); - UI::Unindent(10.f); + inspector.id = changedId; } - UI::PopFont(); - - - ImGui::TableNextColumn(); - UI::Text(name); - - if (ImGui::TableNextColumn()) + if (clone) { - UI::PushFont("WorkSans", UI::FontMode::Italic); - UI::Text(path); - UI::PopFont(); + OpenAvailableSecondaryInspector(inspector.id); } + } - if (ImGui::TableNextColumn()) + void ASTDebugger::OpenAvailableSecondaryInspector(ast::Id id) + { + p::i32 availableIndex = secondaryInspectors.FindIndex([](const auto& inspector) { + return !inspector.open || inspector.id == ast::NoId; + }); + if (availableIndex != p::NO_INDEX) { - UI::Text(AST::GetParentNamespace(access, nodeId).ToString()); + secondaryInspectors[availableIndex] = {id}; } - - - if (hasChildren && open) + else { - for (AST::Id child : parent->children) - { - DrawNode(access, child, true); - } - - UI::TreePop(); + secondaryInspectors.Add({id}); } } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Tools/BigBestFitArenaDebugger.cpp b/Libs/Editor/Src/Tools/BigBestFitArenaDebugger.cpp index 2bcd69bb..e616e0b6 100644 --- a/Libs/Editor/Src/Tools/BigBestFitArenaDebugger.cpp +++ b/Libs/Editor/Src/Tools/BigBestFitArenaDebugger.cpp @@ -1,18 +1,19 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Tools/BigBestFitArenaDebugger.h" #include -#include -#include +#include +#include #include + // External #include -namespace rift::Editor +namespace rift::editor { static constexpr Color gFreeColor{210, 56, 41}; // Red static constexpr Color gUsedColor{56, 210, 41}; // Green @@ -51,7 +52,7 @@ namespace rift::Editor } grid.UpdateGridScale(graphSize.x); - graphSize.y = math::Max(graphSize.y, grid.GetHeight()); + graphSize.y = p::Max(graphSize.y, grid.GetHeight()); const ImRect frameBox(window->DC.CursorPos, ImVec2(v2(window->DC.CursorPos) + graphSize)); @@ -64,7 +65,7 @@ namespace rift::Editor { return -1; } - const bool hovered = UI::ItemHoverable(frameBox, id); + const bool hovered = UI::ItemHoverable(frameBox, id, ImGuiItemFlags_None); UI::RenderFrame(frameBox.Min, frameBox.Max, UI::GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding); @@ -85,7 +86,7 @@ namespace rift::Editor const u32 startX = grid.GetX(startOffset); const u32 endX = grid.GetX(endOffset); const u32 startY = grid.GetY(startOffset); - const u32 endY = math::Min(grid.GetY(endOffset), grid.numRows - 1); + const u32 endY = p::Min(grid.GetY(endOffset), grid.numRows - 1); // Draw incomplete rows if (startY != endY) @@ -134,11 +135,11 @@ namespace rift::Editor void MemoryGrid::Draw(const TArray& freeSlots) { String scaleStr = Strings::ParseMemorySize(memoryScale); - u32 scaleMultiplier = u32(math::Log2(memoryScale)); + u32 scaleMultiplier = u32(p::Log2(memoryScale)); static const u32 min = 2, max = 8; UI::SliderScalar( "Scale", ImGuiDataType_U32, (void*)&scaleMultiplier, &min, &max, scaleStr.c_str()); - memoryScale = math::Pow(2, scaleMultiplier); + memoryScale = p::Pow(2, scaleMultiplier); UI::BeginChild("##memoryblock", ImVec2(0.f, 450.f), false); UI::SetNextItemWidth(-FLT_MIN); @@ -196,13 +197,13 @@ namespace rift::Editor const String usedPctLabel = Strings::Format("{:.0f}%% used ({})", usedPct * 100.f, used); const float pctFontSize = (UI::GetFontSize() * usedPctLabel.size()) / 2.f; - UI::SameLine(UI::GetWindowContentRegionWidth() / 2 - pctFontSize / 2, + UI::SameLine(UI::GetContentRegionAvail().x / 2 - pctFontSize / 2, UI::GetStyle().ItemInnerSpacing.x / 2); UI::Text(usedPctLabel); UI::SetItemAllowOverlap(); const float usedFontSize = (UI::GetFontSize() * size.size()) / 2.f; - UI::SameLine(UI::GetWindowContentRegionWidth() - usedFontSize); + UI::SameLine(UI::GetContentRegionAvail().x - usedFontSize); UI::Text(size); UI::PopStyleColor(2); @@ -216,4 +217,4 @@ namespace rift::Editor UI::End(); } } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Tools/GraphPlayground.cpp b/Libs/Editor/Src/Tools/GraphPlayground.cpp index b9e15c3a..f1e57eed 100644 --- a/Libs/Editor/Src/Tools/GraphPlayground.cpp +++ b/Libs/Editor/Src/Tools/GraphPlayground.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Tools/GraphPlayground.h" @@ -10,11 +10,11 @@ #include -namespace rift::Editor +namespace rift::editor { using namespace Nodes; - void GraphPlayground::Draw(AST::Tree& ast, DockSpaceLayout& layout) + void GraphPlayground::Draw(ast::Tree& ast, DockSpaceLayout& layout) { if (!open) { @@ -31,15 +31,15 @@ namespace rift::Editor if (UI::IsWindowAppearing()) { - Graph::SetNodePosition(AST::Id(0), v2::Zero()); + Graph::SetNodePosition(ast::Id(0), v2::Zero()); } static bool boolValue = false; - // Graph::Literals::DrawBoolNode(AST::Id(0), boolValue); + // Graph::Literals::DrawBoolNode(ast::Id(0), boolValue); static String stringValue; - // Graph::Literals::DrawStringNode(AST::Id(1), stringValue); + // Graph::Literals::DrawStringNode(ast::Id(1), stringValue); - // Graph::DrawCallNode({}, AST::Id(958), "ApplyDamage", "DamageSystem"); + // Graph::DrawCallNode({}, ast::Id(958), "ApplyDamage", "DamageSystem"); Nodes::DrawMiniMap(0.2f, MiniMapCorner::TopRight); Nodes::EndNodeEditor(); @@ -47,4 +47,4 @@ namespace rift::Editor } UI::End(); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Tools/MemoryDebugger.cpp b/Libs/Editor/Src/Tools/MemoryDebugger.cpp index 4cb7be8e..da7f28cd 100644 --- a/Libs/Editor/Src/Tools/MemoryDebugger.cpp +++ b/Libs/Editor/Src/Tools/MemoryDebugger.cpp @@ -1,11 +1,11 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Tools/MemoryDebugger.h" #include -#include -#include #include +#include +#include #include #include @@ -14,7 +14,7 @@ #include -namespace rift::Editor +namespace rift::editor { static constexpr Color gFreeColor{210, 56, 41}; // Red static constexpr Color gUsedColor{56, 210, 41}; // Green @@ -32,12 +32,12 @@ namespace rift::Editor if (UI::Begin("Memory", &open)) { String label; - auto* stats = GetHeapStats(); + auto* stats = GetHeapArena().GetStats(); UI::Text(Strings::Format("Used: {}", Strings::ParseMemorySize(stats->used))); if (UI::BeginChild("Allocations")) { - const i32 shown = math::Min(10000, i32(stats->allocations.Size())); + const i32 shown = p::Min(10000, i32(stats->allocations.Size())); for (i32 i = 0; i < shown; ++i) { const auto& allocation = stats->allocations[i]; @@ -46,7 +46,7 @@ namespace rift::Editor if (UI::TreeNodeEx(label.c_str())) { label.clear(); - Strings::FormatTo(label, "Address: {}, Size: {}", allocation.ptr, + Strings::FormatTo(label, "Address: {}, Size: {}", (void*)allocation.ptr, Strings::ParseMemorySize(allocation.size)); UI::Text(label.c_str()); @@ -72,4 +72,4 @@ namespace rift::Editor } UI::End(); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Tools/ReflectionDebugger.cpp b/Libs/Editor/Src/Tools/ReflectionDebugger.cpp index f3f44187..00d0faf8 100644 --- a/Libs/Editor/Src/Tools/ReflectionDebugger.cpp +++ b/Libs/Editor/Src/Tools/ReflectionDebugger.cpp @@ -1,113 +1,34 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Tools/ReflectionDebugger.h" -#include +#include #include #include #include #include -#include +#include #include #include -namespace rift::Editor +namespace rift::editor { - // using namespace p::core::EnumOperators; - - ReflectionDebugger::ReflectionDebugger() {} - void ReflectionDebugger::Draw() + void ReflectionDebugger::Draw(ast::Tree& ast) { if (!open) { return; } - const auto& registry = TypeRegistry::Get(); - - UI::Begin("Reflection", &open); - - if (UI::BeginPopup("Filter")) - { - UI::CheckboxFlags("Native", (u32*)&categoryFilter, u32(TypeCategory::Native)); - UI::CheckboxFlags("Enum", (u32*)&categoryFilter, u32(TypeCategory::Enum)); - UI::CheckboxFlags("Class", (u32*)&categoryFilter, u32(TypeCategory::Class)); - UI::CheckboxFlags("Struct", (u32*)&categoryFilter, u32(TypeCategory::Struct)); - UI::EndPopup(); - } - if (UI::Button("Filter")) - { - UI::OpenPopup("Filter"); - } - - UI::SameLine(); - filter.Draw("##Filter", -100.0f); - - - static ImGuiTableFlags flags = ImGuiTableFlags_Reorderable | ImGuiTableFlags_Resizable - | ImGuiTableFlags_Hideable | ImGuiTableFlags_SizingStretchProp; - ImGui::BeginChild("typesTableChild", ImVec2(0.f, UI::GetContentRegionAvail().y)); - if (UI::BeginTable("typesTable", 4, flags)) - { - UI::TableSetupColumn("Id", ImGuiTableColumnFlags_IndentEnable); - UI::TableSetupColumn("Category"); - UI::TableSetupColumn("Name"); - UI::TableSetupColumn("Parent"); - UI::TableHeadersRow(); - - for (auto it : registry) - { - DrawType(it.second); - } - UI::EndTable(); - } - UI::EndChild(); - - UI::End(); - } - - void ReflectionDebugger::DrawType(Type* type) - { - if (!HasAllFlags(categoryFilter, type->GetCategory())) - { - return; - } - - static String idText; - idText.clear(); - Strings::FormatTo(idText, "{}", type->GetId()); - - StringView name = type->GetName(); - if (!filter.PassFilter(idText.c_str(), idText.c_str() + idText.size()) - && !filter.PassFilter(name.data(), name.data() + name.size())) - { - return; - } - - UI::TableNextRow(); - - UI::TableSetColumnIndex(0); // Id - UI::Text(idText); - - UI::TableSetColumnIndex(1); // Category - static String categories; - categories.clear(); - GetEnumFlagName(type->GetCategory(), categories); - UI::Text(categories); - - UI::TableSetColumnIndex(2); // Name - UI::Text(name); - - if (const auto* dataType = Cast(type)) + auto& dbgContext = ast.GetOrSetStatic(); + dbgContext.ctx = * + if (p::BeginDebug(dbgContext)) { - if (const DataType* parent = dataType->GetParent()) - { - UI::TableSetColumnIndex(3); // Parent - UI::Text(parent->GetName()); - } + p::DrawReflection("Reflection", &open); + p::EndDebug(); } } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/DetailsPanel.cpp b/Libs/Editor/Src/Utils/DetailsPanel.cpp index 484a4c34..006c1543 100644 --- a/Libs/Editor/Src/Utils/DetailsPanel.cpp +++ b/Libs/Editor/Src/Utils/DetailsPanel.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "AST/Id.h" #include "AST/Utils/Namespaces.h" @@ -15,19 +15,23 @@ #include #include -#include #include #include -#include +#include #include -namespace rift::Editor +namespace rift::editor { - void EditFunctionPin(AST::Tree& ast, AST::Id ownerId, AST::Id id) + void EditFunctionPin(ast::Tree& ast, ast::Id ownerId, ast::Id id) { - auto* ns = ast.TryGet(id); - auto* type = ast.TryGet(id); + if (!ast.IsValid(id)) + { + return; + } + + auto* ns = ast.TryGet(id); + auto* type = ast.TryGet(id); if (!ns || !type) { return; @@ -41,7 +45,7 @@ namespace rift::Editor popupName.clear(); Strings::FormatTo(popupName, "##PinContextMenu_{}", id); - AST::Id typeId = AST::FindIdFromNamespace(ast, type->type); + ast::Id typeId = ast::FindIdFromNamespace(ast, type->type); UI::TableNextRow(); const Color color = GetTypeColor(ast, typeId); @@ -67,11 +71,11 @@ namespace rift::Editor labelId.clear(); Strings::FormatTo(labelId, "##Type_{}", id); UI::SetNextItemWidth(-FLT_MIN); - if (Editor::TypeCombo(ast, labelId, typeId)) + if (editor::TypeCombo(ast, labelId, typeId)) { ScopedChange(ast, id); - ast.GetOrAdd(id).id = typeId; - type->type = AST::GetNamespace(ast, typeId); + ast.GetOrAdd(id).id = typeId; + type->type = ast::GetNamespace(ast, typeId); } UI::PopStyleVar(); if (UI::IsItemHovered()) @@ -81,7 +85,7 @@ namespace rift::Editor if (hovered) { - if (UI::IsKeyReleased(GLFW_KEY_DELETE)) + if (UI::IsKeyReleased(ImGuiKey_Delete)) { removePin = true; } @@ -100,14 +104,14 @@ namespace rift::Editor } if (removePin) { - AST::RemoveExprInputPin(ast, AST::GetExprInputFromPin(ast, id)); - AST::RemoveExprOutputPin(ast, AST::GetExprOutputFromPin(ast, id)); + ast::RemoveExprInputPin(ast, ast::GetExprInputFromPin(ast, id)); + ast::RemoveExprOutputPin(ast, ast::GetExprOutputFromPin(ast, id)); } } - void DrawFunction(AST::Tree& ast, AST::Id typeId, AST::Id id) + void DrawFunction(ast::Tree& ast, ast::Id typeId, ast::Id id) { - auto* ns = ast.TryGet(id); + auto* ns = ast.TryGet(id); if (!ns) { return; @@ -115,9 +119,10 @@ namespace rift::Editor String functionName{ns->name.AsString()}; UI::SetNextItemWidth(UI::GetContentRegionAvail().x); - if (UI::InputText("##name", functionName, ImGuiInputTextFlags_AutoSelectAll)) + if (UI::InputTextWithHint( + "##name", "name...", functionName, ImGuiInputTextFlags_AutoSelectAll)) { - Id sameNameFuncId = AST::FindChildByName(ast, typeId, Tag{functionName}); + Id sameNameFuncId = ast::FindChildByName(ast, typeId, Tag{functionName}); if (!IsNone(sameNameFuncId) && id != sameNameFuncId) { UI::PushTextColor(LinearColor::Red()); @@ -132,62 +137,62 @@ namespace rift::Editor } UI::Spacing(); - UI::Text("Inputs"); - if (UI::BeginTable("##fields", 2, ImGuiTableFlags_SizingFixedFit)) + bool addInput = false; + if (UI::CollapsingHeaderWithButton( + "Inputs", ImGuiTreeNodeFlags_DefaultOpen, addInput, ICON_FA_PLUS)) { - UI::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.9f); - UI::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 1.f); - if (const auto* exprOutputs = ast.TryGet(id)) + UI::Indent(); + if (UI::BeginTable("##fields", 2, ImGuiTableFlags_SizingFixedFit)) { - for (AST::Id pinId : exprOutputs->pinIds) + UI::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.9f); + UI::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 1.f); + if (const auto* exprOutputs = ast.TryGet(id)) { - EditFunctionPin(ast, id, pinId); + for (ast::Id pinId : exprOutputs->pinIds) + { + EditFunctionPin(ast, id, pinId); + } } + UI::EndTable(); } - UI::EndTable(); + UI::Unindent(); } - UI::PushStyleCompact(); - UI::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, {0.5f, 0.5f}); - UI::SetNextItemWidth(UI::GetContentRegionAvailWidth()); - if (UI::Selectable(ICON_FA_PLUS "##AddInput")) + if (addInput) { ScopedChange(ast, id); - AST::AddFunctionInput(ast, id); + ast::AddFunctionInput(ast, id); } - UI::HelpTooltip("Adds a new input parameter to a function"); - UI::PopStyleVar(); - UI::PopStyleCompact(); UI::Spacing(); - UI::Text("Outputs"); - if (UI::BeginTable("##fields", 2, ImGuiTableFlags_SizingFixedFit)) + bool addOutput = false; + if (UI::CollapsingHeaderWithButton( + "Outputs", ImGuiTreeNodeFlags_DefaultOpen, addOutput, ICON_FA_PLUS)) { - UI::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.9f); - UI::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 1.f); - if (const auto* exprInputs = ast.TryGet(id)) + UI::Indent(); + if (UI::BeginTable("##fields", 2, ImGuiTableFlags_SizingFixedFit)) { - for (AST::Id pinId : exprInputs->pinIds) + UI::TableSetupColumn("Name", ImGuiTableColumnFlags_WidthStretch, 0.9f); + UI::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthStretch, 1.f); + if (const auto* exprInputs = ast.TryGet(id)) { - EditFunctionPin(ast, id, pinId); + for (ast::Id pinId : exprInputs->pinIds) + { + EditFunctionPin(ast, id, pinId); + } } + UI::EndTable(); } - UI::EndTable(); + UI::Unindent(); } - UI::PushStyleCompact(); - UI::PushStyleVar(ImGuiStyleVar_SelectableTextAlign, ImVec2(0.5f, 0.5f)); - UI::SetNextItemWidth(UI::GetContentRegionAvailWidth()); - if (UI::Selectable(ICON_FA_PLUS "##AddOutput")) + if (addOutput) { ScopedChange(ast, id); - AST::AddFunctionOutput(ast, id); + ast::AddFunctionOutput(ast, id); } - UI::HelpTooltip("Adds a new output parameter to a function"); - UI::PopStyleVar(); - UI::PopStyleCompact(); UI::Spacing(); } - void DrawDetailsPanel(AST::Tree& ast, AST::Id typeId) + void DrawDetailsPanel(ast::Tree& ast, ast::Id typeId) { auto& editor = ast.Get(typeId); @@ -205,11 +210,11 @@ namespace rift::Editor return; } - if (ast.Has(editor.selectedPropertyId)) + if (ast.Has(editor.selectedPropertyId)) { DrawFunction(ast, typeId, editor.selectedPropertyId); } } UI::End(); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/EditorStyle.cpp b/Libs/Editor/Src/Utils/EditorStyle.cpp index 76a158b0..271fbe1c 100644 --- a/Libs/Editor/Src/Utils/EditorStyle.cpp +++ b/Libs/Editor/Src/Utils/EditorStyle.cpp @@ -1,17 +1,16 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/EditorStyle.h" -#include "AST/Components/CDeclClass.h" -#include "AST/Components/CDeclStruct.h" +#include "AST/Components/Declarations.h" #include #include -namespace rift::Editor +namespace rift::editor { - const Color GetTypeColor(const AST::Tree& ast, AST::Id id) + const Color GetTypeColor(const ast::Tree& ast, ast::Id id) { if (!ast.IsValid(id)) { @@ -44,13 +43,13 @@ namespace rift::Editor { return GetTypeColor(); } - else if (ast.Has(id)) + else if (ast.Has(id)) { - return GetTypeColor(); + return GetTypeColor(); } - else if (ast.Has(id)) + else if (ast.Has(id)) { - return GetTypeColor(); + return GetTypeColor(); // Pass any struct to get struct color } return GetTypeColor(); } @@ -59,7 +58,7 @@ namespace rift::Editor void PushNodeTitleColor(Color color) { Nodes::PushStyleColor(Nodes::ColorVar_TitleBar, color); - Nodes::PushStyleColor(Nodes::ColorVar_TitleBarHovered, UI::Hovered(color)); + Nodes::PushStyleColor(Nodes::ColorVar_TitleBarHovered, UI::ToHovered(color)); Nodes::PushStyleColor(Nodes::ColorVar_TitleBarSelected, color); } @@ -71,7 +70,7 @@ namespace rift::Editor void PushNodeBackgroundColor(Color color) { Nodes::PushStyleColor(Nodes::ColorVar_NodeBackground, color); - Nodes::PushStyleColor(Nodes::ColorVar_NodeBackgroundHovered, UI::Hovered(color)); + Nodes::PushStyleColor(Nodes::ColorVar_NodeBackgroundHovered, UI::ToHovered(color)); Nodes::PushStyleColor(Nodes::ColorVar_NodeBackgroundSelected, color); } @@ -79,4 +78,4 @@ namespace rift::Editor { Nodes::PopStyleColor(3); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/ElementsPanel.cpp b/Libs/Editor/Src/Utils/ElementsPanel.cpp index ffa6b9da..657d9535 100644 --- a/Libs/Editor/Src/Utils/ElementsPanel.cpp +++ b/Libs/Editor/Src/Utils/ElementsPanel.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/ElementsPanel.h" @@ -15,21 +15,18 @@ #include #include -#include #include #include -#include +#include #include -namespace rift::Editor +namespace rift::editor { - // using namespace EnumOperators; - - void DrawVariable(TVariableAccessRef access, CTypeEditor& editor, AST::Id variableId) + void DrawVariable(TVariableAccessRef access, CTypeEditor& editor, ast::Id variableId) { - auto* ns = access.TryGet(variableId); - auto* variableDecl = access.TryGet(variableId); + auto* ns = access.TryGet(variableId); + auto* variableDecl = access.TryGet(variableId); if (!ns || !variableDecl) { return; @@ -43,7 +40,7 @@ namespace rift::Editor ImGui::PushID(ns); const Color color = - GetTypeColor(static_cast(access.GetContext()), variableDecl->typeId); + GetTypeColor(static_cast(access.GetContext()), variableDecl->typeId); static constexpr float frameHeight = 20.f; UI::TableNextColumn(); @@ -61,14 +58,14 @@ namespace rift::Editor { editor.selectedPropertyId = variableId; - if (UI::IsKeyReleased(GLFW_KEY_DELETE)) + if (UI::IsKeyReleased(ImGuiKey_Delete)) { editor.pendingDeletePropertyId = variableId; } } else if (editor.selectedPropertyId == variableId) // If not selected but WAS selected { - editor.selectedPropertyId = AST::NoId; + editor.selectedPropertyId = ast::NoId; } Color bgColor = color; @@ -78,7 +75,7 @@ namespace rift::Editor } else if (UI::IsItemHovered()) { - bgColor = UI::Hovered(color); + bgColor = UI::ToHovered(color); } UI::RenderFrame(bb.Min, bb.Max, bgColor.DWColor(), false, 2.f); @@ -110,7 +107,7 @@ namespace rift::Editor { UI::PushStyleVar(ImGuiStyleVar_FrameRounding, 2.f); UI::SetNextItemWidth(-FLT_MIN); - Editor::TypeCombo(access, "##type", variableDecl->typeId); + editor::TypeCombo(access, "##type", variableDecl->typeId); UI::PopStyleVar(); } @@ -127,9 +124,9 @@ namespace rift::Editor UI::PopID(); } - void DrawFunction(AST::Tree& ast, CTypeEditor& editor, AST::Id typeId, AST::Id id) + void DrawFunction(ast::Tree& ast, CTypeEditor& editor, ast::Id typeId, ast::Id id) { - auto* ns = ast.TryGet(id); + auto* ns = ast.TryGet(id); if (!ns) { return; @@ -141,7 +138,7 @@ namespace rift::Editor } UI::PushHeaderColor(callColor); - UI::PushStyleVar(ImGuiStyleVar_FrameRounding, 3.f); + UI::PushStyleVar(ImGuiStyleVar_FrameRounding, 1.f); static String headerId; headerId.clear(); Strings::FormatTo(headerId, "{}###{}", name, id); @@ -162,26 +159,28 @@ namespace rift::Editor if (ImGui::BeginPopupContextItem()) { - Graph::DrawNodesContextMenu(ast, typeId, id); if (UI::MenuItem("Show in Graph")) { Nodes::MoveToNode(id, v2{150.f, 150.f}); } + Graph::DrawNodesContextMenu(ast, typeId, id); ImGui::EndPopup(); } } - void DrawVariables(TVariableAccessRef access, AST::TransactionAccess transAccess, - CTypeEditor& editor, AST::Id typeId) + void DrawVariables(TVariableAccessRef access, ast::TransactionAccess transAccess, + CTypeEditor& editor, ast::Id typeId) { - if (UI::CollapsingHeader("Variables", ImGuiTreeNodeFlags_DefaultOpen)) + bool add = false; + if (UI::CollapsingHeaderWithButton( + "Variables", ImGuiTreeNodeFlags_DefaultOpen, add, ICON_FA_PLUS)) { - UI::Indent(10.f); - TArray variableIds; - p::GetChildren(access, typeId, variableIds); - ExcludeIdsWithout(access, variableIds); + UI::Indent(); + TArray variableIds; + p::GetIdChildren(access, typeId, variableIds); + ExcludeIdsWithout(access, variableIds); - UI::PushStyleVar(ImGuiStyleVar_CellPadding, {1.f, 3.f}); + UI::PushStyleVar(ImGuiStyleVar_CellPadding, p::v2{1.f, 3.f}); bool showTable = UI::BeginTable("##variableTable", 3, ImGuiTableFlags_SizingFixedFit); UI::PopStyleVar(); if (showTable) @@ -189,9 +188,9 @@ namespace rift::Editor ImGui::TableSetupColumn(nullptr, ImGuiTableColumnFlags_WidthStretch, 0.45f); ImGui::TableSetupColumn(nullptr, ImGuiTableColumnFlags_WidthStretch, 0.25f); ImGui::TableSetupColumn(nullptr, ImGuiTableColumnFlags_WidthStretch, 0.30f); - for (AST::Id child : variableIds) + for (ast::Id child : variableIds) { - if (access.Has(child)) + if (access.Has(child)) { UI::TableNextRow(); DrawVariable(access, editor, child); @@ -199,50 +198,47 @@ namespace rift::Editor } UI::EndTable(); } - - UI::PushStyleCompact(); - if (UI::Button(ICON_FA_PLUS "##Variable", ImVec2(-FLT_MIN, 0.0f))) - { - ScopedChange(transAccess, typeId); - AST::AddVariable( - {static_cast(access.GetContext()), typeId}, "NewVariable"); - } - UI::PopStyleCompact(); - UI::Unindent(10.f); + UI::Unindent(); UI::Dummy(ImVec2(0.0f, 10.0f)); } + + if (add) + { + ScopedChange(transAccess, typeId); + ast::AddVariable({static_cast(access.GetContext()), typeId}, "NewVariable"); + } } - void DrawFunctions(AST::Tree& ast, CTypeEditor& editor, AST::Id typeId) + void DrawFunctions(ast::Tree& ast, CTypeEditor& editor, ast::Id typeId) { - const ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_DefaultOpen - | ImGuiTreeNodeFlags_AllowItemOverlap - | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; - if (UI::CollapsingHeader("Functions", flags)) + const ImGuiTreeNodeFlags flags = + ImGuiTreeNodeFlags_DefaultOpen | ImGuiTreeNodeFlags_AllowItemOverlap; + + bool add = false; + if (UI::CollapsingHeaderWithButton("Functions", flags, add, ICON_FA_PLUS)) { - UI::Indent(10.f); + UI::Indent(); - TArray functionIds; - p::GetChildren(ast, typeId, functionIds); - ExcludeIdsWithout(ast, functionIds); - for (AST::Id functionId : functionIds) + TArray functionIds; + p::GetIdChildren(ast, typeId, functionIds); + ExcludeIdsWithout(ast, functionIds); + for (ast::Id functionId : functionIds) { DrawFunction(ast, editor, typeId, functionId); } - UI::PushStyleCompact(); - if (UI::Button(ICON_FA_PLUS "##Function", ImVec2(-FLT_MIN, 0.0f))) - { - ScopedChange(ast, typeId); - AST::AddFunction({ast, typeId}, "NewFunction"); - } - UI::PopStyleCompact(); - UI::Unindent(10.f); + UI::Unindent(); UI::Dummy(ImVec2(0.0f, 10.0f)); } + + if (add) + { + ScopedChange(ast, typeId); + ast::AddFunction({ast, typeId}, "NewFunction"); + } } - void DrawElementsPanel(AST::Tree& ast, AST::Id typeId) + void DrawElementsPanel(ast::Tree& ast, ast::Id typeId) { auto& editor = ast.Get(typeId); @@ -254,15 +250,15 @@ namespace rift::Editor const String windowName = Strings::Format("Elements##{}", typeId); if (UI::Begin(windowName.c_str(), &editor.showElements)) { - UI::SetNextItemWidth(UI::GetContentRegionAvailWidth()); - editor.elementsFilter.Draw("##filter"); + UI::SetNextItemWidth(UI::GetContentRegionAvail().x); + UI::DrawFilterWithHint(editor.elementsFilter, "##filter", "Search..."); - if (AST::HasVariables(ast, typeId)) + if (ast::HasVariables(ast, typeId)) { DrawVariables(ast, ast, editor, typeId); } - if (AST::HasFunctions(ast, typeId)) + if (ast::HasFunctions(ast, typeId)) { DrawFunctions(ast, editor, typeId); } @@ -272,17 +268,17 @@ namespace rift::Editor if (!IsNone(editor.pendingDeletePropertyId)) { ScopedChange(ast, editor.pendingDeletePropertyId); - bool removedPin = AST::RemoveExprInputPin( - ast, AST::GetExprInputFromPin(ast, editor.pendingDeletePropertyId)); - removedPin |= AST::RemoveExprOutputPin( - ast, AST::GetExprOutputFromPin(ast, editor.pendingDeletePropertyId)); + bool removedPin = ast::RemoveExprInputPin( + ast, ast::GetExprInputFromPin(ast, editor.pendingDeletePropertyId)); + removedPin |= ast::RemoveExprOutputPin( + ast, ast::GetExprOutputFromPin(ast, editor.pendingDeletePropertyId)); // If pin has not been marked for removal, destroy the entity if (!removedPin) { - p::Remove(ast, editor.pendingDeletePropertyId, true); - editor.pendingDeletePropertyId = AST::NoId; + p::RemoveId(ast, editor.pendingDeletePropertyId, true); + editor.pendingDeletePropertyId = ast::NoId; } } } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/FunctionGraph.cpp b/Libs/Editor/Src/Utils/FunctionGraph.cpp index 547dc0e8..46ea0b74 100644 --- a/Libs/Editor/Src/Utils/FunctionGraph.cpp +++ b/Libs/Editor/Src/Utils/FunctionGraph.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/FunctionGraph.h" @@ -9,39 +9,24 @@ #include "Utils/FunctionGraphContextMenu.h" #include "Utils/TypeUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include +#include +#include +#include +#include #include #include #include #include #include -#include -#include +#include #include #include #include #include -namespace rift::Editor::Graph +namespace rift::editor::Graph { static CNodePosition* currentNodeTransform = nullptr; @@ -77,14 +62,14 @@ namespace rift::Editor::Graph return Nodes::ScreenToGridPosition(screenPosition) * GetInvGridSize(); } - void BeginExprInput(TAccessRef access, AST::Id id, const bool& invalid) + void BeginExprInput(p::TAccessRef access, ast::Id id, const bool& invalid) { bool isPointer = false; - AST::Id typeId = AST::NoId; - if (auto* type = access.TryGet(id)) + ast::Id typeId = ast::NoId; + if (auto* type = access.TryGet(id)) { typeId = type->id; - isPointer = type->mode != AST::TypeMode::Value; + isPointer = type->mode != ast::TypeMode::Value; } Color pinColor = GetTypeColor(); @@ -95,24 +80,24 @@ namespace rift::Editor::Graph } else { - pinColor = GetTypeColor(static_cast(access.GetContext()), typeId); + pinColor = GetTypeColor(static_cast(access.GetContext()), typeId); } Nodes::PushStyleColor(Nodes::ColorVar_Pin, pinColor); - Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::Hovered(pinColor)); + Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::ToHovered(pinColor)); Nodes::BeginInput( i32(id), isPointer ? Nodes::PinShape_DiamondFilled : Nodes::PinShape_CircleFilled); } - void BeginExprOutput(TAccessRef access, AST::Id id, const bool& invalid) + void BeginExprOutput(p::TAccessRef access, ast::Id id, const bool& invalid) { bool isPointer = false; - AST::Id typeId = AST::NoId; - if (auto* type = access.TryGet(id)) + ast::Id typeId = ast::NoId; + if (auto* type = access.TryGet(id)) { typeId = type->id; - isPointer = type->mode != AST::TypeMode::Value; + isPointer = type->mode != ast::TypeMode::Value; } Color pinColor = GetTypeColor(); @@ -123,11 +108,11 @@ namespace rift::Editor::Graph } else { - pinColor = GetTypeColor(static_cast(access.GetContext()), typeId); + pinColor = GetTypeColor(static_cast(access.GetContext()), typeId); } Nodes::PushStyleColor(Nodes::ColorVar_Pin, pinColor); - Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::Hovered(pinColor)); + Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::ToHovered(pinColor)); Nodes::BeginOutput( i32(id), isPointer ? Nodes::PinShape_DiamondFilled : Nodes::PinShape_CircleFilled); @@ -153,39 +138,39 @@ namespace rift::Editor::Graph } } - void DrawInputs(TAccessRef access, - const AST::CExprInputs& inputs) + void DrawInputs(p::TAccessRef access, + const ast::CExprInputs& inputs) { - for (AST::Id pinId : inputs.pinIds) + for (ast::Id pinId : inputs.pinIds) { if (access.IsValid(pinId)) { - const bool invalid = access.Has(pinId); + const bool invalid = access.Has(pinId); BeginExprInput(access, pinId, invalid); - auto* ns = access.TryGet(pinId); + auto* ns = access.TryGet(pinId); UI::Text(ns ? ns->name.AsString() : "none"); EndExprInput(invalid); } } } - void DrawOutputs(TAccessRef access, - const AST::CExprOutputs& outputs) + void DrawOutputs(p::TAccessRef access, + const ast::CExprOutputs& outputs) { - for (AST::Id pinId : outputs.pinIds) + for (ast::Id pinId : outputs.pinIds) { if (access.IsValid(pinId)) { - const bool invalid = access.Has(pinId); + const bool invalid = access.Has(pinId); BeginExprOutput(access, pinId, invalid); - auto* ns = access.TryGet(pinId); + auto* ns = access.TryGet(pinId); UI::Text(ns ? ns->name.AsString() : "none"); EndExprOutput(invalid); } } } - void BeginNode(TAccessRef> access, AST::Id id) + void BeginNode(p::TAccessRef> access, ast::Id id) { currentNodeTransform = &access.GetOrAdd(id); auto* context = Nodes::GetCurrentContext(); @@ -200,7 +185,7 @@ namespace rift::Editor::Graph Nodes::BeginNode(id); } - void EndNode(const AST::TransactionAccess& access) + void EndNode(const ast::TransactionAccess& access) { // Selection outline const auto* context = Nodes::GetCurrentContext(); @@ -214,7 +199,7 @@ namespace rift::Editor::Graph if (currentNodeTransform && context->leftMouseReleased) { - const AST::Id id = context->currentNodeId; + const ast::Id id = context->currentNodeId; v2 newPosition = GetNodePosition(id); if (!newPosition.Equals(currentNodeTransform->position, 0.1f)) { @@ -229,7 +214,7 @@ namespace rift::Editor::Graph { static constexpr Color color = executionColor; Nodes::PushStyleColor(Nodes::ColorVar_Pin, color); - Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::Hovered(color)); + Nodes::PushStyleColor(Nodes::ColorVar_PinHovered, UI::ToHovered(color)); } void PopExecutionPinStyle() @@ -237,7 +222,7 @@ namespace rift::Editor::Graph Nodes::PopStyleColor(2); } - void DrawLiteralBool(AST::Tree& ast, AST::Id id, bool& value) + void DrawLiteralBool(ast::Tree& ast, ast::Id id, bool& value) { static constexpr Color color = GetTypeColor(); @@ -255,7 +240,7 @@ namespace rift::Editor::Graph PopNodeBackgroundColor(); } - void DrawLiteralIntegral(AST::Tree& ast, AST::Id id, AST::CLiteralIntegral& value) + void DrawLiteralIntegral(ast::Tree& ast, ast::Id id, ast::CLiteralIntegral& value) { const bool isSigned = value.IsSigned(); const Color color = isSigned ? GetTypeColor() : GetTypeColor(); @@ -269,20 +254,20 @@ namespace rift::Editor::Graph ImGuiDataType dataType = ImGuiDataType_COUNT; switch (value.type) { - case AST::IntegralType::S8: dataType = ImGuiDataType_S8; break; - case AST::IntegralType::S16: dataType = ImGuiDataType_S16; break; - case AST::IntegralType::S32: dataType = ImGuiDataType_S32; break; - case AST::IntegralType::S64: dataType = ImGuiDataType_S64; break; - case AST::IntegralType::U8: dataType = ImGuiDataType_U8; break; - case AST::IntegralType::U16: dataType = ImGuiDataType_U16; break; - case AST::IntegralType::U32: dataType = ImGuiDataType_U32; break; - case AST::IntegralType::U64: dataType = ImGuiDataType_U64; break; + case ast::IntegralType::S8: dataType = ImGuiDataType_S8; break; + case ast::IntegralType::S16: dataType = ImGuiDataType_S16; break; + case ast::IntegralType::S32: dataType = ImGuiDataType_S32; break; + case ast::IntegralType::S64: dataType = ImGuiDataType_S64; break; + case ast::IntegralType::U8: dataType = ImGuiDataType_U8; break; + case ast::IntegralType::U16: dataType = ImGuiDataType_U16; break; + case ast::IntegralType::U32: dataType = ImGuiDataType_U32; break; + case ast::IntegralType::U64: dataType = ImGuiDataType_U64; break; } const char* format = value.IsSigned() ? "%i" : "%iu"; char buf[64]; UI::DataTypeFormatString(buf, IM_ARRAYSIZE(buf), dataType, &value.value, format); - UI::SetNextItemWidth(5.f + math::Max(UI::CalcTextSize(buf).x, 20.f)); + UI::SetNextItemWidth(5.f + p::Max(UI::CalcTextSize(buf).x, 20.f)); UI::InputScalar("##value", dataType, &value.value, nullptr, nullptr, format); PopInnerNodeStyle(); @@ -292,9 +277,9 @@ namespace rift::Editor::Graph PopNodeBackgroundColor(); } - void DrawLiteralFloating(AST::Tree& ast, AST::Id id, AST::CLiteralFloating& value) + void DrawLiteralFloating(ast::Tree& ast, ast::Id id, ast::CLiteralFloating& value) { - const bool isDouble = value.type == AST::FloatingType::F64; + const bool isDouble = value.type == ast::FloatingType::F64; const Color color = isDouble ? GetTypeColor() : GetTypeColor(); PushNodeBackgroundColor(color); BeginNode(ast, id); @@ -305,7 +290,7 @@ namespace rift::Editor::Graph const ImGuiDataType dataType = isDouble ? ImGuiDataType_Double : ImGuiDataType_Float; char buf[64]; UI::DataTypeFormatString(buf, IM_ARRAYSIZE(buf), dataType, &value.value, "%.15g"); - UI::SetNextItemWidth(5.f + math::Max(UI::CalcTextSize(buf).x, 20.f)); + UI::SetNextItemWidth(5.f + p::Max(UI::CalcTextSize(buf).x, 20.f)); UI::InputScalar("##value", dataType, &value.value, nullptr, nullptr, "%.15g"); PopInnerNodeStyle(); @@ -315,7 +300,7 @@ namespace rift::Editor::Graph PopNodeBackgroundColor(); } - void DrawLiteralString(AST::Tree& ast, AST::Id id, String& value) + void DrawLiteralString(ast::Tree& ast, ast::Id id, String& value) { static constexpr Color color = GetTypeColor(); PushNodeBackgroundColor(color); @@ -327,7 +312,7 @@ namespace rift::Editor::Graph ImGuiStyle& style = ImGui::GetStyle(); const ImVec2 textSize = ImGui::CalcTextSize(value.data(), value.data() + value.size()); const v2 minSize{settings.GetGridSize() * 4.f, settings.GetGridSize()}; - const v2 size{math::Max(minSize.x, textSize.x), math::Max(minSize.y, textSize.y)}; + const v2 size{p::Max(minSize.x, textSize.x), p::Max(minSize.y, textSize.y)}; UI::InputTextMultiline("##value", value, v2(size - settings.GetContentPadding())); PopInnerNodeStyle(); EndExprOutput(false); @@ -337,15 +322,15 @@ namespace rift::Editor::Graph PopNodeBackgroundColor(); } - using FunctionDeclsAccess = p::TAccessRef, p::TWrite, AST::CChild, - AST::CFileRef, p::TWrite>; - void DrawFunctionDecls(FunctionDeclsAccess access, const TArray& functionDecls) + using FunctionDeclsAccess = p::TAccessRef, p::TWrite, ast::CChild, + ast::CFileRef, p::TWrite>; + void DrawFunctionDecls(FunctionDeclsAccess access, const TArray& functionDecls) { - for (AST::Id functionId : functionDecls) + for (ast::Id functionId : functionDecls) { Tag name; - if (auto* ns = access.TryGet(functionId)) + if (auto* ns = access.TryGet(functionId)) { name = ns->name; } @@ -367,7 +352,7 @@ namespace rift::Editor::Graph } Nodes::EndNodeTitleBar(); - if (auto* outputs = access.TryGet(functionId)) + if (auto* outputs = access.TryGet(functionId)) { DrawOutputs(access, *outputs); } @@ -378,10 +363,10 @@ namespace rift::Editor::Graph } } - void DrawReturnNode(TAccessRef, TWrite, - TWrite, AST::CChild, AST::CFileRef> + void DrawReturnNode(p::TAccessRef, TWrite, + TWrite, ast::CChild, ast::CFileRef> access, - AST::Id id) + ast::Id id) { PushNodeBackgroundColor(rift::UI::GetNeutralColor(0)); PushNodeTitleColor(returnColor); @@ -407,14 +392,14 @@ namespace rift::Editor::Graph PopNodeBackgroundColor(); } - using CallsAccess = TAccessRef, TWrite, AST::CChild, - AST::CFileRef, AST::CExprCall, AST::CExprInputs, AST::CExprOutputs, AST::CNamespace, - AST::CExprTypeId, AST::CInvalid, TWrite, AST::CDeclType>; - void DrawCalls(CallsAccess access, AST::Id typeId, const TArray& childrenIds) + using CallsAccess = TAccessRef, TWrite, ast::CChild, + ast::CFileRef, ast::CExprCall, ast::CExprInputs, ast::CExprOutputs, ast::CNamespace, + ast::CExprTypeId, ast::CInvalid, TWrite, ast::CDeclType>; + void DrawCalls(CallsAccess access, ast::Id typeId, const TArray& childrenIds) { - for (AST::Id id : childrenIds) + for (ast::Id id : childrenIds) { - if (auto* call = access.TryGet(id)) + if (auto* call = access.TryGet(id)) { StringView functionName = call->function.Last().AsString(); @@ -446,7 +431,7 @@ namespace rift::Editor::Graph // Inputs UI::BeginGroup(); - if (const auto* inputs = access.TryGet(id)) + if (const auto* inputs = access.TryGet(id)) { DrawInputs(access, *inputs); } @@ -455,7 +440,7 @@ namespace rift::Editor::Graph // Outputs UI::BeginGroup(); - if (const auto* outputs = access.TryGet(id)) + if (const auto* outputs = access.TryGet(id)) { DrawOutputs(access, *outputs); } @@ -509,9 +494,9 @@ namespace rift::Editor::Graph const float padding = (settings.GetSpaceHeight(1) - GImGui->FontSize) * 0.5f - settings.verticalPadding; - ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, {style.FramePadding.x, padding}); + ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, p::v2{style.FramePadding.x, padding}); ImGui::PushStyleVar( - ImGuiStyleVar_ItemSpacing, {style.ItemSpacing.x, settings.verticalPadding}); + ImGuiStyleVar_ItemSpacing, p::v2{style.ItemSpacing.x, settings.verticalPadding}); } void PopInnerNodeStyle() @@ -519,49 +504,49 @@ namespace rift::Editor::Graph ImGui::PopStyleVar(2); } - void DrawReturns(TAccessRef, TWrite, - TWrite, AST::CChild, AST::CFileRef, AST::CStmtReturn> + void DrawReturns(p::TAccessRef, TWrite, + TWrite, ast::CChild, ast::CFileRef, ast::CStmtReturn> access, - const TArray& children) + const TArray& children) { - for (AST::Id id : FindIdsWith(access, children)) + for (ast::Id id : FindIdsWith(access, children)) { DrawReturnNode(access, id); } } - void DrawLiterals(AST::Tree& ast, const TArray& children) + void DrawLiterals(ast::Tree& ast, const TArray& children) { - for (AST::Id id : FindIdsWith(ast, children)) + for (ast::Id id : FindIdsWith(ast, children)) { - DrawLiteralBool(ast, id, ast.Get(id).value); + DrawLiteralBool(ast, id, ast.Get(id).value); } - for (AST::Id id : FindIdsWith(ast, children)) + for (ast::Id id : FindIdsWith(ast, children)) { - DrawLiteralIntegral(ast, id, ast.Get(id)); + DrawLiteralIntegral(ast, id, ast.Get(id)); } - for (AST::Id id : FindIdsWith(ast, children)) + for (ast::Id id : FindIdsWith(ast, children)) { - DrawLiteralFloating(ast, id, ast.Get(id)); + DrawLiteralFloating(ast, id, ast.Get(id)); } - for (AST::Id id : FindIdsWith(ast, children)) + for (ast::Id id : FindIdsWith(ast, children)) { - DrawLiteralString(ast, id, ast.Get(id).value); + DrawLiteralString(ast, id, ast.Get(id).value); } } - void DrawVariableRefs(AST::Tree& ast, const TArray& children) + void DrawVariableRefs(ast::Tree& ast, const TArray& children) { String name; - for (AST::Id id : FindIdsWith(ast, children)) + for (ast::Id id : FindIdsWith(ast, children)) { - AST::Id variableId = ast.Get(id).declarationId; + ast::Id variableId = ast.Get(id).declarationId; - const AST::CExprTypeId* exprType = ast.TryGet(id); - AST::Id typeId = exprType ? exprType->id : AST::NoId; + const ast::CExprTypeId* exprType = ast.TryGet(id); + ast::Id typeId = exprType ? exprType->id : ast::NoId; const Color color = GetTypeColor(ast, typeId); PushNodeBackgroundColor(color); @@ -571,9 +556,9 @@ namespace rift::Editor::Graph BeginExprOutput(ast, id, false); PushInnerNodeStyle(); StringView name = "Invalid"; - if (ast.IsValid(variableId) && ast.Has(variableId)) + if (ast.IsValid(variableId) && ast.Has(variableId)) { - name = ast.Get(variableId).name.AsString(); + name = ast.Get(variableId).name.AsString(); } UI::Text(name); PopInnerNodeStyle(); @@ -585,16 +570,16 @@ namespace rift::Editor::Graph } } - void DrawIfs(TAccessRef, TWrite, TWrite, - AST::CChild, AST::CFileRef, AST::CStmtIf, AST::CStmtOutputs, AST::CExprInputs, - AST::CParent, AST::CExprTypeId> + void DrawIfs(p::TAccessRef, TWrite, + TWrite, ast::CChild, ast::CFileRef, ast::CStmtIf, + ast::CStmtOutputs, ast::CExprInputs, ast::CParent, ast::CExprTypeId> access, - const TArray& children) + const TArray& children) { PushNodeBackgroundColor(UI::GetNeutralColor(0)); PushNodeTitleColor(flowColor); - for (AST::Id id : - FindIdsWith(access, children)) + for (ast::Id id : + FindIdsWith(access, children)) { BeginNode(access, id); { @@ -608,8 +593,8 @@ namespace rift::Editor::Graph Nodes::EndInput(); PopExecutionPinStyle(); - auto& inputs = access.Get(id); - if (!Ensure(inputs.pinIds.Size() == 1)) + auto& inputs = access.Get(id); + if (!P_Ensure(inputs.pinIds.Size() == 1)) { continue; } @@ -627,8 +612,8 @@ namespace rift::Editor::Graph UI::SameLine(); UI::BeginGroup(); { - auto& outputs = access.Get(id); - if (!Ensure(outputs.pinIds.Size() == 2)) + auto& outputs = access.Get(id); + if (!P_Ensure(outputs.pinIds.Size() == 2)) { continue; } @@ -652,12 +637,12 @@ namespace rift::Editor::Graph } void DrawUnaryOperators( - TAccessRef, TWrite, TWrite, - AST::CChild, AST::CParent, AST::CFileRef, AST::CExprUnaryOperator, AST::CExprTypeId> + TAccessRef, TWrite, TWrite, + ast::CChild, ast::CParent, ast::CFileRef, ast::CExprUnaryOperator, ast::CExprTypeId> access, - const TArray& children) + const TArray& children) { - for (AST::Id id : FindIdsWith(access, children)) + for (ast::Id id : FindIdsWith(access, children)) { static constexpr Color color = UI::GetNeutralColor(0); @@ -670,8 +655,8 @@ namespace rift::Editor::Graph EndExprInput(false); UI::SameLine(); - const auto& op = access.Get(id); - StringView shortName = Editor::GetUnaryOperatorName(op.type); + const auto& op = access.Get(id); + StringView shortName = editor::GetUnaryOperatorName(op.type); UI::Text(shortName); UI::SameLine(); @@ -685,13 +670,13 @@ namespace rift::Editor::Graph } void DrawBinaryOperators( - TAccessRef, TWrite, TWrite, - AST::CChild, AST::CParent, AST::CFileRef, AST::CExprBinaryOperator, AST::CExprTypeId> + TAccessRef, TWrite, TWrite, + ast::CChild, ast::CParent, ast::CFileRef, ast::CExprBinaryOperator, ast::CExprTypeId> access, - const TArray& children) + const TArray& children) { - TArray pinIds; - for (AST::Id id : FindIdsWith(access, children)) + TArray pinIds; + for (ast::Id id : FindIdsWith(access, children)) { static constexpr Color color = UI::GetNeutralColor(0); PushNodeBackgroundColor(color); @@ -699,8 +684,8 @@ namespace rift::Editor::Graph BeginNode(access, id); { pinIds.Clear(false); - p::GetChildren(access, id, pinIds); - if (!Ensure(pinIds.Size() >= 2)) + p::GetIdChildren(access, id, pinIds); + if (!P_Ensure(pinIds.Size() >= 2)) { continue; } @@ -715,8 +700,8 @@ namespace rift::Editor::Graph UI::EndGroup(); UI::SameLine(); - const auto& op = access.Get(id); - StringView shortName = Editor::GetBinaryOperatorName(op.type); + const auto& op = access.Get(id); + StringView shortName = editor::GetBinaryOperatorName(op.type); UI::Text(shortName); UI::SameLine(); @@ -729,17 +714,18 @@ namespace rift::Editor::Graph } } - void DrawStatementLinks(TAccessRef& access, - const TArray& children) + void DrawStatementLinks( + p::TAccessRef& access, + const TArray& children) { Nodes::PushStyleVar(Nodes::StyleVar_LinkThickness, 2.f); Nodes::PushStyleColor(Nodes::ColorVar_Link, executionColor); - Nodes::PushStyleColor(Nodes::ColorVar_LinkHovered, UI::Hovered(executionColor)); + Nodes::PushStyleColor(Nodes::ColorVar_LinkHovered, UI::ToHovered(executionColor)); Nodes::PushStyleColor(Nodes::ColorVar_LinkSelected, selectedColor); - for (AST::Id outputId : FindIdsWith(access, children)) + for (ast::Id outputId : FindIdsWith(access, children)) { - const auto* output = access.TryGet(outputId); + const auto* output = access.TryGet(outputId); if (output && access.IsValid(output->linkInputNode)) { // Input pin ids equal input node ids @@ -748,17 +734,17 @@ namespace rift::Editor::Graph } } - for (AST::Id outputId : FindIdsWith(access, children)) + for (ast::Id outputId : FindIdsWith(access, children)) { - if (const auto* outputs = access.TryGet(outputId)) + if (const auto* outputs = access.TryGet(outputId)) { - if (EnsureMsg(outputs->linkInputNodes.Size() == outputs->pinIds.Size(), + if (P_EnsureMsg(outputs->linkInputNodes.Size() == outputs->pinIds.Size(), "Inputs and pins must match. Graph might be corrupted.")) { for (i32 i = 0; i < outputs->linkInputNodes.Size(); ++i) { - const AST::Id outputPinId = outputs->pinIds[i]; - const AST::Id inputNodeId = outputs->linkInputNodes[i]; + const ast::Id outputPinId = outputs->pinIds[i]; + const ast::Id inputNodeId = outputs->linkInputNodes[i]; if (access.IsValid(outputPinId) && access.IsValid(inputNodeId)) { // Input pin ids equal input node ids @@ -775,16 +761,16 @@ namespace rift::Editor::Graph } void DrawExpressionLinks( - TAccessRef& access, - const TArray& children) + TAccessRef& access, + const TArray& children) { Nodes::PushStyleVar(Nodes::StyleVar_LinkThickness, 1.5f); Nodes::PushStyleColor(Nodes::ColorVar_LinkSelected, selectedColor); - for (AST::Id nodeId : FindIdsWith(access, children)) + for (ast::Id nodeId : FindIdsWith(access, children)) { - const auto& inputs = access.Get(nodeId); - if (!EnsureMsg(inputs.pinIds.Size() == inputs.linkedOutputs.Size(), + const auto& inputs = access.Get(nodeId); + if (!P_EnsureMsg(inputs.pinIds.Size() == inputs.linkedOutputs.Size(), "Inputs are invalid. The graph might be corrupted.")) [[likely]] { continue; @@ -792,29 +778,29 @@ namespace rift::Editor::Graph for (i32 i = 0; i < inputs.linkedOutputs.Size(); ++i) { - AST::Id inputId = inputs.pinIds[i]; - AST::ExprOutput output = inputs.linkedOutputs[i]; + ast::Id inputId = inputs.pinIds[i]; + ast::ExprOutput output = inputs.linkedOutputs[i]; if (!access.IsValid(inputId) || !access.IsValid(output.pinId)) { continue; } Color color = GetTypeColor(); - if (access.Has(inputId) || access.Has(output.pinId)) + if (access.Has(inputId) || access.Has(output.pinId)) { color = invalidColor; } - else if (const auto* type = access.TryGet(output.pinId)) + else if (const auto* type = access.TryGet(output.pinId)) { - color = GetTypeColor(static_cast(access.GetContext()), type->id); + color = GetTypeColor(static_cast(access.GetContext()), type->id); } - else if (const auto* type = access.TryGet(inputId)) + else if (const auto* type = access.TryGet(inputId)) { - color = GetTypeColor(static_cast(access.GetContext()), type->id); + color = GetTypeColor(static_cast(access.GetContext()), type->id); } Nodes::PushStyleColor(Nodes::ColorVar_Link, color); - Nodes::PushStyleColor(Nodes::ColorVar_LinkHovered, UI::Hovered(color)); + Nodes::PushStyleColor(Nodes::ColorVar_LinkHovered, UI::ToHovered(color)); Nodes::Link(i32(inputId), i32(output.pinId), i32(inputId)); @@ -825,7 +811,7 @@ namespace rift::Editor::Graph Nodes::PopStyleVar(); } - void DrawTypeGraph(AST::Tree& ast, AST::Id typeId, CTypeEditor& typeEditor) + void DrawTypeGraph(ast::Tree& ast, ast::Id typeId, CTypeEditor& typeEditor) { if (!typeEditor.showGraph) { @@ -841,7 +827,7 @@ namespace rift::Editor::Graph if (UI::Begin(graphId.c_str(), &typeEditor.showGraph, ImGuiWindowFlags_NoCollapse)) { Nodes::SetEditorContext(&typeEditor.nodesEditor); - Nodes::GetCurrentContext()->canCreateLinks = AST::HasFunctionBodies(ast, typeId); + Nodes::GetCurrentContext()->canCreateLinks = ast::HasFunctionBodies(ast, typeId); Nodes::BeginNodeEditor(); PushNodeStyle(); @@ -851,11 +837,11 @@ namespace rift::Editor::Graph wantsToOpenContextMenu = true; } - TArray children; - p::GetChildren(ast, typeId, children); + TArray children; + p::GetIdChildren(ast, typeId, children); // Nodes - DrawFunctionDecls(ast, FindIdsWith(ast, children)); + DrawFunctionDecls(ast, FindIdsWith(ast, children)); DrawReturns(ast, children); DrawCalls(ast, typeId, children); DrawLiterals(ast, children); @@ -872,9 +858,9 @@ namespace rift::Editor::Graph Nodes::DrawMiniMap(0.2f, Nodes::MiniMapCorner::TopRight); PopNodeStyle(); - if (UI::IsKeyReleased(GLFW_KEY_DELETE)) + if (UI::IsKeyReleased(ImGuiKey_Delete)) { - AST::RemoveNodes(ast, Nodes::GetSelectedNodes()); + ast::RemoveNodes(ast, Nodes::GetSelectedNodes()); } Nodes::EndNodeEditor(); @@ -883,30 +869,30 @@ namespace rift::Editor::Graph Nodes::Id inputPin; if (Nodes::IsLinkCreated(outputPin, inputPin)) { - AST::Id pinIds[2]{AST::Id(outputPin), AST::Id(inputPin)}; + ast::Id pinIds[2]{ast::Id(outputPin), ast::Id(inputPin)}; ScopedChange(ast, pinIds); - AST::TryConnectStmt(ast, AST::Id(outputPin), AST::Id(inputPin)); - AST::TryConnectExpr(ast, AST::GetExprOutputFromPin(ast, AST::Id(outputPin)), - AST::GetExprInputFromPin(ast, AST::Id(inputPin))); + ast::TryConnectStmt(ast, ast::Id(outputPin), ast::Id(inputPin)); + ast::TryConnectExpr(ast, ast::GetExprOutputFromPin(ast, ast::Id(outputPin)), + ast::GetExprInputFromPin(ast, ast::Id(inputPin))); } Nodes::Id linkId; if (Nodes::IsLinkDestroyed(linkId)) { - ScopedChange(ast, AST::Id(linkId)); + ScopedChange(ast, ast::Id(linkId)); // linkId is always the outputId - AST::DisconnectStmtLink(ast, AST::Id(linkId)); - AST::DisconnectExpr(ast, AST::GetExprInputFromPin(ast, AST::Id(linkId))); + ast::DisconnectStmtLink(ast, ast::Id(linkId)); + ast::DisconnectExpr(ast, ast::GetExprInputFromPin(ast, ast::Id(linkId))); } - AST::Id hoveredNodeId = Nodes::GetHoveredNode(); + ast::Id hoveredNodeId = Nodes::GetHoveredNode(); if (!IsNone(hoveredNodeId) && Nodes::IsNodeSelected(hoveredNodeId) && UI::IsMouseClicked(ImGuiMouseButton_Left)) { typeEditor.selectedPropertyId = Nodes::GetHoveredNode(); } - static AST::Id contextHoveredNodeId = AST::NoId; - static AST::Id contextHoveredLinkId = AST::NoId; + static ast::Id contextHoveredNodeId = ast::NoId; + static ast::Id contextHoveredLinkId = ast::NoId; if (wantsToOpenContextMenu) { contextHoveredNodeId = Nodes::GetHoveredNode(); @@ -918,15 +904,15 @@ namespace rift::Editor::Graph UI::End(); } - void SetNodePosition(AST::Id id, v2 position) + void SetNodePosition(ast::Id id, v2 position) { position *= settings.GetGridSize(); Nodes::SetNodeGridSpacePos(id, position); } - v2 GetNodePosition(AST::Id id) + v2 GetNodePosition(ast::Id id) { const v2 pos = Nodes::GetNodeGridSpacePos(id); return v2{pos.x * settings.GetInvGridSize(), pos.y * settings.GetInvGridSize()}.Floor(); } -} // namespace rift::Editor::Graph +} // namespace rift::editor::Graph diff --git a/Libs/Editor/Src/Utils/FunctionGraphContextMenu.cpp b/Libs/Editor/Src/Utils/FunctionGraphContextMenu.cpp index cf65d796..642a8873 100644 --- a/Libs/Editor/Src/Utils/FunctionGraphContextMenu.cpp +++ b/Libs/Editor/Src/Utils/FunctionGraphContextMenu.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/FunctionGraphContextMenu.h" @@ -11,11 +11,9 @@ #include "Utils/TypeUtils.h" #include "Utils/Widgets.h" -#include -#include -#include -#include #include +#include +#include #include #include #include @@ -26,9 +24,9 @@ #include -namespace rift::Editor::Graph +namespace rift::editor::Graph { - void SetPositionAndConnect(AST::Tree& ast, AST::Id id, v2 position) + void SetPositionAndConnect(ast::Tree& ast, ast::Id id, v2 position) { if (!IsNone(id)) { @@ -36,18 +34,18 @@ namespace rift::Editor::Graph // TODO: Improve nodes input to handle this correctly TPair linkPin = Nodes::GetDraggedOriginPin(); - const auto linkPinId = AST::Id(linkPin.first); + const auto linkPinId = ast::Id(linkPin.first); switch (linkPin.second) { case Nodes::PinType::Output: - AST::TryConnectStmt(ast, linkPinId, id); - AST::TryConnectExpr(ast, AST::GetExprOutputFromPin(ast, linkPinId), - AST::GetExprInputFromPin(ast, id)); + ast::TryConnectStmt(ast, linkPinId, id); + ast::TryConnectExpr(ast, ast::GetExprOutputFromPin(ast, linkPinId), + ast::GetExprInputFromPin(ast, id)); break; case Nodes::PinType::Input: - AST::TryConnectStmt(ast, id, linkPinId); - AST::TryConnectExpr(ast, AST::GetExprOutputFromPin(ast, id), - AST::GetExprInputFromPin(ast, linkPinId)); + ast::TryConnectStmt(ast, id, linkPinId); + ast::TryConnectExpr(ast, ast::GetExprOutputFromPin(ast, id), + ast::GetExprInputFromPin(ast, linkPinId)); break; default: break; } @@ -81,61 +79,60 @@ namespace rift::Editor::Graph return false; } - void DrawNodesContextMenu(AST::Tree& ast, AST::Id typeId, TView nodeIds) + void DrawNodesContextMenu(ast::Tree& ast, ast::Id typeId, TView nodeIds) { - Check(!nodeIds.IsEmpty()); - const bool canEditBody = AST::HasFunctionBodies(ast, typeId); + P_Check(!nodeIds.IsEmpty()); + const bool canEditBody = ast::HasFunctionBodies(ast, typeId); - AST::Id firstNodeId = nodeIds[0]; + if (canEditBody && UI::MenuItem("Delete")) + { + ast::RemoveNodes(ast, nodeIds); + } - if (nodeIds.Size() == 1 && ast.Has(firstNodeId)) + ast::Id firstNodeId = nodeIds[0]; + if (nodeIds.Size() == 1 && ast.Has(firstNodeId)) { if (canEditBody && UI::MenuItem("Add return node")) { - AST::Id newId = AST::AddReturn({ast, typeId}); + ast::Id newId = ast::AddReturn({ast, typeId}); if (!IsNone(newId)) { v2 position = ast.Get(firstNodeId).position; ast.Add(newId, position + v2{10.f, 0.f}); - AST::TryConnectStmt(ast, firstNodeId, newId); + ast::TryConnectStmt(ast, firstNodeId, newId); } } } - TArray calls = FindIdsWith(ast, nodeIds); + TArray calls = FindIdsWith(ast, nodeIds); if (!calls.IsEmpty() && UI::MenuItem("Refresh")) { - ast.AddN(calls); - } - - if (canEditBody && UI::MenuItem("Delete")) - { - AST::RemoveNodes(ast, nodeIds); + ast.AddN(calls); } } - void DrawLinksContextMenu(AST::Tree& ast, AST::Id typeId, TView linkIds) + void DrawLinksContextMenu(ast::Tree& ast, ast::Id typeId, TView linkIds) { - Check(!linkIds.IsEmpty()); - const bool canEditBody = AST::HasFunctionBodies(ast, typeId); + P_Check(!linkIds.IsEmpty()); + const bool canEditBody = ast::HasFunctionBodies(ast, typeId); - AST::Id firstLinkId = linkIds[0]; + ast::Id firstLinkId = linkIds[0]; if (canEditBody && UI::MenuItem("Delete")) { ScopedChange(ast, linkIds); - for (AST::Id linkId : linkIds) + for (ast::Id linkId : linkIds) { - AST::DisconnectExpr(ast, AST::GetExprInputFromPin(ast, firstLinkId)); - AST::DisconnectStmtLink(ast, firstLinkId); + ast::DisconnectExpr(ast, ast::GetExprInputFromPin(ast, firstLinkId)); + ast::DisconnectStmtLink(ast, firstLinkId); } } } - void DrawGraphContextMenu(AST::Tree& ast, AST::Id typeId) + void DrawGraphContextMenu(ast::Tree& ast, ast::Id typeId) { static ImGuiTextFilter filter; - const bool canEditBody = AST::HasFunctionBodies(ast, typeId); + const bool canEditBody = ast::HasFunctionBodies(ast, typeId); if (UI::IsWindowAppearing()) { @@ -155,12 +152,12 @@ namespace rift::Editor::Graph { if (ContextItem("Return", filter)) { - AST::Id newId = AST::AddReturn({ast, typeId}); + ast::Id newId = ast::AddReturn({ast, typeId}); SetPositionAndConnect(ast, newId, gridPos); } if (ContextItem("If", filter)) { - AST::Id newId = AST::AddIf({ast, typeId}); + ast::Id newId = ast::AddIf({ast, typeId}); SetPositionAndConnect(ast, newId, gridPos); } ContextTreePop(filter); @@ -169,17 +166,17 @@ namespace rift::Editor::Graph if (ContextTreeNode("Constructors", filter)) { String makeStr{}; - auto& typeList = ast.GetStatic(); - TAccess typesAccess{ast}; - for (Id typeId : FindAllIdsWith(typesAccess)) + auto& typeList = ast.GetStatic(); + TAccess typesAccess{ast}; + for (Id typeId : FindAllIdsWith(typesAccess)) { - if (auto* ns = typesAccess.TryGet(typeId)) + if (auto* ns = typesAccess.TryGet(typeId)) { makeStr.clear(); Strings::FormatTo(makeStr, "Make {}", ns->name); if (ContextItem(makeStr, filter)) { - AST::Id newId = AST::AddLiteral({ast, typeId}, typeId); + ast::Id newId = ast::AddLiteral({ast, typeId}, typeId); SetPositionAndConnect(ast, newId, gridPos); } } @@ -190,16 +187,16 @@ namespace rift::Editor::Graph if (ContextTreeNode("Functions", filter)) { static String label; - TAccess access{ast}; - for (AST::Id functionId : FindAllIdsWith(access)) + TAccess access{ast}; + for (ast::Id functionId : FindAllIdsWith(access)) { - Tag name = access.Get(functionId).name; + Tag name = access.Get(functionId).name; label.clear(); - AST::Id funcTypeId = GetParent(access, functionId); - if (!IsNone(funcTypeId) && access.Has(funcTypeId)) + ast::Id funcTypeId = p::GetIdParent(access, functionId); + if (!IsNone(funcTypeId) && access.Has(funcTypeId)) { Strings::FormatTo(label, "{} ({})", name, - access.Get(funcTypeId).name); + access.Get(funcTypeId).name); } else { @@ -207,7 +204,7 @@ namespace rift::Editor::Graph } if (ContextItem(label, filter)) { - AST::Id newId = AST::AddCall({ast, typeId}, functionId); + ast::Id newId = ast::AddCall({ast, typeId}, functionId); SetPositionAndConnect(ast, newId, gridPos); } } @@ -217,16 +214,16 @@ namespace rift::Editor::Graph if (ContextTreeNode("Variables", filter)) { static String label; - TAccess access{ast}; - for (AST::Id variableId : FindAllIdsWith(access)) + TAccess access{ast}; + for (ast::Id variableId : FindAllIdsWith(access)) { - Tag name = access.Get(variableId).name; + Tag name = access.Get(variableId).name; label.clear(); - AST::Id typeId = p::GetParent(access, variableId); - if (!IsNone(typeId) && access.Has(typeId)) + ast::Id typeId = p::GetIdParent(access, variableId); + if (!IsNone(typeId) && access.Has(typeId)) { Strings::FormatTo( - label, "{} ({})", name, access.Get(typeId).name); + label, "{} ({})", name, access.Get(typeId).name); } else { @@ -234,7 +231,7 @@ namespace rift::Editor::Graph } if (ContextItem(label, filter)) { - AST::Id newId = AST::AddDeclarationReference({ast, typeId}, variableId); + ast::Id newId = ast::AddDeclarationReference({ast, typeId}, variableId); SetPositionAndConnect(ast, newId, gridPos); } } @@ -245,7 +242,7 @@ namespace rift::Editor::Graph { static String name; // Unary operators - for (auto type : GetEnumValues()) + for (auto type : GetEnumValues()) { name.clear(); StringView shortName = GetUnaryOperatorName(type); @@ -253,12 +250,12 @@ namespace rift::Editor::Graph Strings::FormatTo(name, "{} ({})", shortName, longName); if (ContextItem(name, filter)) { - AST::Id newId = AST::AddUnaryOperator({ast, typeId}, type); + ast::Id newId = ast::AddUnaryOperator({ast, typeId}, type); SetPositionAndConnect(ast, newId, gridPos); } } // Binary operators - for (auto type : GetEnumValues()) + for (auto type : GetEnumValues()) { name.clear(); StringView shortName = GetBinaryOperatorName(type); @@ -266,7 +263,7 @@ namespace rift::Editor::Graph Strings::FormatTo(name, "{} ({})", shortName, longName); if (ContextItem(name, filter)) { - AST::Id newId = AST::AddBinaryOperator({ast, typeId}, type); + ast::Id newId = ast::AddBinaryOperator({ast, typeId}, type); SetPositionAndConnect(ast, newId, gridPos); } } @@ -277,7 +274,7 @@ namespace rift::Editor::Graph void DrawLinkContextMenu() {} void DrawContextMenu( - AST::Tree& ast, AST::Id typeId, AST::Id hoveredNodeId, AST::Id hoveredLinkId) + ast::Tree& ast, ast::Id typeId, ast::Id hoveredNodeId, ast::Id hoveredLinkId) { if (UI::BeginPopup("ContextMenu")) { @@ -294,7 +291,7 @@ namespace rift::Editor::Graph } else if (!IsNone(hoveredLinkId)) { - TArray selectedLinkIds; + TArray selectedLinkIds; if (Nodes::GetSelectedLinks(selectedLinkIds)) { DrawLinksContextMenu(ast, typeId, selectedLinkIds); @@ -311,4 +308,4 @@ namespace rift::Editor::Graph UI::EndPopup(); } } -} // namespace rift::Editor::Graph +} // namespace rift::editor::Graph diff --git a/Libs/Editor/Src/Utils/ModuleUtils.cpp b/Libs/Editor/Src/Utils/ModuleUtils.cpp index cf5f57b6..5c977791 100644 --- a/Libs/Editor/Src/Utils/ModuleUtils.cpp +++ b/Libs/Editor/Src/Utils/ModuleUtils.cpp @@ -1,15 +1,15 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/ModuleUtils.h" #include -namespace rift::Editor +namespace rift::editor { - void OpenModuleEditor(TAccessRef, AST::CModule> access, AST::Id id) + void OpenModuleEditor(p::TAccessRef, ast::CModule> access, ast::Id id) { - Check(access.Has(id)); + P_Check(access.Has(id)); if (auto* editor = access.TryGet(id)) { editor->pendingFocus = true; @@ -20,14 +20,14 @@ namespace rift::Editor } } - void CloseModuleEditor(TAccessRef, AST::CModule> access, AST::Id id) + void CloseModuleEditor(p::TAccessRef, ast::CModule> access, ast::Id id) { - Check(access.Has(id)); + P_Check(access.Has(id)); access.Remove(id); } - bool IsEditingModule(TAccessRef access, AST::Id id) + bool IsEditingModule(p::TAccessRef access, ast::Id id) { return access.Has(id); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/Nodes.cpp b/Libs/Editor/Src/Utils/Nodes.cpp index 937aef8c..ede70dca 100644 --- a/Libs/Editor/Src/Utils/Nodes.cpp +++ b/Libs/Editor/Src/Utils/Nodes.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved // the structure of this file: // @@ -15,7 +15,7 @@ #include #include -#include +#include #include #include // strlen, strncmp @@ -29,7 +29,7 @@ namespace rift::Nodes EditorContext& GetEditorContext() { // No editor context was set! Did you forget to call Nodes::CreateContext()? - Check(gNodes->EditorCtx != nullptr); + P_Check(gNodes->EditorCtx != nullptr); return *gNodes->EditorCtx; } @@ -58,7 +58,7 @@ namespace rift::Nodes // Calculates the closest point along each bezier curve segment. v2 GetClosestPointOnCubicBezier(const i32 numSegments, const v2& p, const CubicBezier& cb) { - Ensure(numSegments > 0); + P_Ensure(numSegments > 0); v2 pLast = cb.p0; v2 pClosest; float pClosestDist = FLT_MAX; @@ -87,8 +87,8 @@ namespace rift::Nodes Rect GetContainingRectForCubicBezier(const CubicBezier& cb) { - const v2 min = v2(math::Min(cb.p0.x, cb.p3.x), math::Min(cb.p0.y, cb.p3.y)); - const v2 max = v2(math::Max(cb.p0.x, cb.p3.x), math::Max(cb.p0.y, cb.p3.y)); + const v2 min = v2(p::Min(cb.p0.x, cb.p3.x), p::Min(cb.p0.y, cb.p3.y)); + const v2 max = v2(p::Max(cb.p0.x, cb.p3.x), p::Max(cb.p0.y, cb.p3.y)); const float hoverDistance = gNodes->style.LinkHoverDistance; @@ -389,7 +389,7 @@ namespace rift::Nodes // | | // ----------------------- - void DrawListAddNode(AST::Id nodeId) + void DrawListAddNode(ast::Id nodeId) { gNodes->NodeIdxToSubmissionIdx.SetInt( static_cast(GetIdIndex(nodeId)), gNodes->nodeSubmissionOrder.Size); @@ -429,7 +429,7 @@ namespace rift::Nodes gNodes->CanvasDrawList, foregroundChannelIdx); } - void DrawListActivateNodeBackground(AST::Id nodeId) + void DrawListActivateNodeBackground(ast::Id nodeId) { const i32 submissionIdx = gNodes->NodeIdxToSubmissionIdx.GetInt(static_cast(GetIdIndex(nodeId)), -1); @@ -461,7 +461,7 @@ namespace rift::Nodes gNodes->CanvasDrawList->_Splitter, lhsForegroundChannelIdx, rhsForegroundChannelIdx); } - void DrawListSortChannelsByDepth(const TArray& nodeDepthOrder) + void DrawListSortChannelsByDepth(const TArray& nodeDepthOrder) { if (gNodes->NodeIdxToSubmissionIdx.Data.Size < 2) { @@ -485,7 +485,7 @@ namespace rift::Nodes for (i32 depthIdx = startIdx; depthIdx > 0; --depthIdx) { - const AST::Id nodeId = nodeDepthOrder[depthIdx]; + const ast::Id nodeId = nodeDepthOrder[depthIdx]; // Find the current index of the nodeIdx in the submission order array i32 submissionIdx = -1; @@ -536,7 +536,7 @@ namespace rift::Nodes && gNodes->CanvasRectScreenSpace.Contains(ImGui::GetMousePos()); } - void BeginNodeSelection(EditorContext& editor, AST::Id nodeId) + void BeginNodeSelection(EditorContext& editor, ast::Id nodeId) { // Don't start selecting a node if we are e.g. already creating and dragging // a new link! New link creation can happen when the mouse is clicked over @@ -581,7 +581,7 @@ namespace rift::Nodes refOrigin + gNodes->CanvasOriginScreenSpace + editor.panning - gNodes->mousePosition; editor.SelectedNodeOrigins.clear(); - for (AST::Id id : editor.selectedNodeIds) + for (ast::Id id : editor.selectedNodeIds) { const v2 nodeOrigin = editor.nodes.Get(id).Origin - refOrigin; editor.SelectedNodeOrigins.push_back(nodeOrigin); @@ -722,7 +722,7 @@ namespace rift::Nodes // Test for overlap against node rectangles - for (AST::Id nodeId : editor.nodes) + for (ast::Id nodeId : editor.nodes) { NodeData& node = editor.nodes.Get(nodeId); if (boxRect.Overlaps(node.rect)) @@ -850,7 +850,7 @@ namespace rift::Nodes for (i32 i = 0; i < editor.selectedNodeIds.Size(); ++i) { const v2 nodeRel = editor.SelectedNodeOrigins[i]; - const AST::Id nodeId = editor.selectedNodeIds[i]; + const ast::Id nodeId = editor.selectedNodeIds[i]; NodeData& node = editor.nodes[nodeId]; if (node.Draggable) { @@ -885,8 +885,8 @@ namespace rift::Nodes if (gNodes->leftMouseReleased) { - TArray& depthStack = editor.nodes.depthOrder; - const TArray& selectedIds = editor.selectedNodeIds; + TArray& depthStack = editor.nodes.depthOrder; + const TArray& selectedIds = editor.selectedNodeIds; // Bump the selected node indices, in order, to the top of the depth stack. // NOTE: this algorithm has worst case time complexity of O(N^2), if the @@ -898,7 +898,7 @@ namespace rift::Nodes i32 numMoved = 0; for (i32 i = 0; i < depthStack.Size() - selectedIds.Size(); ++i) { - for (AST::Id nodeId = depthStack[i]; selectedIds.Contains(nodeId); + for (ast::Id nodeId = depthStack[i]; selectedIds.Contains(nodeId); nodeId = depthStack[i]) { depthStack.RemoveAt(i, false); @@ -1050,7 +1050,7 @@ namespace rift::Nodes void ResolveOccludedPins(const EditorContext& editor, ImVector& occludedPinIndices) { - const TArray& depthStack = editor.nodes.depthOrder; + const TArray& depthStack = editor.nodes.depthOrder; occludedPinIndices.resize(0); @@ -1131,11 +1131,11 @@ namespace rift::Nodes return {pinIdxWithSmallestDistance, type}; } - AST::Id ResolveHoveredNode(const TArray& depthStack) + ast::Id ResolveHoveredNode(const TArray& depthStack) { if (gNodes->nodeIdsOverlappingWithMouse.size() == 0) { - return AST::NoId; + return ast::NoId; } if (gNodes->nodeIdsOverlappingWithMouse.size() == 1) @@ -1144,9 +1144,9 @@ namespace rift::Nodes } i32 largestDepthIdx = -1; - AST::Id nodeIdOnTop = AST::NoId; + ast::Id nodeIdOnTop = ast::NoId; - for (AST::Id nodeId : gNodes->nodeIdsOverlappingWithMouse) + for (ast::Id nodeId : gNodes->nodeIdsOverlappingWithMouse) { for (i32 depthIdx = 0; depthIdx < depthStack.Size(); ++depthIdx) { @@ -1158,7 +1158,7 @@ namespace rift::Nodes } } - assert(nodeIdOnTop != AST::NoId); + assert(nodeIdOnTop != ast::NoId); return nodeIdOnTop; } @@ -1416,7 +1416,7 @@ namespace rift::Nodes DrawPinShape(pinData.position, pinData, pinColor); } - void DrawNode(EditorContext& editor, const AST::Id nodeId) + void DrawNode(EditorContext& editor, const ast::Id nodeId) { const NodeData& node = editor.nodes[nodeId]; ImGui::SetCursorPos(node.Origin + editor.panning); @@ -1525,7 +1525,7 @@ namespace rift::Nodes cubicBezier.numSegments); } - void BeginPin(const i32 id, const PinType type, const PinShape shape, AST::Id nodeId) + void BeginPin(const i32 id, const PinType type, const PinShape shape, ast::Id nodeId) { // Make sure to call BeginNode() before calling // BeginPin() @@ -1584,7 +1584,7 @@ namespace rift::Nodes context->currentScope = Scope::None; context->CurrentPinIdx = PinIdx::Invalid(); - context->currentNodeId = AST::NoId; + context->currentNodeId = ast::NoId; context->DefaultEditorCtx = EditorContextCreate(); SetEditorContext(gNodes->DefaultEditorCtx); @@ -1697,7 +1697,7 @@ namespace rift::Nodes editor.panning = pos; } - void MoveToNode(AST::Id nodeId, v2 offset) + void MoveToNode(ast::Id nodeId, v2 offset) { EditorContext& editor = GetEditorContext(); NodeData& node = editor.nodes.Get(nodeId); @@ -1861,7 +1861,7 @@ namespace rift::Nodes ObjectPoolReset(editor.outputs); ObjectPoolReset(editor.links); - gNodes->hoveredNodeId = AST::NoId; + gNodes->hoveredNodeId = ast::NoId; gNodes->HoveredLinkIdx.Reset(); gNodes->HoveredPinIdx = PinIdx::Invalid(); gNodes->DeletedLinkIdx.Reset(); @@ -1979,7 +1979,7 @@ namespace rift::Nodes } } - for (AST::Id nodeId : editor.nodes) + for (ast::Id nodeId : editor.nodes) { DrawListActivateNodeBackground(nodeId); DrawNode(editor, nodeId); @@ -2053,7 +2053,7 @@ namespace rift::Nodes // At this point, draw commands have been issued for all nodes (and pins). Update the // node pool to detect unused node slots and remove those indices from the depth stack // before sorting the node draw commands by depth. - for (AST::Id nodeId : editor.nodes) + for (ast::Id nodeId : editor.nodes) { auto& node = editor.nodes[nodeId]; node.inputs.clear(); @@ -2081,7 +2081,7 @@ namespace rift::Nodes ImGui::EndGroup(); } - void BeginNode(const AST::Id nodeId) + void BeginNode(const ast::Id nodeId) { // Remember to call BeginNodeEditor before calling BeginNode assert(gNodes->currentScope == Scope::Editor); @@ -2140,7 +2140,7 @@ namespace rift::Nodes } } - v2 GetNodeDimensions(AST::Id nodeId) + v2 GetNodeDimensions(ast::Id nodeId) { assert(!IsNone(nodeId)); EditorContext& editor = GetEditorContext(); @@ -2349,35 +2349,35 @@ namespace rift::Nodes } } - void SetNodeScreenSpacePos(AST::Id nodeId, const v2& screenSpacePos) + void SetNodeScreenSpacePos(ast::Id nodeId, const v2& screenSpacePos) { EditorContext& editor = GetEditorContext(); NodeData& node = editor.nodes.GetOrAdd(nodeId); node.Origin = ScreenToGridPosition(editor, screenSpacePos); } - void SetNodeEditorSpacePos(AST::Id nodeId, const v2& editorSpacePos) + void SetNodeEditorSpacePos(ast::Id nodeId, const v2& editorSpacePos) { EditorContext& editor = GetEditorContext(); NodeData& node = editor.nodes.GetOrAdd(nodeId); node.Origin = EditorToGridPosition(editor, editorSpacePos); } - void SetNodeGridSpacePos(AST::Id nodeId, const v2& gridPos) + void SetNodeGridSpacePos(ast::Id nodeId, const v2& gridPos) { EditorContext& editor = GetEditorContext(); NodeData& node = editor.nodes.GetOrAdd(nodeId); node.Origin = gridPos; } - void SetNodeDraggable(AST::Id nodeId, const bool draggable) + void SetNodeDraggable(ast::Id nodeId, const bool draggable) { EditorContext& editor = GetEditorContext(); NodeData& node = editor.nodes.GetOrAdd(nodeId); node.Draggable = draggable; } - v2 GetNodeScreenSpacePos(AST::Id nodeId) + v2 GetNodeScreenSpacePos(ast::Id nodeId) { assert(!IsNone(nodeId)); EditorContext& editor = GetEditorContext(); @@ -2385,7 +2385,7 @@ namespace rift::Nodes return GridToScreenPosition(editor, node.Origin); } - v2 GetNodeEditorSpacePos(AST::Id nodeId) + v2 GetNodeEditorSpacePos(ast::Id nodeId) { assert(!IsNone(nodeId)); EditorContext& editor = GetEditorContext(); @@ -2393,7 +2393,7 @@ namespace rift::Nodes return GridToEditorPosition(editor, node.Origin); } - v2 GetNodeGridSpacePos(AST::Id nodeId) + v2 GetNodeGridSpacePos(ast::Id nodeId) { assert(!IsNone(nodeId)); EditorContext& editor = GetEditorContext(); @@ -2406,34 +2406,34 @@ namespace rift::Nodes return IsMouseInCanvas(); } - AST::Id GetHoveredNode() + ast::Id GetHoveredNode() { return gNodes->hoveredNodeId; } - AST::Id GetHoveredLink() + ast::Id GetHoveredLink() { if (gNodes->HoveredLinkIdx.IsValid()) { const EditorContext& editor = GetEditorContext(); - return AST::Id(editor.links.pool[gNodes->HoveredLinkIdx.Value()].id); + return ast::Id(editor.links.pool[gNodes->HoveredLinkIdx.Value()].id); } - return AST::NoId; + return ast::NoId; } - bool IsNodeHovered(AST::Id nodeId) + bool IsNodeHovered(ast::Id nodeId) { assert(gNodes->currentScope != Scope::None); - return gNodes->hoveredNodeId == nodeId && gNodes->hoveredNodeId != AST::NoId; + return gNodes->hoveredNodeId == nodeId && gNodes->hoveredNodeId != ast::NoId; } - bool IsLinkHovered(AST::Id linkId) + bool IsLinkHovered(ast::Id linkId) { assert(gNodes->currentScope != Scope::None); const EditorContext& editor = GetEditorContext(); return gNodes->HoveredLinkIdx.IsValid() - && linkId == AST::Id(editor.links.pool[gNodes->HoveredLinkIdx.Value()].id); + && linkId == ast::Id(editor.links.pool[gNodes->HoveredLinkIdx.Value()].id); } bool IsPinHovered(Id* const pin) @@ -2465,20 +2465,20 @@ namespace rift::Nodes return editor.selectedLinkIndices.size(); } - const TArray& GetSelectedNodes() + const TArray& GetSelectedNodes() { const EditorContext& editor = GetEditorContext(); return editor.selectedNodeIds; } - bool GetSelectedLinks(TArray& linkIds) + bool GetSelectedLinks(TArray& linkIds) { const EditorContext& editor = GetEditorContext(); linkIds.Resize(editor.selectedLinkIndices.size()); for (i32 i = 0; i < editor.selectedLinkIndices.size(); ++i) { const i32 linkIdx = editor.selectedLinkIndices[i]; - linkIds[i] = AST::Id(editor.links.pool[linkIdx].id); + linkIds[i] = ast::Id(editor.links.pool[linkIdx].id); } return !linkIds.IsEmpty(); } @@ -2489,7 +2489,7 @@ namespace rift::Nodes editor.selectedNodeIds.Clear(); } - void ClearNodeSelection(AST::Id nodeId) + void ClearNodeSelection(ast::Id nodeId) { EditorContext& editor = GetEditorContext(); editor.selectedNodeIds.Remove(nodeId); @@ -2510,7 +2510,7 @@ namespace rift::Nodes editor.selectedLinkIndices.find_erase_unsorted(idx); } - void SelectNode(AST::Id nodeId) + void SelectNode(ast::Id nodeId) { EditorContext& editor = GetEditorContext(); editor.selectedNodeIds.AddUnique(nodeId); @@ -2525,7 +2525,7 @@ namespace rift::Nodes editor.selectedLinkIndices.push_back(idx); } - bool IsNodeSelected(AST::Id nodeId) + bool IsNodeSelected(ast::Id nodeId) { EditorContext& editor = GetEditorContext(); return editor.selectedNodeIds.Contains(nodeId); @@ -2545,7 +2545,7 @@ namespace rift::Nodes bool IsPinActive() { - Check(HasFlag(gNodes->currentScope, Scope::Node)); + P_Check(HasFlag(gNodes->currentScope, Scope::Node)); if (!gNodes->activePin) { @@ -2557,7 +2557,7 @@ namespace rift::Nodes bool IsAnyPinActive(Id* const pinId) { - Check(!HasAnyFlags(gNodes->currentScope, (Scope::Node | Scope::Pin))); + P_Check(!HasAnyFlags(gNodes->currentScope, (Scope::Node | Scope::Pin))); if (!gNodes->activePin) { @@ -2599,8 +2599,8 @@ namespace rift::Nodes bool IsLinkDropped(Id* outputId, Id* inputId, bool includingDetachedLinks) { // Call this function after EndNodeEditor()! - Check(gNodes->currentScope != Scope::None); - Check(outputId != nullptr); + P_Check(gNodes->currentScope != Scope::None); + P_Check(outputId != nullptr); const EditorContext& editor = GetEditorContext(); @@ -2628,7 +2628,7 @@ namespace rift::Nodes bool IsLinkCreated(Id& outputPinId, Id& inputPinId, bool* createdFromSnap) { - Check(gNodes->currentScope == Scope::None); + P_Check(gNodes->currentScope == Scope::None); if ((gNodes->UIState & UIState_LinkCreated) != 0) { @@ -2651,10 +2651,10 @@ namespace rift::Nodes return false; } - bool IsLinkCreated(AST::Id& outputNodeId, Id& outputPinId, AST::Id& inputNodeId, Id& inputPinId, + bool IsLinkCreated(ast::Id& outputNodeId, Id& outputPinId, ast::Id& inputNodeId, Id& inputPinId, bool* createdFromSnap) { - Check(gNodes->currentScope == Scope::None); + P_Check(gNodes->currentScope == Scope::None); if ((gNodes->UIState & UIState_LinkCreated) != 0) { @@ -2681,7 +2681,7 @@ namespace rift::Nodes bool IsLinkDestroyed(Id& linkId) { - Check(gNodes->currentScope == Scope::None); + P_Check(gNodes->currentScope == Scope::None); const bool linkDestroyed = gNodes->DeletedLinkIdx.IsValid(); if (linkDestroyed) diff --git a/Libs/Editor/Src/Utils/NodesMiniMap.cpp b/Libs/Editor/Src/Utils/NodesMiniMap.cpp index 8aba780f..cfc4f186 100644 --- a/Libs/Editor/Src/Utils/NodesMiniMap.cpp +++ b/Libs/Editor/Src/Utils/NodesMiniMap.cpp @@ -1,12 +1,12 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/NodesMiniMap.h" #include "Utils/Nodes.h" #include "Utils/NodesInternal.h" -#include -#include +#include +#include namespace rift::Nodes @@ -87,7 +87,7 @@ namespace rift::Nodes scaling = miniMapScaling; } - void MiniMap::DrawNode(EditorContext& editor, const AST::Id nodeId) + void MiniMap::DrawNode(EditorContext& editor, const ast::Id nodeId) { const NodeData& node = editor.nodes[nodeId]; @@ -95,7 +95,7 @@ namespace rift::Nodes ScreenToMiniMapPosition(editor, node.rect.max)}; // Round to near whole pixel value for corner-rounding to prevent visual glitches - const float miniMapNodeRounding = math::Floor(node.LayoutStyle.CornerRounding * scaling); + const float miniMapNodeRounding = p::Floor(node.LayoutStyle.CornerRounding * scaling); Color miniMapNodeBackground; if (editor.clickInteraction.type == ClickInteractionType_None @@ -199,7 +199,7 @@ namespace rift::Nodes } } - for (AST::Id nodeId : editor.nodes) + for (ast::Id nodeId : editor.nodes) { DrawNode(editor, nodeId); } diff --git a/Libs/Editor/Src/Utils/ProjectManager.cpp b/Libs/Editor/Src/Utils/ProjectManager.cpp index b797a868..5636ef25 100644 --- a/Libs/Editor/Src/Utils/ProjectManager.cpp +++ b/Libs/Editor/Src/Utils/ProjectManager.cpp @@ -1,105 +1,127 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Editor.h" +#include "Statics/EditorSettings.h" #include "Utils/ElementsPanel.h" -#include +#include +#include +#include #include #include -namespace rift::Editor +namespace rift::editor { - void DrawProjectManager(AST::Tree& ast) + void TextCentered(const char* text) + { + auto windowWidth = ImGui::GetWindowSize().x; + auto textWidth = ImGui::CalcTextSize(text).x; + + ImGui::SetCursorPosX((windowWidth - textWidth) * 0.5f); + ImGui::Text(text); + } + + void DrawProjectManager(ast::Tree& ast) { // Center modal when appearing UI::SetNextWindowPos(UI::GetMainViewport()->GetCenter(), ImGuiCond_Always, {0.5f, 0.5f}); - v2 viewportSize = UI::GetMainViewport()->Size; - v2 modalSize = v2{600.f, 400.f}; - modalSize.x = math::Min(modalSize.x, viewportSize.x - 20.f); - modalSize.y = math::Min(modalSize.y, viewportSize.y - 20.f); + p::v2 viewportSize = UI::GetMainViewport()->Size; + p::v2 modalSize = p::v2{600.f, 0.f}; + modalSize.x = p::Min(modalSize.x, viewportSize.x - 20.f); + modalSize.y = p::Min(modalSize.y, viewportSize.y - 20.f); UI::SetNextWindowSize(modalSize, ImGuiCond_Always); if (UI::BeginPopupModal("Project Manager", nullptr, - ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_AlwaysAutoResize)) + ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize)) { - UI::PushFont("WorkSans", UI::FontMode::Regular, 18.f); - UI::Text("Projects"); + UI::PushFont("WorkSans", UI::FontMode::Regular, 24.f); + TextCentered("Projects"); UI::PopFont(); - UI::Separator(); + + UI::Spacing(); UI::Spacing(); - if (UI::Button("Open", v2{-FLT_MIN, 0.0f})) - { - String folder = - files::SelectFolderDialog("Select project folder", p::GetCurrentPath()); - if (Editor::Get().OpenProject(folder)) - { - UI::CloseCurrentPopup(); - } - else - { - UI::AddNotification({UI::ToastType::Error, 1.f, - Strings::Format("Failed to open project at '{}'", p::ToString(folder))}); - } - } - UI::SetItemDefaultFocus(); + static p::String folder; + + ImGui::BeginTable("table", 2); + ImGui::TableNextColumn(); { - UI::Text("Recent Projects"); - static const char* recentProjects[]{"One recent project"}; - static int selectedN = 0; - UI::SetNextItemWidth(-FLT_MIN); - if (UI::BeginListBox("##RecentProjects")) + UI::PushFont("WorkSans", UI::FontMode::Regular, 18.f); + UI::Text("Open"); + UI::PopFont(); + UI::Separator(); + UI::Spacing(); + + UI::SetItemDefaultFocus(); { - for (int n = 0; n < IM_ARRAYSIZE(recentProjects); ++n) + UI::Text("Recent projects:"); + auto& editorSettings = rift::GetUserSettings(); + static const char* recentProjects[]{"Project.rift"}; + static int selectedN = 0; + UI::SetNextItemWidth(-FLT_MIN); + + for (int n = 0; n < editorSettings.recentProjects.Size(); ++n) { const bool isSelected = (selectedN == n); - if (UI::Selectable(recentProjects[n], isSelected)) - { - selectedN = n; - } - - // Set the initial focus when opening the combo (scrolling + keyboard - // navigation focus) - if (isSelected) + p::StringView path = editorSettings.recentProjects[n]; + UI::BulletText(path.data()); + UI::SameLine(ImGui::GetContentRegionAvail().x - 30.f); + if (UI::SmallButton("open")) { - UI::SetItemDefaultFocus(); + if (Editor::Get().OpenProject(path)) + { + UI::CloseCurrentPopup(); + } + else + { + UI::AddNotification({UI::ToastType::Error, 1.f, + p::Strings::Format("Failed to open project at '{}'", path)}); + } } } - UI::EndListBox(); } + UI::Dummy({10.f, 40.f}); } - - - UI::Spacing(); - UI::Spacing(); - UI::Spacing(); - UI::Spacing(); - - UI::PushFont("WorkSans", UI::FontMode::Regular, 18.f); - UI::Text("New"); - UI::PopFont(); - UI::Separator(); - UI::Spacing(); - - UI::AlignTextToFramePadding(); - UI::Text("Destination"); - UI::SameLine(); - static String folder; - UI::PushItemWidth(-32.f); - UI::InputText("##path", folder); - UI::PopItemWidth(); - UI::SameLine(); - if (UI::Button("...", v2{24.f, 0.f})) + ImGui::TableNextColumn(); { - Path selectedFolder = - files::SelectFolderDialog("Select project folder", p::GetCurrentPath()); - folder = p::ToString(selectedFolder); + UI::PushFont("WorkSans", UI::FontMode::Regular, 18.f); + UI::Text("Create"); + UI::PopFont(); + UI::Separator(); + UI::Spacing(); + + UI::PushItemWidth(-32.f); + UI::InputTextWithHint("##path", "project path...", folder); + UI::PopItemWidth(); + UI::SameLine(); + if (UI::Button("...", p::v2{24.f, 0.f})) + { + folder = p::SelectFolderDialog( + "Select project folder", p::PlatformPaths::GetCurrentPath()); + } } - if (UI::Button("Create", v2{-FLT_MIN, 0.0f})) + ImGui::TableNextRow(); + ImGui::TableNextColumn(); + if (UI::Button("Open", p::v2{-FLT_MIN, 0.0f})) + { + p::String folder = p::SelectFolderDialog( + "Select project folder", p::PlatformPaths::GetCurrentPath()); + if (Editor::Get().OpenProject(folder)) + { + UI::CloseCurrentPopup(); + } + else + { + UI::AddNotification({UI::ToastType::Error, 1.f, + p::Strings::Format("Failed to open project at '{}'", p::ToString(folder))}); + } + } + ImGui::TableNextColumn(); + if (UI::Button("Create", p::v2{-FLT_MIN, 0.0f})) { if (Editor::Get().CreateProject(folder)) { @@ -109,9 +131,10 @@ namespace rift::Editor else { UI::AddNotification({UI::ToastType::Error, 1.f, - Strings::Format("Failed to create project at '{}'", folder)}); + p::Strings::Format("Failed to create project at '{}'", folder)}); } } + ImGui::EndTable(); UI::EndPopup(); } @@ -121,4 +144,4 @@ namespace rift::Editor { UI::OpenPopup("Project Manager"); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/TypeUtils.cpp b/Libs/Editor/Src/Utils/TypeUtils.cpp index 61dd6e46..f39bcb22 100644 --- a/Libs/Editor/Src/Utils/TypeUtils.cpp +++ b/Libs/Editor/Src/Utils/TypeUtils.cpp @@ -1,16 +1,16 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/TypeUtils.h" #include -#include +#include -namespace rift::Editor +namespace rift::editor { - void OpenType(TAccessRef, AST::CDeclType> access, AST::Id id) + void OpenType(p::TAccessRef, ast::CDeclType> access, ast::Id id) { - Check(access.Has(id)); + P_Check(access.Has(id)); if (auto* editor = access.TryGet(id)) { editor->pendingFocus = true; @@ -21,14 +21,14 @@ namespace rift::Editor } } - void CloseType(TAccessRef, AST::CDeclType> access, AST::Id id) + void CloseType(p::TAccessRef, ast::CDeclType> access, ast::Id id) { - Check(access.Has(id)); + P_Check(access.Has(id)); access.Remove(id); } - bool IsTypeOpen(TAccessRef access, AST::Id id) + bool IsTypeOpen(p::TAccessRef access, ast::Id id) { return access.Has(id); } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Editor/Src/Utils/Widgets.cpp b/Libs/Editor/Src/Utils/Widgets.cpp index eb5d355b..98ff1c0d 100644 --- a/Libs/Editor/Src/Utils/Widgets.cpp +++ b/Libs/Editor/Src/Utils/Widgets.cpp @@ -1,18 +1,18 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "Utils/Widgets.h" #include -namespace rift::Editor +namespace rift::editor { - void ListTypesFromFilter(p::TAccessRef access, p::TArray typeIds, - AST::Id& selectedId, ImGuiTextFilter& searchFilter) + void ListTypesFromFilter(p::TAccessRef access, p::TArray typeIds, + ast::Id& selectedId, ImGuiTextFilter& searchFilter) { - for (AST::Id id : typeIds) + for (ast::Id id : typeIds) { - const auto& type = access.Get(id); + const auto& type = access.Get(id); p::StringView name = type.name.AsString(); if (!searchFilter.PassFilter(name.data(), name.data() + name.size())) @@ -29,18 +29,18 @@ namespace rift::Editor } } - bool TypeCombo(p::TAccessRef + bool TypeCombo(p::TAccessRef access, - p::StringView label, AST::Id& selectedId) + p::StringView label, ast::Id& selectedId) { p::Tag ownerName; if (!IsNone(selectedId)) { - ownerName = access.Get(selectedId).name; + ownerName = access.Get(selectedId).name; } - AST::Id lastId = selectedId; + ast::Id lastId = selectedId; if (UI::BeginCombo(label.data(), ownerName.AsString().data())) { static ImGuiTextFilter filter; @@ -52,11 +52,11 @@ namespace rift::Editor filter.Draw("##Filter"); auto nativeIds = - p::FindAllIdsWith(access); + p::FindAllIdsWith(access); auto structIds = - p::FindAllIdsWith(access); + p::FindAllIdsWith(access); auto classIds = - p::FindAllIdsWith(access); + p::FindAllIdsWith(access); if (filter.IsActive()) { if (UI::TreeNodeEx("Native##Filtered", ImGuiTreeNodeFlags_DefaultOpen)) @@ -98,8 +98,8 @@ namespace rift::Editor return selectedId != lastId; } - bool InputLiteralValue(AST::Tree& ast, p::StringView label, AST::Id literalId) + bool InputLiteralValue(ast::Tree& ast, p::StringView label, ast::Id literalId) { return false; } -} // namespace rift::Editor +} // namespace rift::editor diff --git a/Libs/Runtimes/Std/Include/IO.h b/Libs/Runtimes/Std/Include/IO.h index 4f388ce8..f30d902c 100644 --- a/Libs/Runtimes/Std/Include/IO.h +++ b/Libs/Runtimes/Std/Include/IO.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once extern "C" diff --git a/Libs/Runtimes/Std/Include/Math.h b/Libs/Runtimes/Std/Include/Math.h index c7803966..f30dbd42 100644 --- a/Libs/Runtimes/Std/Include/Math.h +++ b/Libs/Runtimes/Std/Include/Math.h @@ -1,2 +1,2 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once diff --git a/Libs/Runtimes/Std/Src/IO.cpp b/Libs/Runtimes/Std/Src/IO.cpp index be6e0410..474504f8 100644 --- a/Libs/Runtimes/Std/Src/IO.cpp +++ b/Libs/Runtimes/Std/Src/IO.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "IO.h" @@ -9,7 +9,7 @@ extern "C" { void Print(const char* text) { - printf(text); + printf("%s", text); } void PrintHelloWorld() diff --git a/Libs/Runtimes/Std/Src/Math.cpp b/Libs/Runtimes/Std/Src/Math.cpp index 4cec711e..c78a1582 100644 --- a/Libs/Runtimes/Std/Src/Math.cpp +++ b/Libs/Runtimes/Std/Src/Math.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved // Dummy const char* gA = ""; diff --git a/Libs/UI/CMakeLists.txt b/Libs/UI/CMakeLists.txt index bb5a56fb..cbb67938 100644 --- a/Libs/UI/CMakeLists.txt +++ b/Libs/UI/CMakeLists.txt @@ -1,18 +1,19 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftUI STATIC) +add_library(RiftUILib STATIC) -target_include_directories(RiftUI PUBLIC Include) +target_include_directories(RiftUILib PUBLIC Include) file(GLOB_RECURSE UI_SOURCE_FILES CONFIGURE_DEPENDS Src/*.cpp Src/*.h) -target_sources(RiftUI PRIVATE ${UI_SOURCE_FILES}) +target_sources(RiftUILib PRIVATE ${UI_SOURCE_FILES}) -target_link_libraries(RiftUI PUBLIC +target_link_libraries(RiftUILib PUBLIC Pipe glfw gl3w imgui IconFontCppHeaders ) -target_compile_definitions(RiftUI PRIVATE NOMINMAX) +target_link_libraries(RiftUILib PRIVATE stb_image) +target_compile_definitions(RiftUILib PRIVATE NOMINMAX) -rift_module(RiftUI) +rift_module(RiftUILib) diff --git a/Libs/UI/Include/UI/Inspection.h b/Libs/UI/Include/UI/Inspection.h index f72bf02e..98947262 100644 --- a/Libs/UI/Include/UI/Inspection.h +++ b/Libs/UI/Include/UI/Inspection.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -6,56 +6,147 @@ #include "UI/UIImgui.h" #include "UI/Widgets.h" -#include -#include -#include -#include -#include -#include +#include namespace rift::UI { - using namespace p; + struct ValueHandle + { + protected: + void* container = nullptr; + p::TypeId containerType; + const p::TypeProperty* property = nullptr; + p::i32 index = p::NO_INDEX; + + + public: + ValueHandle(void* container, p::TypeId containerType) + : container{container}, containerType{containerType} + {} + ValueHandle(void* container, p::TypeId containerType, const p::TypeProperty& property) + : container{container}, containerType{containerType}, property{&property} + {} + ValueHandle(void* data, const p::TypeProperty* property, p::i32 index) + : container{data}, property{property}, index{index} + { + // P_Check(GetArrayProperty()); + } + ValueHandle(const ValueHandle& container, p::i32 index) + : ValueHandle(container.GetPtr(), container.GetProperty(), index) + {} + + ValueHandle(const ValueHandle& other) = default; + ValueHandle& operator=(const ValueHandle& other) = default; + + const p::TypeProperty* GetProperty() const + { + return property; + } + + bool IsArray() const + { + return !IsArrayItem() && property && property->HasFlag(p::PF_Array); + } + bool IsArrayItem() const + { + return index != p::NO_INDEX; + } + + // const ArrayProperty* GetArrayProperty() const + //{ + // if (property && property->HasFlag(PF_Array)) + // { + // return static_cast(property); + // } + // return nullptr; + // } + + virtual void GetDisplayName(p::String& name) const + { + if (index != p::NO_INDEX) + { + p::Strings::FormatTo(name, "{}", index); + } + else if (property) + { + name.append(p::Strings::ToSentenceCase(property->name.AsString())); + } + } + p::TypeId GetType() const + { + return containerType; + } - // label, data, type - using CustomKeyValue = TFunction; + void* GetContainer() const + { + P_Check(index != p::NO_INDEX); + return container; + } + p::i32 GetIndex() const + { + return index; + } - void RegisterCustomInspection(Type* typeId, const CustomKeyValue& custom); + void* GetPtr() const + { + // const auto* arrayProp = GetArrayProperty(); + // if (arrayProp && index != NO_INDEX) + //{ + // return arrayProp->GetItem(container, index); + // } + return container; + } + + bool IsValid() const + { + return container != nullptr; + } + + operator bool() const + { + return IsValid(); + } + }; + + + using CustomKeyValue = p::TFunction; + + + void RegisterCustomInspection(p::TypeId type, const CustomKeyValue& custom); template void RegisterCustomInspection(const CustomKeyValue& custom) { - RegisterCustomInspection(GetType(), custom); + RegisterCustomInspection(p::GetTypeId(), custom); } - void DrawEnumValue(void* data, EnumType* type); - void DrawNativeValue(void* data, NativeType* type); - void DrawKeyValue(StringView label, void* data, Type* type); + void DrawEnumValue(void* data, p::TypeId type); + void DrawNativeValue(void* data, p::TypeId type); + void DrawKeyValue(p::StringView label, void* data, p::TypeId type); - void InspectProperty(const PropertyHandle& property); - void InspectProperties(void* container, DataType* type); + void InspectProperty(const ValueHandle& handle); + void InspectChildrenProperties(const ValueHandle& handle); - inline void InspectStruct(Struct* data, StructType* type) + inline void InspectStruct(void* data, p::TypeId type) { - InspectProperties(data, type); + if (p::HasTypeFlags(type, p::TF_Struct)) + { + InspectChildrenProperties({data, type}); + } } template inline void InspectStruct(T* data) - requires(Derived) - { - InspectStruct(data, T::GetStaticType()); - } - inline void InspectClass(Class* data, ClassType* type) + requires(p::IsStructOrClass) { - InspectProperties(data, type); + InspectStruct(data, GetTypeId()); } - bool BeginInspectHeader(StringView label, bool isLeaf = false); - void EndInspectHeader(); + bool BeginCategory(p::StringView name, bool isLeaf); + void EndCategory(); - bool BeginInspector(const char* name, v2 size = v2{0.f, 0.f}); + bool BeginInspector(const char* name, p::v2 size = p::v2{0.f, 0.f}); void EndInspector(); void RegisterCoreKeyValueInspections(); diff --git a/Libs/UI/Include/UI/Notify.h b/Libs/UI/Include/UI/Notify.h index 3a048b10..6b882032 100644 --- a/Libs/UI/Include/UI/Notify.h +++ b/Libs/UI/Include/UI/Notify.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -9,7 +9,7 @@ namespace rift::UI { - enum class ToastType : u8 + enum class ToastType : p::u8 { None = 0, Success, @@ -22,8 +22,8 @@ namespace rift::UI { ToastType type = ToastType::None; float durationTime = 3.f; - String title; - String message; + p::String title; + p::String message; }; void AddNotification(Toast toast); diff --git a/Libs/UI/Include/UI/Paths.h b/Libs/UI/Include/UI/Paths.h index bff1bd11..d4ebce02 100644 --- a/Libs/UI/Include/UI/Paths.h +++ b/Libs/UI/Include/UI/Paths.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -7,8 +7,5 @@ namespace rift::Paths { - using namespace p; - - - Path GetResourcesPath(); + p::String GetResourcesPath(); }; // namespace rift::Paths diff --git a/Libs/UI/Include/UI/Style.h b/Libs/UI/Include/UI/Style.h index 2b718460..bc4dd35b 100644 --- a/Libs/UI/Include/UI/Style.h +++ b/Libs/UI/Include/UI/Style.h @@ -1,45 +1,43 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include -#include +#include +#include +#include namespace rift::UI { - using namespace p; + constexpr p::LinearColor primaryColor = p::LinearColor::FromHex(0xD6863B); + constexpr p::LinearColor whiteTextColor = p::LinearColor::White().Shade(0.05f); + constexpr p::LinearColor blackTextColor = p::LinearColor::Black().Tint(0.05f); - constexpr LinearColor primaryColor = LinearColor::FromHEX(0xD6863B); + constexpr p::LinearColor infoColor = p::LinearColor::FromHex(0x2B8ED6); + constexpr p::LinearColor successColor = p::LinearColor::FromHex(0x4DD62B); + constexpr p::LinearColor warningColor = p::LinearColor::FromHex(0xD6AB2B); + constexpr p::LinearColor errorColor = p::LinearColor::FromHex(0xD62B2B); - constexpr LinearColor whiteTextColor = LinearColor::White().Shade(0.05f); - constexpr LinearColor blackTextColor = LinearColor::Black().Tint(0.05f); - constexpr LinearColor infoColor = LinearColor::FromHEX(0x2B8ED6); - constexpr LinearColor successColor = LinearColor::FromHEX(0x4DD62B); - constexpr LinearColor warningColor = LinearColor::FromHEX(0xD6AB2B); - constexpr LinearColor errorColor = LinearColor::FromHEX(0xD62B2B); - - - constexpr LinearColor GetNeutralColor(u8 level) + constexpr p::LinearColor GetNeutralColor(p::u8 level) { switch (level) { default: - case 0: return LinearColor::FromHEX(0x222222); - case 1: return LinearColor::FromHEX(0x3B3B3B); - case 2: return LinearColor::FromHEX(0x464646); - case 3: return LinearColor::FromHEX(0x515151); - case 4: return LinearColor::FromHEX(0x626262); - case 5: return LinearColor::FromHEX(0x6E6E6E); - case 6: return LinearColor::FromHEX(0x9E9E9E); - case 7: return LinearColor::FromHEX(0xB1B1B1); - case 8: return LinearColor::FromHEX(0xCFCFCF); - case 9: return LinearColor::FromHEX(0xE1E1E1); - case 10: return LinearColor::FromHEX(0xF7F7F7); + case 0: return p::LinearColor::FromHex(0x222222); + case 1: return p::LinearColor::FromHex(0x3B3B3B); + case 2: return p::LinearColor::FromHex(0x464646); + case 3: return p::LinearColor::FromHex(0x515151); + case 4: return p::LinearColor::FromHex(0x626262); + case 5: return p::LinearColor::FromHex(0x6E6E6E); + case 6: return p::LinearColor::FromHex(0x9E9E9E); + case 7: return p::LinearColor::FromHex(0xB1B1B1); + case 8: return p::LinearColor::FromHex(0xCFCFCF); + case 9: return p::LinearColor::FromHex(0xE1E1E1); + case 10: return p::LinearColor::FromHex(0xF7F7F7); } } - inline LinearColor GetNeutralTextColor(u8 level) + inline p::LinearColor GetNeutralTextColor(p::u8 level) { return level <= 5 ? whiteTextColor : blackTextColor; } @@ -72,29 +70,4 @@ namespace rift::UI void PushGeneralStyle(); void PopGeneralStyle(); - - void PushStyleCompact(); - void PopStyleCompact(); - - void PushFrameBgColor(LinearColor color); - void PopFrameBgColor(); - void PushButtonColor(LinearColor color); - void PopButtonColor(); - void PushHeaderColor(LinearColor color = GetNeutralColor(2)); - void PopHeaderColor(); - - void PushTextColor(LinearColor color); - void PopTextColor(); - - template - TColor Hovered(const TColor& color) - { - return color.Shade(0.1f); - } - - template - TColor Disabled(const TColor& color) - { - return color.Shade(0.2f); - } }; // namespace rift::UI diff --git a/Libs/UI/Include/UI/UI.h b/Libs/UI/Include/UI/UI.h index 7b6b0432..89fcc390 100644 --- a/Libs/UI/Include/UI/UI.h +++ b/Libs/UI/Include/UI/UI.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include "UI/Style.h" diff --git a/Libs/UI/Include/UI/UIImgui.h b/Libs/UI/Include/UI/UIImgui.h index 70a27fb9..a50f317e 100644 --- a/Libs/UI/Include/UI/UIImgui.h +++ b/Libs/UI/Include/UI/UIImgui.h @@ -1,17 +1,18 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once -#include #include -#include -#include +#include +#include +#include -#define IM_VEC2_CLASS_EXTRA \ - constexpr ImVec2(p::v2 other) : x(other.x), y(other.y) {} \ - constexpr operator p::v2() const \ - { \ - return p::v2{x, y}; \ +#define IM_VEC2_CLASS_EXTRA \ + constexpr ImVec2(p::v2 other) : x(other.x), y(other.y) \ + {} \ + constexpr operator p::v2() const \ + { \ + return p::v2{x, y}; \ } #define IM_VEC4_CLASS_EXTRA \ @@ -21,7 +22,8 @@ { \ return p::LinearColor{x, y, z, w}; \ } \ - constexpr ImVec4(const p::v4& other) : x(other.x), y(other.y), z(other.z), w(other.w) {} \ + constexpr ImVec4(const p::v4& other) : x(other.x), y(other.y), z(other.z), w(other.w) \ + {} \ constexpr operator p::v4() const \ { \ return p::v4{x, y, z, w}; \ @@ -31,109 +33,10 @@ #define IMGUI_DEFINE_MATH_OPERATORS #include #include +#include namespace rift::UI { - using namespace p; using namespace ImGui; - - // Begin ImGui API override - // Push string into the ID stack (will hash string) - inline void PushID(const char* str_id) - { - ImGui::PushID(str_id); - } - // Push string into the ID stack (will hash string) - inline void PushID(const char* str_id_begin, const char* str_id_end) - { - ImGui::PushID(str_id_begin, str_id_end); - } - // Push pointer into the ID stack (will hash pointer) - inline void PushID(const void* ptr_id) - { - ImGui::PushID(ptr_id); - } - - inline ImGuiID GetID(const char* str_id) - { - return ImGui::GetID(str_id); - } - inline ImGuiID GetID(const char* str_id_begin, const char* str_id_end) - { - return ImGui::GetID(str_id_begin, str_id_end); - } - inline ImGuiID GetID(const void* ptr_id) - { - return ImGui::GetID(ptr_id); - } - inline void PushStyleColor(ImGuiCol idx, u32 col) - { - ImGui::PushStyleColor(idx, col); - } - inline void PushStyleColor(ImGuiCol idx, const ImVec4& col) - { - ImGui::PushStyleColor(idx, col); - } - // End ImGui API override - - - inline void PushID(StringView id) - { - UI::PushID(id.data(), id.data() + id.size()); - } - - template - inline void PushID(T id) - { - UI::PushID(reinterpret_cast(sizet(id))); - } - - inline ImGuiID GetID(StringView id) - { - return UI::GetID(id.data(), id.data() + id.size()); - } - - inline void PushStyleColor(ImGuiCol idx, Color color) - { - ImGui::PushStyleColor(idx, color.DWColor()); - } - - inline void PushStyleColor(ImGuiCol idx, const LinearColor& color) - { - ImGui::PushStyleColor(idx, color); - } - - inline void Text(const char* fmt, ...) - { - va_list args; - va_start(args, fmt); - TextV(fmt, args); - va_end(args); - } - inline void Text(StringView text) - { - TextUnformatted(text.data(), text.data() + text.size()); - } - - inline void TextColoredUnformatted( - const LinearColor& color, const char* text, const char* textEnd = nullptr) - { - PushStyleColor(ImGuiCol_Text, color); - TextUnformatted(text, textEnd); - PopStyleColor(); - } - - inline void TextColored(const LinearColor& color, const char* fmt, ...) - { - va_list args; - va_start(args, fmt); - TextColoredV(ImVec4(color), fmt, args); - va_end(args); - } - inline void TextColored(const LinearColor& color, StringView text) - { - TextColoredUnformatted(color, text.data(), text.data() + text.size()); - } - } // namespace rift::UI diff --git a/Libs/UI/Include/UI/Widgets.h b/Libs/UI/Include/UI/Widgets.h index 1a44d695..1da1ad13 100644 --- a/Libs/UI/Include/UI/Widgets.h +++ b/Libs/UI/Include/UI/Widgets.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -15,23 +15,23 @@ namespace rift::UI struct AnimatedSprite { ImTextureID textureId; - v2 size{}; + p::v2 size{}; float rate = 1.f / 24.f; // Number of frames in each row - TArray numFrames{}; + p::TArray numFrames{}; - v2_u32 currentFrame{}; + p::v2_u32 currentFrame{}; float currentFrameRemainingTime = 0.f; - void SetAnimation(u32 id); + void SetAnimation(p::u32 id); void NextFrame(float deltaTime); - v2 GetUV() const; + p::v2 GetUV() const; }; - static bool SpriteButton(AnimatedSprite& sprite, i32 framePadding, const LinearColor& bgColor, - const LinearColor& tintColor); + static bool SpriteButton(AnimatedSprite& sprite, p::i32 framePadding, + const p::LinearColor& bgColor, const p::LinearColor& tintColor); inline bool InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, @@ -59,46 +59,63 @@ namespace rift::UI bool InputTextMultiline(const char* label, p::String& str, const ImVec2& size = ImVec2(0, 0), ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* userData = nullptr); - bool InputTextWithHint(const char* label, const char* hint, String& str, + bool InputTextWithHint(const char* label, const char* hint, p::String& str, ImGuiInputTextFlags flags = 0, ImGuiInputTextCallback callback = nullptr, void* userData = nullptr); - - static bool Begin(const char* name, bool* pOpen = nullptr, ImGuiWindowFlags flags = 0) + static void BeginOuterStyle() { - LinearColor titleColor = UI::GetNeutralColor(0); + p::LinearColor titleColor = UI::GetNeutralColor(0); UI::PushStyleColor(ImGuiCol_TitleBg, titleColor); UI::PushStyleColor(ImGuiCol_TitleBgActive, titleColor); - UI::PushStyleColor(ImGuiCol_TitleBgCollapsed, UI::Disabled(titleColor)); + UI::PushStyleColor(ImGuiCol_TitleBgCollapsed, UI::ToDisabled(titleColor)); - LinearColor tabColorActive = UI::GetNeutralColor(1); - LinearColor tabColor = UI::Disabled(tabColorActive); + p::LinearColor tabColorActive = UI::GetNeutralColor(1); + p::LinearColor tabColor = UI::ToDisabled(tabColorActive); UI::PushStyleColor(ImGuiCol_Tab, tabColor); UI::PushStyleColor(ImGuiCol_TabActive, tabColorActive); UI::PushStyleColor(ImGuiCol_TabUnfocused, tabColor); UI::PushStyleColor(ImGuiCol_TabUnfocusedActive, tabColorActive); - UI::PushStyleColor(ImGuiCol_TabHovered, UI::Hovered(tabColorActive)); + UI::PushStyleColor(ImGuiCol_TabHovered, UI::ToHovered(tabColorActive)); UI::PushTextColor(UI::GetNeutralTextColor(1)); + } + static void BeginInnerStyle() + { + UI::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.f, 3.f)); + } + static void EndOuterStyle() + { + UI::PopTextColor(); + UI::PopStyleColor(8); + } + static void EndInnerStyle() + { + UI::PopStyleVar(); + } + static bool Begin(const char* name, bool* pOpen = nullptr, ImGuiWindowFlags flags = 0) + { + BeginOuterStyle(); const bool value = ImGui::Begin(name, pOpen, flags); - - UI::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(2.f, 3.f)); + BeginInnerStyle(); return value; } static void End() { - UI::PopStyleVar(); + EndInnerStyle(); ImGui::End(); - UI::PopTextColor(); - UI::PopStyleColor(5); - UI::PopStyleColor(3); + EndOuterStyle(); } - ImRect GetWorkRect(v2 desiredSize, bool addhalfItemSpacing = true, v2 extent = v2::Zero()); + ImRect GetWorkRect( + p::v2 desiredSize, bool addhalfItemSpacing = true, p::v2 extent = p::v2::Zero()); bool MutableText(p::StringView label, p::String& text, ImGuiInputTextFlags flags = 0); - void HelpTooltip(p::StringView text, float delay = 1.f); - void HelpMarker(p::StringView text); + bool DrawFilterWithHint(ImGuiTextFilter& filter, const char* label = "Filter (inc,-exc)", + const char* hint = "...", float width = 0.0f); + + bool CollapsingHeaderWithButton(p::StringView label, ImGuiTreeNodeFlags flags, + bool& buttonClicked, p::StringView buttonLabel, p::v2 buttonSize = p::v2(18.f, 14.f)); } // namespace rift::UI diff --git a/Libs/UI/Include/UI/Window.h b/Libs/UI/Include/UI/Window.h index 01e12673..688d1ede 100644 --- a/Libs/UI/Include/UI/Window.h +++ b/Libs/UI/Include/UI/Window.h @@ -1,10 +1,10 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once #include -#include #include +#include struct GLFWwindow; @@ -22,4 +22,6 @@ namespace rift::UI bool WantsToClose(); GLFWwindow* GetWindow(); + + void SetWindowIcon(); }; // namespace rift::UI diff --git a/Libs/UI/Src/Inspection.cpp b/Libs/UI/Src/Inspection.cpp index 19e77b50..10762a51 100644 --- a/Libs/UI/Src/Inspection.cpp +++ b/Libs/UI/Src/Inspection.cpp @@ -1,305 +1,287 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Inspection.h" #include "imgui.h" #include +#include #include #include -#include -#include namespace rift::UI { static const char* gCurrentInspector = nullptr; - static TMap gCustomKeyValues; + static p::TMap gCustomKeyValues; - void RegisterCustomInspection(Type* typeId, const CustomKeyValue& custom) + void RegisterCustomInspection(p::TypeId type, const CustomKeyValue& custom) { if (custom) { - gCustomKeyValues.Insert(typeId, custom); + gCustomKeyValues.Insert(type, custom); } } - void DrawEnumValue(void* data, EnumType* type) + void DrawEnumValue(void* data, p::TypeId type) { - static String label; + static p::String label; label.clear(); - Strings::FormatTo(label, "##{}", sizet(data)); - + p::Strings::FormatTo(label, "##{}", p::sizet(data)); + /* const i32 currentIndex = type->GetIndexFromValue(data); if (UI::BeginCombo(label.c_str(), type->GetNameByIndex(currentIndex).AsString().data())) { - for (i32 i = 0; i < type->Size(); ++i) - { - const bool isSelected = currentIndex == i; - - if (UI::Selectable(type->GetNameByIndex(i).AsString().data(), isSelected)) - { - type->SetValueFromIndex(data, i); - } - - // Set the initial focus when opening the combo - if (isSelected) - { - UI::SetItemDefaultFocus(); - } - } - UI::EndCombo(); + for (i32 i = 0; i < type->Size(); ++i) + { + const bool isSelected = currentIndex == i; + + if (UI::Selectable(type->GetNameByIndex(i).AsString().data(), isSelected)) + { + type->SetValueFromIndex(data, i); + } + + // Set the initial focus when opening the combo + if (isSelected) + { + UI::SetItemDefaultFocus(); + } + } + UI::EndCombo(); } + */ } - void DrawNativeValue(void* data, NativeType* type) + void DrawNativeValue(void* data, p::TypeId type) { - static String label; + static p::String label; label.clear(); - Strings::FormatTo(label, "##{}", sizet(data)); + p::Strings::FormatTo(label, "##{}", p::sizet(data)); - if (type == GetType()) - { - UI::Checkbox(label.c_str(), static_cast(data)); - } - else if (type == GetType()) + switch (type.GetId()) { - UI::InputText(label.c_str(), *static_cast(data)); - } - else if (type == GetType()) - { - Tag& name = *static_cast(data); - String text{name.AsString()}; - if (UI::InputText(label.c_str(), text)) - { - name = Tag{text}; + case p::GetTypeId().GetId(): + UI::Checkbox(label.c_str(), static_cast(data)); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_U8, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_S32, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_U32, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_S64, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_U64, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_Float, data); + break; + case p::GetTypeId().GetId(): + UI::InputScalar(label.c_str(), ImGuiDataType_Double, data); + break; + case p::GetTypeId().GetId(): + UI::InputFloat2(label.c_str(), static_cast(data)); + break; + case p::GetTypeId().GetId(): + UI::InputFloat3(label.c_str(), static_cast(data)); + break; + case p::GetTypeId().GetId(): + UI::InputText(label.c_str(), *static_cast(data)); + break; + case p::GetTypeId().GetId(): { + auto& name = *static_cast(data); + p::String text{name.AsString()}; + if (UI::InputText(label.c_str(), text)) + { + name = p::Tag{text}; + } } } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_U8, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_S32, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_U32, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_S64, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_U64, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_Float, data); - } - else if (type == GetType()) - { - UI::InputScalar(label.c_str(), ImGuiDataType_Double, data); - } - else if (type == GetType()) - { - UI::InputFloat2(label.c_str(), static_cast(data)); - } - else if (type == GetType()) - { - UI::InputFloat3(label.c_str(), static_cast(data)); - } } - void DrawKeyValue(StringView label, void* data, Type* type) + void DrawKeyValue(p::StringView label, void* data, p::TypeId type) { UI::TableNextRow(); UI::TableSetColumnIndex(0); UI::AlignTextToFramePadding(); UI::Text(label); UI::TableSetColumnIndex(1); - if (auto* nativeType = Cast(type)) + if (p::HasTypeFlags(type, p::TF_Native)) { - DrawNativeValue(data, nativeType); + DrawNativeValue(data, type); } - else if (auto* enumType = Cast(type)) + else if (p::HasTypeFlags(type, p::TF_Enum)) { - DrawEnumValue(data, enumType); + DrawEnumValue(data, type); } } - void DrawArrayValue(bool open, const ArrayProperty& property, void* instance) + void DrawArrayValue(p::TypeId type, void* instance) { - UI::Text(Strings::Format("{} items", property.GetSize(instance))); + const p::ContainerTypeOps* ops = p::GetTypeContainerOps(type); + if (!ops) + { + return; + } + + UI::Text(p::Strings::Format("{} items", ops->GetSize(instance))); // Ignore indent on buttons const float widthAvailable = - ImGui::GetContentRegionAvailWidth() + UI::GetCurrentWindow()->DC.Indent.x; + ImGui::GetContentRegionAvail().x + UI::GetCurrentWindow()->DC.Indent.x; UI::SameLine(widthAvailable - 50.f); UI::PushStyleCompact(); - if (UI::Button(ICON_FA_PLUS "##AddItem", v2(16.f, 18.f))) + if (UI::Button(ICON_FA_PLUS "##AddItem", p::v2(16.f, 18.f))) { - property.AddItem(instance, nullptr); + ops->AddItem(instance, nullptr); } UI::SameLine(); - if (UI::Button(ICON_FA_TRASH_ALT "##Empty", v2(16.f, 18.f))) + if (UI::Button(ICON_FA_TRASH_ALT "##Empty", p::v2(16.f, 18.f))) { - property.Clear(instance); + ops->Clear(instance); } UI::PopStyleCompact(); } - void DrawArrayItemButtons(const ArrayProperty& property, void* instance, i32 index) + void DrawArrayItemButtons(const ValueHandle& handle) { const float widthAvailable = - ImGui::GetContentRegionAvailWidth() + UI::GetCurrentWindow()->DC.Indent.x; + ImGui::GetContentRegionAvail().x + UI::GetCurrentWindow()->DC.Indent.x; UI::SameLine(widthAvailable - 50.f); UI::PushStyleCompact(); - static String label; + static p::String label; label.clear(); - Strings::FormatTo(label, ICON_FA_TIMES "##removeItem_{}", index); - if (UI::Button(label.c_str(), v2(18.f, 18.f))) + p::Strings::FormatTo(label, ICON_FA_TIMES "##removeItem_{}", handle.GetIndex()); + if (UI::Button(label.c_str(), p::v2(18.f, 18.f))) { - property.RemoveItem(instance, index); + // handle.GetArrayProperty()->RemoveItem(handle.GetContainerPtr(), handle.GetIndex()); } UI::PopStyleCompact(); } - void InspectArrayProperty(const ArrayProperty& property, void* instance) - { - const i32 size = property.GetSize(instance); - const bool open = BeginInspectHeader(property.GetDisplayName().data(), size <= 0); - UI::TableSetColumnIndex(1); - DrawArrayValue(open, property, instance); - if (open) - { - auto* type = property.GetType(); - static String label; - if (auto* structType = Cast(type)) - { - for (i32 i = 0; i < size; ++i) - { - label.clear(); - Strings::FormatTo(label, "{}", i); - const bool open = BeginInspectHeader(label); - if (open) - { - UI::Unindent(); - } - UI::TableSetColumnIndex(1); - DrawArrayItemButtons(property, instance, i); - if (open) - { - UI::Indent(); - InspectProperties(property.GetItem(instance, i), structType); - EndInspectHeader(); - } - } - } - else if (auto* custom = gCustomKeyValues.Find(type)) - { - for (i32 i = 0; i < size; ++i) - { - label.clear(); - Strings::FormatTo(label, "{}", i); - (*custom)(label, property.GetItem(instance, i), type); - DrawArrayItemButtons(property, instance, i); - } - } - else - { - for (i32 i = 0; i < size; ++i) - { - label.clear(); - Strings::FormatTo(label, "{}", i); - DrawKeyValue(label, property.GetItem(instance, i), type); - DrawArrayItemButtons(property, instance, i); - } - } - EndInspectHeader(); - } - } - - void InspectProperty(const PropertyHandle& handle) + void InspectProperty(const ValueHandle& handle) { - auto* type = handle.GetType(); - if (!type) + p::TypeId type = handle.GetType(); + if (!type.IsValid()) { return; } void* instance = handle.GetPtr(); UI::PushID(instance); - if (auto* arrayProperty = handle.GetArrayProperty()) + + p::String displayName; + handle.GetDisplayName(displayName); + + bool isLeaf = false; + if (handle.IsArray()) { - InspectArrayProperty(*arrayProperty, instance); + // isLeaf = handle.GetArrayProperty()->GetSize(instance) > 0; } else if (auto* custom = gCustomKeyValues.Find(type)) { - (*custom)(handle.GetDisplayName(), instance, type); + (*custom)(displayName, instance, type); + if (handle.IsArrayItem()) + { + DrawArrayItemButtons(handle); + } + UI::PopID(); + return; } - else if (auto* structType = Cast(type)) + else if (p::HasTypeFlags(type, p::TF_Struct)) { - if (BeginInspectHeader(handle.GetDisplayName())) + isLeaf = !GetTypeProperties(type).IsEmpty(); + } + else + { + DrawKeyValue(displayName, instance, type); + if (handle.IsArrayItem()) { - InspectProperties(instance, structType); - EndInspectHeader(); + DrawArrayItemButtons(handle); } + UI::PopID(); + return; } - else + + bool bOpen = BeginCategory(displayName, isLeaf); + + if (handle.IsArray()) { - DrawKeyValue(handle.GetDisplayName(), instance, type); + // UI::TableSetColumnIndex(1); + // DrawArrayValue(*handle.GetArrayProperty(), instance); + } + + if (bOpen) + { + InspectChildrenProperties(handle); + EndCategory(); } UI::PopID(); } - void InspectProperties(void* container, DataType* type) + void InspectChildrenProperties(const ValueHandle& handle) { - if (!EnsureMsg(gCurrentInspector, + if (!P_EnsureMsg(gCurrentInspector, "Make sure to call Begin/EndInspector around reflection widgets.")) { return; } - UI::PushID(container); - - TArray properties; - type->GetProperties(properties); - for (auto* prop : properties) + const p::TypeId type = handle.GetType(); + if (!type.IsValid()) { - InspectProperty(PropertyHandle{*prop, container}); + return; } - UI::PopID(); + if (p::HasTypeFlags(type, p::TF_Struct)) + { + void* instance = handle.GetPtr(); + p::TView properties = p::GetTypeProperties(type); + for (const auto* prop : properties) + { + InspectProperty({instance, type, *prop}); + } + } + else if (handle.IsArray()) + { + // auto* arrayProperty = handle.GetArrayProperty(); + // void* instance = handle.GetPtr(); + // const i32 size = arrayProperty->GetSize(instance); + // for (i32 i = 0; i < size; ++i) + //{ + // InspectProperty({handle, i}); + // } + } } - bool BeginInspectHeader(StringView label, bool isLeaf) + bool BeginCategory(p::StringView name, bool isLeaf) { UI::TableNextRow(); UI::TableSetColumnIndex(0); UI::PushHeaderColor(UI::GetNeutralColor(1)); - UI::AlignTextToFramePadding(); const ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_AllowItemOverlap | (isLeaf ? ImGuiTreeNodeFlags_Leaf : 0); - const bool isOpen = UI::TreeNodeEx(label.data(), ImGuiTreeNodeFlags_AllowItemOverlap); + bool bOpen = UI::TreeNodeEx(name.data(), ImGuiTreeNodeFlags_AllowItemOverlap); UI::PopHeaderColor(); - return isOpen; + return bOpen; } - - void EndInspectHeader() + void EndCategory() { UI::TreePop(); } - bool BeginInspector(const char* label, v2 size) + bool BeginInspector(const char* label, p::v2 size) { - if (!EnsureMsg(!gCurrentInspector, + if (!P_EnsureMsg(!gCurrentInspector, "Called BeginInspector() twice without calling EndInspector() first.")) { return false; @@ -319,7 +301,7 @@ namespace rift::UI void EndInspector() { - if (!EnsureMsg(gCurrentInspector, "Called EndInspector() but no inspector was drawing.")) + if (!P_EnsureMsg(gCurrentInspector, "Called EndInspector() but no inspector was drawing.")) { return; } @@ -328,7 +310,7 @@ namespace rift::UI } - bool DrawColorKeyValue(StringView label, LinearColor& color, ImGuiColorEditFlags flags) + bool DrawColorKeyValue(p::StringView label, p::LinearColor& color, ImGuiColorEditFlags flags) { auto* data = reinterpret_cast(&color); // LinearColor* can be interpreted as float* @@ -342,45 +324,47 @@ namespace rift::UI void RegisterCoreKeyValueInspections() { - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { - DrawColorKeyValue(label, *reinterpret_cast(data), + UI::RegisterCustomInspection( + [](p::StringView label, void* data, p::TypeId type) { + DrawColorKeyValue(label, *reinterpret_cast(data), ImGuiColorEditFlags_Float | ImGuiColorEditFlags_AlphaPreviewHalf); }); - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { - auto* color = reinterpret_cast(data); - LinearColor lColor{*color}; + UI::RegisterCustomInspection( + [](p::StringView label, void* data, p::TypeId type) { + auto* color = reinterpret_cast(data); + p::LinearColor lColor{*color}; if (DrawColorKeyValue(label, lColor, ImGuiColorEditFlags_Float | ImGuiColorEditFlags_DisplayHSV | ImGuiColorEditFlags_AlphaPreviewHalf)) { - *color = HSVColor{lColor}; + *color = p::HSVColor{lColor}; } }); - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { - auto* color = reinterpret_cast(data); - LinearColor lColor{*color}; + UI::RegisterCustomInspection([](p::StringView label, void* data, p::TypeId type) { + auto* color = reinterpret_cast(data); + p::LinearColor lColor{*color}; if (DrawColorKeyValue(label, lColor, ImGuiColorEditFlags_Uint8 | ImGuiColorEditFlags_DisplayRGB | ImGuiColorEditFlags_AlphaPreviewHalf)) { - *color = Color{lColor}; + *color = p::Color{lColor}; } }); - UI::RegisterCustomInspection([](StringView label, void* data, Type* type) { - auto* path = reinterpret_cast(data); + UI::RegisterCustomInspection([](p::StringView label, void* data, p::TypeId type) { + auto* path = reinterpret_cast(data); UI::TableNextRow(); UI::TableSetColumnIndex(0); UI::AlignTextToFramePadding(); UI::Text(label); UI::TableSetColumnIndex(1); - UI::SetNextItemWidth(math::Min(300.f, UI::GetContentRegionAvail().x)); - String str = ToString(*path); + UI::SetNextItemWidth(p::Min(300.f, UI::GetContentRegionAvail().x)); + p::String str = p::ToString(*path); if (UI::InputText("##value", str)) { - *path = p::ToPath(str); + *path = p::ToSTDPath(str); } }); } diff --git a/Libs/UI/Src/Notify.cpp b/Libs/UI/Src/Notify.cpp index c3dac932..f6a7f64a 100644 --- a/Libs/UI/Src/Notify.cpp +++ b/Libs/UI/Src/Notify.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Notify.h" @@ -7,9 +7,8 @@ #include #include -#include -#include -#include +#include +#include #define NOTIFY_USE_SEPARATOR @@ -19,14 +18,14 @@ namespace rift::UI { struct Notification { - enum class Phase : u8 + enum class Phase : p::u8 { FadeIn, Wait, FadeOut, Expired }; - enum class Corner : u8 + enum class Corner : p::u8 { TopLeft, TopRight, @@ -36,12 +35,12 @@ namespace rift::UI Toast toast; - DateTime creationTime = DateTime::Now(); + p::DateTime creationTime = p::DateTime::Now(); static constexpr float opacity = 1.f; static constexpr float fadeInDuration = 0.1f; static constexpr float fadeOutDuration = 0.15f; - static constexpr v2 padding{20.f, 20.f}; + static constexpr p::v2 padding{20.f, 20.f}; static constexpr Corner corner = Corner::BottomRight; static constexpr float separationY = 10.f; // Padding between notifications static constexpr ImGuiWindowFlags flags = @@ -71,9 +70,9 @@ namespace rift::UI } } - Timespan GetElapsedTime() const + p::Timespan GetElapsedTime() const { - return DateTime::Now() - creationTime; + return p::DateTime::Now() - creationTime; } const char* GetIcon() const @@ -89,7 +88,7 @@ namespace rift::UI } } - Color GetColor() + p::Color GetColor() { switch (toast.type) { @@ -98,7 +97,7 @@ namespace rift::UI case ToastType::Error: return UI::errorColor; case ToastType::Info: return UI::infoColor; case ToastType::None: - default: return Color::White(); + default: return p::Color::White(); } } @@ -121,21 +120,23 @@ namespace rift::UI return 1.f * opacity; } - void GetPositionAndPivot(float height, v2& position, v2& pivot) + void GetPositionAndPivot(float height, p::v2& position, p::v2& pivot) { - v2 pad{padding.x, padding.y + height}; + p::v2 pad{padding.x, padding.y + height}; const ImGuiViewport* viewport = ImGui::GetMainViewport(); - v2 workPos = viewport->WorkPos; - v2 workSize = viewport->WorkSize; - position.x = (u8(corner) & 1) ? (workPos.x + workSize.x - pad.x) : (workPos.x + pad.x); - position.y = (u8(corner) & 2) ? (workPos.y + workSize.y - pad.y) : (workPos.y + pad.y); - pivot.x = (u8(corner) & 1) ? 1.0f : 0.0f; - pivot.y = (u8(corner) & 2) ? 1.0f : 0.0f; + p::v2 workPos = viewport->WorkPos; + p::v2 workSize = viewport->WorkSize; + position.x = + (p::u8(corner) & 1) ? (workPos.x + workSize.x - pad.x) : (workPos.x + pad.x); + position.y = + (p::u8(corner) & 2) ? (workPos.y + workSize.y - pad.y) : (workPos.y + pad.y); + pivot.x = (p::u8(corner) & 1) ? 1.0f : 0.0f; + pivot.y = (p::u8(corner) & 2) ? 1.0f : 0.0f; } }; - static TArray gNotifications; + static p::TArray gNotifications; void AddNotification(Toast toast) @@ -149,7 +150,7 @@ namespace rift::UI ImGui::PushStyleColor(ImGuiCol_WindowBg, UI::GetNeutralColor(0)); float height = 0.f; - for (i32 i = 0; i < gNotifications.Size(); ++i) + for (p::i32 i = 0; i < gNotifications.Size(); ++i) { auto& notification = gNotifications[i]; @@ -161,17 +162,17 @@ namespace rift::UI continue; } - const float opacity = notification.GetFadePercent(); - LinearColor textColor = notification.GetColor(); - textColor.a = opacity; + const float opacity = notification.GetFadePercent(); + p::LinearColor textColor = notification.GetColor(); + textColor.a = opacity; // ImGui::PushStyleColor(ImGuiCol_Text, textColor); ImGui::SetNextWindowBgAlpha(opacity); - v2 position, pivot; + p::v2 position, pivot; notification.GetPositionAndPivot(height, position, pivot); ImGui::SetNextWindowPos(position, ImGuiCond_Always, pivot); - String windowName = Strings::Format("##Notification_{}", i); + p::String windowName = p::Strings::Format("##Notification_{}", i); ImGui::Begin(windowName.c_str(), nullptr, Notification::flags); // Here we render the toast content @@ -179,7 +180,7 @@ namespace rift::UI // We want to support multi-line text, this will // wrap the text after 1/3 of the screen width - const v2 workSize = UI::GetMainViewport()->WorkSize; + const p::v2 workSize = UI::GetMainViewport()->WorkSize; ImGui::PushTextWrapPos(workSize.x / 3.f); bool wasTitleRendered = false; @@ -192,7 +193,7 @@ namespace rift::UI } // If a title is set - const String& title = notification.toast.title; + const p::String& title = notification.toast.title; if (!title.empty()) { // If a title and an icon is set, we want to render on same line @@ -207,7 +208,7 @@ namespace rift::UI // In case ANYTHING was rendered in the top, we want to add a small padding // so the text (or icon) looks centered vertically - const String& message = notification.toast.message; + const p::String& message = notification.toast.message; if (wasTitleRendered && !message.empty()) { ImGui::SetCursorPosY( diff --git a/Libs/UI/Src/Paths.cpp b/Libs/UI/Src/Paths.cpp index 679769f7..483c2c34 100644 --- a/Libs/UI/Src/Paths.cpp +++ b/Libs/UI/Src/Paths.cpp @@ -1,12 +1,15 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Paths.h" +#include + + namespace rift::Paths { - Path GetResourcesPath() + p::String GetResourcesPath() { - static p::Path relativeResourcesPath{"./Resources"}; - return GetBasePath() / relativeResourcesPath; + static p::StringView relativeResourcesPath{"Resources"}; + return p::JoinPaths(p::PlatformPaths::GetBasePath(), relativeResourcesPath); } }; // namespace rift::Paths diff --git a/Libs/UI/Src/Style.cpp b/Libs/UI/Src/Style.cpp index 9ae896fe..040556c1 100644 --- a/Libs/UI/Src/Style.cpp +++ b/Libs/UI/Src/Style.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Style.h" @@ -8,25 +8,24 @@ #include #include #include -#include +#include +#include #include -#include -#include +#include +#include +#include namespace rift::UI { - using namespace p; - - struct FontType { - TArray> sizes{}; + p::TArray> sizes{}; void Add(float size, ImFont* imFont) { if (sizes.Contains([size](const auto& font) { - return math::NearlyEqual(font.first, size); + return p::NearlyEqual(font.first, size); })) { p::Error( @@ -47,8 +46,8 @@ namespace rift::UI { return sizes.First().second; } - const TPair* foundFont = sizes.Find([desiredSize](const auto& font) { - return math::NearlyEqual(font.first, desiredSize); + const p::TPair* foundFont = sizes.Find([desiredSize](const auto& font) { + return p::NearlyEqual(font.first, desiredSize); }); return foundFont ? foundFont->second : nullptr; } @@ -56,29 +55,29 @@ namespace rift::UI struct FontDescriptor { - std::array()> modes{}; + std::array()> modes{}; FontType& operator[](UI::FontMode mode) { - return modes[u8(mode)]; + return modes[p::u8(mode)]; } const FontType& operator[](UI::FontMode mode) const { - return modes[u8(mode)]; + return modes[p::u8(mode)]; } }; - static TMap gFonts{}; + static p::TMap gFonts{}; - ImFont* AddFont(Path file, float size, const ImFontConfig* fontConfig = nullptr, + ImFont* AddFont(p::StringView file, float size, const ImFontConfig* fontConfig = nullptr, const ImWchar* glyphRanges = nullptr) { auto& io = ImGui::GetIO(); - return io.Fonts->AddFontFromFileTTF(ToString(file).data(), size, fontConfig, glyphRanges); + return io.Fonts->AddFontFromFileTTF(file.data(), size, fontConfig, glyphRanges); } - void AddTextFont(Tag name, UI::FontMode mode, float size, p::Path file) + void AddTextFont(p::Tag name, UI::FontMode mode, float size, p::StringView file) { FontDescriptor* font = gFonts.Find(name); if (!font) @@ -87,7 +86,7 @@ namespace rift::UI font = &gFonts[name]; } - ImFont* imFont = AddFont(ToString(file).data(), size); + ImFont* imFont = AddFont(file.data(), size); (*font)[mode].Add(size, imFont); // Add Font Awesome icons @@ -97,7 +96,8 @@ namespace rift::UI iconsConfig.PixelSnapH = true; iconsConfig.GlyphMinAdvanceX = 14.f; // use FONT_ICON_FILE_NAME_FAR if you want regular instead of solid - AddFont(file.parent_path() / FONT_ICON_FILE_NAME_FAS, 14.0f, &iconsConfig, iconsRanges); + p::String path = p::JoinPaths(p::GetParentPath(file), FONT_ICON_FILE_NAME_FAS); + AddFont(path, 14.0f, &iconsConfig, iconsRanges); } void LoadFonts() @@ -105,42 +105,50 @@ namespace rift::UI auto& io = ImGui::GetIO(); io.Fonts->AddFontDefault(); - auto resources = rift::Paths::GetResourcesPath() / "Editor"; + auto resources = p::JoinPaths(rift::Paths::GetResourcesPath(), "Editor"); // Work Sans - AddTextFont("WorkSans", UI::FontMode::Bold, 14.f, resources / "Fonts/WorkSans-Bold.ttf"); + AddTextFont("WorkSans", UI::FontMode::Bold, 14.f, + p::JoinPaths(resources, "Fonts/WorkSans-Bold.ttf")); AddTextFont("WorkSans", UI::FontMode::BoldItalic, 14.f, - resources / "Fonts/WorkSans-BoldItalic.ttf"); - AddTextFont( - "WorkSans", UI::FontMode::Italic, 14.f, resources / "Fonts/WorkSans-Italic.ttf"); - AddTextFont("WorkSans", UI::FontMode::Light, 14.f, resources / "Fonts/WorkSans-Light.ttf"); + p::JoinPaths(resources, "Fonts/WorkSans-BoldItalic.ttf")); + AddTextFont("WorkSans", UI::FontMode::Italic, 14.f, + p::JoinPaths(resources, "Fonts/WorkSans-Italic.ttf")); + AddTextFont("WorkSans", UI::FontMode::Light, 14.f, + p::JoinPaths(resources, "Fonts/WorkSans-Light.ttf")); AddTextFont("WorkSans", UI::FontMode::LightItalic, 14.f, - resources / "Fonts/WorkSans-LightItalic.ttf"); - AddTextFont( - "WorkSans", UI::FontMode::Regular, 14.f, resources / "Fonts/WorkSans-Regular.ttf"); - AddTextFont( - "WorkSans", UI::FontMode::Regular, 18.f, resources / "Fonts/WorkSans-Regular.ttf"); + p::JoinPaths(resources, "Fonts/WorkSans-LightItalic.ttf")); + AddTextFont("WorkSans", UI::FontMode::Regular, 14.f, + p::JoinPaths(resources, "Fonts/WorkSans-Regular.ttf")); + AddTextFont("WorkSans", UI::FontMode::Regular, 18.f, + p::JoinPaths(resources, "Fonts/WorkSans-Regular.ttf")); + AddTextFont("WorkSans", UI::FontMode::Regular, 24.f, + p::JoinPaths(resources, "Fonts/WorkSans-Regular.ttf")); // Karla - AddTextFont("Karla", UI::FontMode::Bold, 14.f, resources / "Fonts/Karla-Bold.ttf"); AddTextFont( - "Karla", UI::FontMode::BoldItalic, 14.f, resources / "Fonts/Karla-BoldItalic.ttf"); - AddTextFont("Karla", UI::FontMode::Italic, 14.f, resources / "Fonts/Karla-Italic.ttf"); - AddTextFont("Karla", UI::FontMode::Light, 14.f, resources / "Fonts/Karla-Light.ttf"); + "Karla", UI::FontMode::Bold, 14.f, p::JoinPaths(resources, "Fonts/Karla-Bold.ttf")); + AddTextFont("Karla", UI::FontMode::BoldItalic, 14.f, + p::JoinPaths(resources, "Fonts/Karla-BoldItalic.ttf")); AddTextFont( - "Karla", UI::FontMode::LightItalic, 14.f, resources / "Fonts/Karla-LightItalic.ttf"); - AddTextFont("Karla", UI::FontMode::Regular, 14.f, resources / "Fonts/Karla-Regular.ttf"); + "Karla", UI::FontMode::Italic, 14.f, p::JoinPaths(resources, "Fonts/Karla-Italic.ttf")); + AddTextFont( + "Karla", UI::FontMode::Light, 14.f, p::JoinPaths(resources, "Fonts/Karla-Light.ttf")); + AddTextFont("Karla", UI::FontMode::LightItalic, 14.f, + p::JoinPaths(resources, "Fonts/Karla-LightItalic.ttf")); + AddTextFont("Karla", UI::FontMode::Regular, 14.f, + p::JoinPaths(resources, "Fonts/Karla-Regular.ttf")); io.Fonts->Build(); } - ImFont* FindFont(Tag name, UI::FontMode mode, float size) + ImFont* FindFont(p::Tag name, UI::FontMode mode, float size) { const FontDescriptor* const font = gFonts.Find(name); return font ? (*font)[mode].Get(size) : nullptr; } - void SetDefaultFont(Tag name, UI::FontMode mode, float size) + void SetDefaultFont(p::Tag name, UI::FontMode mode, float size) { ImFont* font = FindFont(name, mode, size); if (!font && !name.IsNone()) @@ -150,13 +158,13 @@ namespace rift::UI ImGui::GetIO().FontDefault = font; } - void PushFont(Tag name, UI::FontMode mode, float size) + void PushFont(p::Tag name, UI::FontMode mode, float size) { ImFont* font = FindFont(name, mode, size); if (!font && !name.IsNone()) { p::Error("Tried to push inexistent font '{}' (mode: {}, size: {})", name, - GetEnumName(mode), size); + p::GetEnumName(mode), size); } ImGui::PushFont(font); } @@ -181,10 +189,10 @@ namespace rift::UI ImVec4* colors = style.Colors; - LinearColor titleColor = UI::GetNeutralColor(0); + p::LinearColor titleColor = UI::GetNeutralColor(0); colors[ImGuiCol_TitleBg] = titleColor.Shade(0.2f); colors[ImGuiCol_TitleBgActive] = titleColor; - colors[ImGuiCol_TitleBgCollapsed] = UI::Disabled(titleColor); + colors[ImGuiCol_TitleBgCollapsed] = UI::ToDisabled(titleColor); colors[ImGuiCol_WindowBg] = UI::GetNeutralColor(1); colors[ImGuiCol_Border] = UI::GetNeutralColor(0); @@ -194,17 +202,17 @@ namespace rift::UI colors[ImGuiCol_SliderGrab] = UI::GetNeutralColor(4); - LinearColor separatorColor = UI::GetNeutralColor(1); - colors[ImGuiCol_SeparatorHovered] = UI::Hovered(separatorColor); + p::LinearColor separatorColor = UI::GetNeutralColor(1); + colors[ImGuiCol_SeparatorHovered] = UI::ToHovered(separatorColor); colors[ImGuiCol_SeparatorActive] = separatorColor; - LinearColor resizeGripColor = UI::GetNeutralColor(1); + p::LinearColor resizeGripColor = UI::GetNeutralColor(1); colors[ImGuiCol_ResizeGrip] = resizeGripColor.Shade(0.3f); - colors[ImGuiCol_ResizeGripHovered] = UI::Hovered(resizeGripColor); + colors[ImGuiCol_ResizeGripHovered] = UI::ToHovered(resizeGripColor); colors[ImGuiCol_ResizeGripActive] = resizeGripColor; colors[ImGuiCol_DockingPreview] = UI::GetNeutralColor(2); - colors[ImGuiCol_DockingEmptyBg] = LinearColor::White().Shade(0.97f); + colors[ImGuiCol_DockingEmptyBg] = p::LinearColor::White().Shade(0.97f); colors[ImGuiCol_TextSelectedBg] = UI::primaryColor.Shade(0.1f); colors[ImGuiCol_NavHighlight] = UI::primaryColor; @@ -221,73 +229,11 @@ namespace rift::UI UI::PushButtonColor(UI::GetNeutralColor(3)); UI::PushFrameBgColor(UI::GetNeutralColor(2)); - UI::PushHeaderColor(); + UI::PushHeaderColor(UI::GetNeutralColor(2)); LoadFonts(); UI::SetDefaultFont("WorkSans"); } void PopGeneralStyle() {} - - // Make the UI compact because there are so many fields - void PushStyleCompact() - { - ImGuiStyle& style = ImGui::GetStyle(); - UI::PushStyleVar(ImGuiStyleVar_FramePadding, - ImVec2(style.FramePadding.x, (float)(int)(style.FramePadding.y * 0.60f))); - UI::PushStyleVar(ImGuiStyleVar_ItemSpacing, - ImVec2(style.ItemSpacing.x, (float)(int)(style.ItemSpacing.y * 0.60f))); - } - - void PopStyleCompact() - { - UI::PopStyleVar(2); - } - - void PushFrameBgColor(LinearColor color) - { - UI::PushStyleColor(ImGuiCol_FrameBg, color.Shade(0.3f)); - UI::PushStyleColor(ImGuiCol_FrameBgHovered, UI::Hovered(color)); - UI::PushStyleColor(ImGuiCol_FrameBgActive, color); - } - - void PopFrameBgColor() - { - UI::PopStyleColor(3); - } - - void PushButtonColor(LinearColor color) - { - UI::PushStyleColor(ImGuiCol_Button, color); - UI::PushStyleColor(ImGuiCol_ButtonHovered, UI::Hovered(color)); - UI::PushStyleColor(ImGuiCol_ButtonActive, color.Tint(0.1f)); - } - - void PopButtonColor() - { - UI::PopStyleColor(3); - } - - void PushHeaderColor(LinearColor color) - { - UI::PushStyleColor(ImGuiCol_Header, color); - UI::PushStyleColor(ImGuiCol_HeaderHovered, UI::Hovered(color)); - UI::PushStyleColor(ImGuiCol_HeaderActive, color.Tint(0.1f)); - } - - void PopHeaderColor() - { - UI::PopStyleColor(3); - } - - void PushTextColor(LinearColor color) - { - UI::PushStyleColor(ImGuiCol_Text, color); - UI::PushStyleColor(ImGuiCol_TextDisabled, color.Shade(0.15f)); - } - - void PopTextColor() - { - UI::PopStyleColor(2); - } } // namespace rift::UI diff --git a/Libs/UI/Src/UIImgui.cpp b/Libs/UI/Src/UIImgui.cpp new file mode 100644 index 00000000..2ff0ecca --- /dev/null +++ b/Libs/UI/Src/UIImgui.cpp @@ -0,0 +1,6 @@ +// Copyright 2015-2024 Piperift - All rights reserved + +#include "UI/UIImgui.h" + +#define P_IMGUI_IMPLEMENTATION +#include diff --git a/Libs/UI/Src/Widgets.cpp b/Libs/UI/Src/Widgets.cpp index aa4cce28..49b06353 100644 --- a/Libs/UI/Src/Widgets.cpp +++ b/Libs/UI/Src/Widgets.cpp @@ -1,17 +1,16 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Widgets.h" #include -#include -#include +#include namespace rift::UI { - void AnimatedSprite::SetAnimation(u32 id) + void AnimatedSprite::SetAnimation(p::u32 id) { - currentFrame = {0, math::Clamp(id, 0u, u32(numFrames.Size() - 1))}; + currentFrame = {0, p::Clamp(id, 0u, p::u32(numFrames.Size() - 1))}; currentFrameRemainingTime = rate; } @@ -22,7 +21,7 @@ namespace rift::UI if (currentFrameRemainingTime <= 0.f) { ++currentFrame.x; - if (currentFrame.x >= numFrames[i32(currentFrame.y)]) + if (currentFrame.x >= numFrames[p::i32(currentFrame.y)]) { currentFrame.x = 0; } @@ -30,16 +29,16 @@ namespace rift::UI } } - v2 AnimatedSprite::GetUV() const + p::v2 AnimatedSprite::GetUV() const { return size * currentFrame; } - bool SpriteButton(AnimatedSprite& sprite, i32 framePadding, const LinearColor& bgColor, - const LinearColor& tintColor) + bool SpriteButton(AnimatedSprite& sprite, p::i32 framePadding, const p::LinearColor& bgColor, + const p::LinearColor& tintColor) { - const v2 uv = sprite.GetUV(); + const p::v2 uv = sprite.GetUV(); return UI::ImageButton( sprite.textureId, sprite.size, uv, uv + sprite.size, framePadding, bgColor, tintColor); } @@ -47,7 +46,7 @@ namespace rift::UI struct InputTextCallbackStringUserData { - String* str; + p::String* str; ImGuiInputTextCallback chainCallback; void* chainCallbackUserData; }; @@ -60,7 +59,7 @@ namespace rift::UI // Resize string callback // If for some reason we refuse the new length (BufTextLen) and/or capacity (BufSize) we // need to set them back to what we want. - String* str = userData->str; + p::String* str = userData->str; IM_ASSERT(data->Buf == str->c_str()); str->resize(data->BufTextLen); data->Buf = (char*)str->c_str(); @@ -75,7 +74,7 @@ namespace rift::UI } - bool InputText(const char* label, String& str, ImGuiInputTextFlags flags, + bool InputText(const char* label, p::String& str, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* userData) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); @@ -89,7 +88,7 @@ namespace rift::UI label, (char*)str.c_str(), str.capacity() + 1, flags, InputTextCallback, &cbUserData); } - bool InputTextMultiline(const char* label, String& str, const ImVec2& size, + bool InputTextMultiline(const char* label, p::String& str, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* userData) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); @@ -103,7 +102,7 @@ namespace rift::UI InputTextCallback, &cbUserData); } - bool InputTextWithHint(const char* label, const char* hint, String& str, + bool InputTextWithHint(const char* label, const char* hint, p::String& str, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, void* userData) { IM_ASSERT((flags & ImGuiInputTextFlags_CallbackResize) == 0); @@ -117,7 +116,7 @@ namespace rift::UI InputTextCallback, &cbUserData); } - ImRect GetWorkRect(v2 desiredSize, bool addhalfItemSpacing, v2 extent) + ImRect GetWorkRect(p::v2 desiredSize, bool addhalfItemSpacing, p::v2 extent) { auto& style = ImGui::GetStyle(); auto* window = UI::GetCurrentWindow(); @@ -127,7 +126,7 @@ namespace rift::UI const float minX = window->ParentWorkRect.Min.x; const float maxX = window->ParentWorkRect.Max.x; - const ImVec2 size{math::Max(desiredSize.x, maxX - minX), desiredSize.y}; + const ImVec2 size{p::Max(desiredSize.x, maxX - minX), desiredSize.y}; ImRect bb{minX, pos.y, minX + size.x, pos.y + size.y}; if (addhalfItemSpacing) @@ -150,13 +149,13 @@ namespace rift::UI static ImGuiID gPendingEditingId = 0; - bool MutableText(StringView label, String& text, ImGuiInputTextFlags flags) + bool MutableText(p::StringView label, p::String& text, ImGuiInputTextFlags flags) { const ImGuiID id = UI::GetID(label); const bool isEditing = UI::GetActiveID() == id; if (!isEditing) // Is editing { - UI::PushStyleColor(ImGuiCol_FrameBg, LinearColor::Transparent()); + UI::PushStyleColor(ImGuiCol_FrameBg, p::LinearColor::Transparent()); } const bool valueChanged = UI::InputText(label.data(), text, flags); @@ -167,7 +166,7 @@ namespace rift::UI return valueChanged; } - void HelpTooltip(StringView text, float delay) + void HelpTooltip(p::StringView text, float delay) { static ImGuiID currentHelpItemId = 0; @@ -177,8 +176,8 @@ namespace rift::UI bool show = true; if (delay > 0.f) { - static DateTime hoverStartTime; - const DateTime now = DateTime::Now(); + static p::DateTime hoverStartTime; + const p::DateTime now = p::DateTime::Now(); if (itemId != currentHelpItemId) { // Reset help tooltip countdown @@ -190,12 +189,12 @@ namespace rift::UI if (show) { - UI::PushStyleVar(ImGuiStyleVar_WindowPadding, v2{4.f, 3.f}); + UI::PushStyleVar(ImGuiStyleVar_WindowPadding, p::v2{4.f, 3.f}); ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); - static String finalText; + static p::String finalText; finalText.clear(); - Strings::FormatTo(finalText, "{} {}", ICON_FA_QUESTION_CIRCLE, text); + p::Strings::FormatTo(finalText, "{} {}", ICON_FA_QUESTION_CIRCLE, text); UI::AlignTextToFramePadding(); ImGui::TextUnformatted(finalText.c_str()); ImGui::PopTextWrapPos(); @@ -208,9 +207,60 @@ namespace rift::UI currentHelpItemId = 0; } } - void HelpMarker(StringView text) + void HelpMarker(p::StringView text) { ImGui::TextDisabled(ICON_FA_QUESTION_CIRCLE); HelpTooltip(text, 0.f); } + + bool DrawFilterWithHint( + ImGuiTextFilter& filter, const char* label, const char* hint, float width) + { + if (width != 0.0f) + ImGui::SetNextItemWidth(width); + bool value_changed = + ImGui::InputTextWithHint(label, hint, filter.InputBuf, IM_ARRAYSIZE(filter.InputBuf)); + if (value_changed) + filter.Build(); + return value_changed; + } + + bool CollapsingHeaderWithButton(p::StringView label, ImGuiTreeNodeFlags flags, + bool& buttonClicked, p::StringView buttonLabel, p::v2 buttonSize) + { + ImGuiWindow* window = ImGui::GetCurrentWindow(); + if (window->SkipItems) + return false; + + ImGuiID id = window->GetID(label.data()); + flags |= ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_AllowOverlap + | ImGuiTreeNodeFlags_ClipLabelForTrailingButton; + bool isOpen = ImGui::TreeNodeBehavior(id, flags, label.data()); + + + // Create a small overlapping close button + // FIXME: We can evolve this into user accessible helpers to add extra buttons on title + // bars, headers, etc. + // FIXME: CloseButton can overlap into text, need find a way to clip the text somehow. + ImGuiContext& g = *GImGui; + ImGuiLastItemData last_item_backup = g.LastItemData; + UI::PushID(id); + const float widthAvailable = + ImGui::GetContentRegionAvail().x + UI::GetCurrentWindow()->DC.Indent.x; + ImGui::SameLine(widthAvailable - 25.f); + UI::PushStyleVar(ImGuiStyleVar_FrameRounding, 2.f); + UI::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.5f, 0.5f)); + float backup_padding_y = g.Style.FramePadding.y; + g.Style.FramePadding.y = 0.0f; + if (ImGui::ButtonEx(buttonLabel.data(), buttonSize, ImGuiButtonFlags_AlignTextBaseLine)) + { + buttonClicked = true; + } + g.Style.FramePadding.y = backup_padding_y; + UI::PopStyleVar(2); + UI::PopID(); + g.LastItemData = last_item_backup; + + return isOpen; + } } // namespace rift::UI diff --git a/Libs/UI/Src/Window.cpp b/Libs/UI/Src/Window.cpp index e1b6864c..c3c5032b 100644 --- a/Libs/UI/Src/Window.cpp +++ b/Libs/UI/Src/Window.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "UI/Window.h" @@ -16,20 +16,22 @@ // Include glfw3.h after our OpenGL definitions #include #include -#include -#include +#include +#include +#include -namespace rift::UI -{ - using namespace p::math; +#define STB_IMAGE_IMPLEMENTATION +#include +namespace rift::UI +{ static GLFWwindow* gWindow = nullptr; void OnGl3WError(int error, const char* description) { - p::Error("Glfw Error {}: {}", error, description); + p::Error("Glfw Error {}: {}", error, p::StringView{description}); } bool Init() @@ -95,6 +97,8 @@ namespace rift::UI ImGui_ImplGlfw_InitForOpenGL(gWindow, true); ImGui_ImplOpenGL3_Init(glslVersion); + SetWindowIcon(); + RegisterCoreKeyValueInspections(); return true; } @@ -117,7 +121,6 @@ namespace rift::UI void PreFrame() { - ZoneScopedN("PreFrame"); glfwPollEvents(); ImGui_ImplOpenGL3_NewFrame(); @@ -127,14 +130,12 @@ namespace rift::UI void Render() { - ZoneScopedC(0xA245D1); - ImGui::Render(); - i32 displayW, displayH; + p::i32 displayW, displayH; glfwGetFramebufferSize(gWindow, &displayW, &displayH); glViewport(0, 0, displayW, displayH); - static constexpr LinearColor clearColor{0.1f, 0.1f, 0.1f, 1.00f}; + static constexpr p::LinearColor clearColor{0.1f, 0.1f, 0.1f, 1.00f}; glClearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); @@ -168,4 +169,31 @@ namespace rift::UI { return gWindow; } + + void SetWindowIcon() + { + p::String icon64Path = + p::JoinPaths(p::PlatformPaths::GetBasePath(), "Resources/Editor/Icons/Logo_64.png"); + p::String icon128Path = + p::JoinPaths(p::PlatformPaths::GetBasePath(), "Resources/Editor/Icons/Logo_128.png"); + p::String icon256Path = + p::JoinPaths(p::PlatformPaths::GetBasePath(), "Resources/Editor/Icons/Logo_256.png"); + GLFWimage images[3]; + images[0].pixels = + stbi_load(icon64Path.c_str(), &images[0].width, &images[0].height, nullptr, 0); + images[1].pixels = + stbi_load(icon128Path.c_str(), &images[1].width, &images[1].height, nullptr, 0); + images[2].pixels = + stbi_load(icon256Path.c_str(), &images[2].width, &images[2].height, nullptr, 0); + if (!images[0].pixels || !images[1].pixels || !images[2].pixels) + { + p::Error("Window icon couldn't be loaded"); + return; + } + glfwSetWindowIcon(gWindow, 3, images); + + stbi_image_free(images[0].pixels); + stbi_image_free(images[1].pixels); + stbi_image_free(images[2].pixels); + } } // namespace rift::UI diff --git a/Libs/Views/Graph/CMakeLists.txt b/Libs/Views/Graph/CMakeLists.txt index 81ae9962..782c3678 100644 --- a/Libs/Views/Graph/CMakeLists.txt +++ b/Libs/Views/Graph/CMakeLists.txt @@ -1,9 +1,9 @@ # Copyright 2015-2023 Piperift - All rights reserved -add_library(RiftViewGraph STATIC) -rift_compiler_module(RiftViewGraph) -target_link_libraries(RiftViewGraph PUBLIC RiftAST) +add_library(RiftViewGraphLib STATIC) +rift_compiler_module(RiftViewGraphLib) +target_link_libraries(RiftViewGraphLib PUBLIC RiftASTLib) -add_library(RiftViewGraphEditor STATIC) -rift_editor_module(RiftViewGraphEditor) -target_link_libraries(RiftViewGraphEditor PUBLIC RiftEditor RiftViewGraph) +add_library(RiftViewGraphEditorLib STATIC) +rift_editor_module(RiftViewGraphEditorLib) +target_link_libraries(RiftViewGraphEditorLib PUBLIC RiftEditorLib RiftViewGraphLib) diff --git a/Libs/Views/Graph/Compiler/Include/GraphViewModule.h b/Libs/Views/Graph/Compiler/Include/GraphViewModule.h index 20e27bc6..4ec60cbf 100644 --- a/Libs/Views/Graph/Compiler/Include/GraphViewModule.h +++ b/Libs/Views/Graph/Compiler/Include/GraphViewModule.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -9,12 +9,13 @@ #include - namespace rift { class GraphViewModule : public Module { - CLASS(GraphViewModule, Module) + public: + using Super = Module; + P_CLASS(GraphViewModule) public: void Load() override; diff --git a/Libs/Views/Graph/Compiler/Src/GraphViewModule.cpp b/Libs/Views/Graph/Compiler/Src/GraphViewModule.cpp index d65e5ea2..cf03f24e 100644 --- a/Libs/Views/Graph/Compiler/Src/GraphViewModule.cpp +++ b/Libs/Views/Graph/Compiler/Src/GraphViewModule.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "GraphViewModule.h" diff --git a/Libs/Views/Graph/Editor/Include/GraphViewEditorModule.h b/Libs/Views/Graph/Editor/Include/GraphViewEditorModule.h index 9047608b..d4c4bfdf 100644 --- a/Libs/Views/Graph/Editor/Include/GraphViewEditorModule.h +++ b/Libs/Views/Graph/Editor/Include/GraphViewEditorModule.h @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #pragma once @@ -9,6 +9,8 @@ namespace rift { class GraphViewEditorModule : public Module { - CLASS(GraphViewEditorModule, Module) + public: + using Super = Module; + P_CLASS(GraphViewEditorModule) }; } // namespace rift diff --git a/Libs/Views/Graph/Editor/Src/GraphViewEditorModule.cpp b/Libs/Views/Graph/Editor/Src/GraphViewEditorModule.cpp index 304c6af9..81fdf709 100644 --- a/Libs/Views/Graph/Editor/Src/GraphViewEditorModule.cpp +++ b/Libs/Views/Graph/Editor/Src/GraphViewEditorModule.cpp @@ -1,3 +1,3 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include "GraphViewEditorModule.h" diff --git a/Tests/AST/Expressions.spec.cpp b/Tests/AST/Expressions.spec.cpp index 668cb109..4fd1132a 100644 --- a/Tests/AST/Expressions.spec.cpp +++ b/Tests/AST/Expressions.spec.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include #include @@ -14,21 +14,21 @@ using namespace rift; go_bandit([]() { describe("AST.Expressions", []() { it("Initializes inputs & outputs correctly", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id id = AST::AddBinaryOperator({ast, AST::NoId}, AST::BinaryOperatorType::Div); - AssertThat(ast.Has(id), Equals(true)); - AssertThat(ast.Has(id), Equals(true)); - AssertThat(ast.Get(id).linkedOutputs.Size(), Equals(2)); - AssertThat(ast.Get(id).linkedOutputs.Size(), - Equals(ast.Get(id).pinIds.Size())); + ast::Id id = ast::AddBinaryOperator({ast, ast::NoId}, ast::BinaryOperatorType::Div); + AssertThat(ast.Has(id), Equals(true)); + AssertThat(ast.Has(id), Equals(true)); + AssertThat(ast.Get(id).linkedOutputs.Size(), Equals(2)); + AssertThat(ast.Get(id).linkedOutputs.Size(), + Equals(ast.Get(id).pinIds.Size())); - AST::Id id2 = AST::AddUnaryOperator({ast, AST::NoId}, AST::UnaryOperatorType::Not); - AssertThat(ast.Has(id2), Equals(true)); - AssertThat(ast.Has(id2), Equals(true)); - AssertThat(ast.Get(id2).linkedOutputs.Size(), Equals(1)); - AssertThat(ast.Get(id2).linkedOutputs.Size(), - Equals(ast.Get(id2).pinIds.Size())); + ast::Id id2 = ast::AddUnaryOperator({ast, ast::NoId}, ast::UnaryOperatorType::Not); + AssertThat(ast.Has(id2), Equals(true)); + AssertThat(ast.Has(id2), Equals(true)); + AssertThat(ast.Get(id2).linkedOutputs.Size(), Equals(1)); + AssertThat(ast.Get(id2).linkedOutputs.Size(), + Equals(ast.Get(id2).pinIds.Size())); }); }); }); diff --git a/Tests/AST/Namespaces.spec.cpp b/Tests/AST/Namespaces.spec.cpp index fe973c53..0cae17d4 100644 --- a/Tests/AST/Namespaces.spec.cpp +++ b/Tests/AST/Namespaces.spec.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include #include @@ -9,68 +9,66 @@ #include - using namespace snowhouse; using namespace bandit; using namespace rift; -using namespace p::core; go_bandit([]() { describe("AST.Namespaces", []() { it("Can get namespaces", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id functionId = AST::AddFunction({ast, AST::NoId}, "TestFunction"); + ast::Id functionId = ast::AddFunction({ast, ast::NoId}, "TestFunction"); AssertThat( - AST::GetNamespace(ast, functionId).ToString().c_str(), Equals("@TestFunction")); - AssertThat(AST::GetParentNamespace(ast, functionId).ToString().c_str(), Equals("")); + ast::GetNamespace(ast, functionId).ToString().c_str(), Equals("@TestFunction")); + AssertThat(ast::GetParentNamespace(ast, functionId).ToString().c_str(), Equals("")); - AST::Id classBId = AST::CreateType(ast, ASTModule::classType, "TestClass"); - AST::Id functionBId = AST::AddFunction({ast, classBId}, "TestFunction"); - AssertThat(AST::GetNamespace(ast, functionBId).ToString().c_str(), + ast::Id classBId = ast::CreateType(ast, ASTModule::classType, "TestClass"); + ast::Id functionBId = ast::AddFunction({ast, classBId}, "TestFunction"); + AssertThat(ast::GetNamespace(ast, functionBId).ToString().c_str(), Equals("@TestClass.TestFunction")); AssertThat( - AST::GetParentNamespace(ast, functionBId).ToString().c_str(), Equals("@TestClass")); - - AST::Id parentC = ast.Create(); - ast.Add(parentC); - ast.Add(parentC, AST::CNamespace{"SomeScope"}); - AST::Id classCId = AST::CreateType(ast, ASTModule::classType, "TestClass"); - p::Attach(ast, parentC, classCId); - AST::Id functionCId = AST::AddFunction({ast, classCId}, "TestFunction"); - AssertThat(AST::GetNamespace(ast, functionCId).ToString().c_str(), + ast::GetParentNamespace(ast, functionBId).ToString().c_str(), Equals("@TestClass")); + + ast::Id parentC = ast.Create(); + ast.Add(parentC); + ast.Add(parentC, ast::CNamespace{"SomeScope"}); + ast::Id classCId = ast::CreateType(ast, ASTModule::classType, "TestClass"); + p::AttachId(ast, parentC, classCId); + ast::Id functionCId = ast::AddFunction({ast, classCId}, "TestFunction"); + AssertThat(ast::GetNamespace(ast, functionCId).ToString().c_str(), Equals("@SomeScope.TestClass.TestFunction")); - AssertThat(AST::GetParentNamespace(ast, functionCId).ToString().c_str(), + AssertThat(ast::GetParentNamespace(ast, functionCId).ToString().c_str(), Equals("@SomeScope.TestClass")); }); it("Can get local namespaces", [&]() { - AST::Tree ast; - - AST::Id parent = ast.Create(); - ast.Add(parent); - ast.Add(parent, AST::CNamespace{"SomeModule"}); - AST::Id classId = AST::CreateType(ast, ASTModule::classType, "TestClass"); - p::Attach(ast, parent, classId); - AST::Id functionId = AST::AddFunction({ast, classId}, "TestFunction"); - p::String ns = AST::GetNamespace(ast, functionId).ToString(true); + ast::Tree ast; + + ast::Id parent = ast.Create(); + ast.Add(parent); + ast.Add(parent, ast::CNamespace{"SomeModule"}); + ast::Id classId = ast::CreateType(ast, ASTModule::classType, "TestClass"); + p::AttachId(ast, parent, classId); + ast::Id functionId = ast::AddFunction({ast, classId}, "TestFunction"); + p::String ns = ast::GetNamespace(ast, functionId).ToString(true); AssertThat(ns.c_str(), Equals("TestClass.TestFunction")); }); it("Can initialize", [&]() { - AST::Namespace ns0{}; + ast::Namespace ns0{}; AssertThat(ns0.scopes[0].IsNone(), Equals(true)); AssertThat(ns0.Size(), Equals(0)); AssertThat(ns0.IsEmpty(), Equals(true)); - AST::Namespace ns1{"A"}; + ast::Namespace ns1{"A"}; AssertThat(ns1.scopes[0].AsString().data(), Equals("A")); AssertThat(ns1.scopes[1].IsNone(), Equals(true)); AssertThat(ns1.Size(), Equals(1)); AssertThat(ns1.IsEmpty(), Equals(false)); - AST::Namespace ns2{"A", "B"}; + ast::Namespace ns2{"A", "B"}; AssertThat(ns2.scopes[0].AsString().data(), Equals("A")); AssertThat(ns2.scopes[1].AsString().data(), Equals("B")); AssertThat(ns2.scopes[2].IsNone(), Equals(true)); @@ -79,19 +77,19 @@ go_bandit([]() { }); it("Can iterate", [&]() { - AST::Namespace ns0{}; + ast::Namespace ns0{}; for (const Tag& name : ns0) { Assert(); } - AST::Namespace ns1{"C"}; + ast::Namespace ns1{"C"}; for (const Tag& name : ns1) { AssertThat(name.AsString().data(), Equals("C")); } - AST::Namespace ns2{"A", "B"}; + ast::Namespace ns2{"A", "B"}; i32 i = 0; for (const Tag& name : ns2) { @@ -101,29 +99,29 @@ go_bandit([]() { }); it("Can find id from namespace", [&]() { - AST::Tree ast; - AST::Id parent = ast.Create(); - ast.Add(parent); - ast.Add(parent, AST::CNamespace{"A"}); + ast::Tree ast; + ast::Id parent = ast.Create(); + ast.Add(parent); + ast.Add(parent, ast::CNamespace{"A"}); - AST::Id classId = AST::CreateType(ast, ASTModule::classType, "B"); - p::Attach(ast, parent, classId); + ast::Id classId = ast::CreateType(ast, ASTModule::classType, "B"); + p::AttachId(ast, parent, classId); - AST::Id class2Id = AST::CreateType(ast, ASTModule::classType, "B2"); - p::Attach(ast, parent, class2Id); + ast::Id class2Id = ast::CreateType(ast, ASTModule::classType, "B2"); + p::AttachId(ast, parent, class2Id); - AST::Id functionId = AST::AddFunction({ast, classId}, "C"); - AST::Id function2Id = AST::AddFunction({ast, classId}, "C2"); + ast::Id functionId = ast::AddFunction({ast, classId}, "C"); + ast::Id function2Id = ast::AddFunction({ast, classId}, "C2"); - AssertThat(AST::FindIdFromNamespace(ast, {"A"}), Equals(parent)); - AssertThat(AST::FindIdFromNamespace(ast, {"A", "B"}), Equals(classId)); - AssertThat(AST::FindIdFromNamespace(ast, {"A", "B2"}), Equals(class2Id)); - AssertThat(AST::FindIdFromNamespace(ast, {"A", "B", "C"}), Equals(functionId)); - AssertThat(AST::FindIdFromNamespace(ast, {"A", "B", "C2"}), Equals(function2Id)); + AssertThat(ast::FindIdFromNamespace(ast, {"A"}), Equals(parent)); + AssertThat(ast::FindIdFromNamespace(ast, {"A", "B"}), Equals(classId)); + AssertThat(ast::FindIdFromNamespace(ast, {"A", "B2"}), Equals(class2Id)); + AssertThat(ast::FindIdFromNamespace(ast, {"A", "B", "C"}), Equals(functionId)); + AssertThat(ast::FindIdFromNamespace(ast, {"A", "B", "C2"}), Equals(function2Id)); - AssertThat(AST::FindIdFromNamespace(ast, {"N"}), Equals(AST::NoId)); - AssertThat(AST::FindIdFromNamespace(ast, {"A", "N"}), Equals(AST::NoId)); + AssertThat(ast::FindIdFromNamespace(ast, {"N"}), Equals(ast::NoId)); + AssertThat(ast::FindIdFromNamespace(ast, {"A", "N"}), Equals(ast::NoId)); }); }); }); diff --git a/Tests/AST/Statements.spec.cpp b/Tests/AST/Statements.spec.cpp index 9c7d8874..967ecafb 100644 --- a/Tests/AST/Statements.spec.cpp +++ b/Tests/AST/Statements.spec.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include #include @@ -14,77 +14,77 @@ using namespace rift; go_bandit([]() { describe("AST.Statements", []() { it("Initializes outputs correctly", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id functionId = AST::AddFunction({ast, AST::NoId}, "TestFunction"); - AssertThat(ast.Has(functionId), Equals(true)); + ast::Id functionId = ast::AddFunction({ast, ast::NoId}, "TestFunction"); + AssertThat(ast.Has(functionId), Equals(true)); - AST::Id callId = AST::AddCall({ast, AST::NoId}, functionId); - AssertThat(ast.Has(callId), Equals(true)); + ast::Id callId = ast::AddCall({ast, ast::NoId}, functionId); + AssertThat(ast.Has(callId), Equals(true)); - AST::Id ifId = AST::AddIf({ast, AST::NoId}); - AssertThat(ast.Has(ifId), Equals(true)); - AssertThat(ast.Get(ifId).pinIds.Size(), Equals(2)); + ast::Id ifId = ast::AddIf({ast, ast::NoId}); + AssertThat(ast.Has(ifId), Equals(true)); + AssertThat(ast.Get(ifId).pinIds.Size(), Equals(2)); }); it("Initializes inputs correctly", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id functionId = AST::AddFunction({ast, AST::NoId}, "TestFunction"); - AssertThat(ast.Has(functionId), Equals(false)); + ast::Id functionId = ast::AddFunction({ast, ast::NoId}, "TestFunction"); + AssertThat(ast.Has(functionId), Equals(false)); - AST::Id callId = AST::AddCall({ast, AST::NoId}, functionId); - AssertThat(ast.Has(callId), Equals(true)); + ast::Id callId = ast::AddCall({ast, ast::NoId}, functionId); + AssertThat(ast.Has(callId), Equals(true)); - AST::Id ifId = AST::AddIf({ast, AST::NoId}); - AssertThat(ast.Has(ifId), Equals(true)); + ast::Id ifId = ast::AddIf({ast, ast::NoId}); + AssertThat(ast.Has(ifId), Equals(true)); }); it("Can connect with single output", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id functionId = AST::AddFunction({ast, AST::NoId}, "TestFunction"); - AST::Id callId = AST::AddCall({ast, AST::NoId}, functionId); - AST::Id ifId = AST::AddIf({ast, AST::NoId}); + ast::Id functionId = ast::AddFunction({ast, ast::NoId}, "TestFunction"); + ast::Id callId = ast::AddCall({ast, ast::NoId}, functionId); + ast::Id ifId = ast::AddIf({ast, ast::NoId}); - AssertThat(AST::TryConnectStmt(ast, functionId, callId), Equals(true)); + AssertThat(ast::TryConnectStmt(ast, functionId, callId), Equals(true)); // Can't connect to self - AssertThat(AST::TryConnectStmt(ast, functionId, functionId), Equals(false)); + AssertThat(ast::TryConnectStmt(ast, functionId, functionId), Equals(false)); // Can't connect in loops - AssertThat(AST::TryConnectStmt(ast, callId, ifId), Equals(true)); - AssertThat(AST::TryConnectStmt(ast, ifId, callId), Equals(false)); + AssertThat(ast::TryConnectStmt(ast, callId, ifId), Equals(true)); + AssertThat(ast::TryConnectStmt(ast, ifId, callId), Equals(false)); // Can replace a connection - AssertThat(AST::TryConnectStmt(ast, functionId, ifId), Equals(true)); + AssertThat(ast::TryConnectStmt(ast, functionId, ifId), Equals(true)); }); it("Can connect with multiple outputs", [&]() { - AST::Tree ast; + ast::Tree ast; - AST::Id functionId = AST::AddFunction({ast, AST::NoId}, "TestFunction"); + ast::Id functionId = ast::AddFunction({ast, ast::NoId}, "TestFunction"); - AST::Id ifId = AST::AddIf({ast, AST::NoId}); - AST::Id call1Id = AST::AddCall({ast, AST::NoId}, functionId); - AST::Id call2Id = AST::AddCall({ast, AST::NoId}, functionId); + ast::Id ifId = ast::AddIf({ast, ast::NoId}); + ast::Id call1Id = ast::AddCall({ast, ast::NoId}, functionId); + ast::Id call2Id = ast::AddCall({ast, ast::NoId}, functionId); AssertThat( - AST::TryConnectStmt(ast, ast.Get(ifId).pinIds[0], call2Id), + ast::TryConnectStmt(ast, ast.Get(ifId).pinIds[0], call2Id), Equals(true)); - AssertThat(ast.Get(ifId).linkInputNodes[0], Equals(call2Id)); + AssertThat(ast.Get(ifId).linkInputNodes[0], Equals(call2Id)); // Can replace a connection AssertThat( - AST::TryConnectStmt(ast, ast.Get(ifId).pinIds[0], call1Id), + ast::TryConnectStmt(ast, ast.Get(ifId).pinIds[0], call1Id), Equals(true)); - AssertThat(ast.Get(ifId).linkInputNodes[0], Equals(call1Id)); + AssertThat(ast.Get(ifId).linkInputNodes[0], Equals(call1Id)); // Can connect to a different pin AssertThat( - AST::TryConnectStmt(ast, ast.Get(ifId).pinIds[1], call2Id), + ast::TryConnectStmt(ast, ast.Get(ifId).pinIds[1], call2Id), Equals(true)); - AssertThat(ast.Get(ifId).linkInputNodes[1], Equals(call2Id)); + AssertThat(ast.Get(ifId).linkInputNodes[1], Equals(call2Id)); }); }); }); diff --git a/Tests/CMakeLists.txt b/Tests/CMakeLists.txt index 84c8b53b..70dc30a1 100644 --- a/Tests/CMakeLists.txt +++ b/Tests/CMakeLists.txt @@ -5,6 +5,8 @@ add_executable(RiftTests ${TESTS_SOURCE_FILES}) rift_module(RiftTests) pipe_target_shared_output_directory(RiftTests) target_include_directories(RiftTests PUBLIC .) -target_link_libraries(RiftTests PUBLIC RiftAST Bandit) +target_link_libraries(RiftTests PUBLIC RiftASTLib Bandit) add_test(NAME RiftTests COMMAND $) + +set_icon(RiftTests Icon.ico) diff --git a/Tests/Icon.ico b/Tests/Icon.ico new file mode 100644 index 00000000..11b4a077 Binary files /dev/null and b/Tests/Icon.ico differ diff --git a/Tests/Project.spec.cpp b/Tests/Project.spec.cpp index df168573..e9e5b2a6 100644 --- a/Tests/Project.spec.cpp +++ b/Tests/Project.spec.cpp @@ -1,4 +1,4 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved #include #include @@ -6,6 +6,7 @@ #include #include #include +#include #include #include @@ -18,57 +19,57 @@ using namespace rift; using namespace p; using namespace std::chrono_literals; -String testProjectPath = p::JoinPaths(GetCurrentPath(), "TestProject"); +String testProjectPath = p::JoinPaths(PlatformPaths::GetCurrentPath(), "TestProject"); go_bandit([]() { describe("Project", []() { before_each([]() { - files::Delete(testProjectPath, true, false); + Delete(testProjectPath, true, false); - if (!files::ExistsAsFolder(testProjectPath)) + if (!ExistsAsFolder(testProjectPath)) { - files::CreateFolder(testProjectPath); + CreateFolder(testProjectPath); } }); after_each([]() { - files::Delete(testProjectPath); + Delete(testProjectPath); }); it("Can load empty descriptor", [&]() { - files::SaveStringFile(p::JoinPaths(testProjectPath, AST::moduleFilename), "{}"); + SaveStringFile(p::JoinPaths(testProjectPath, ast::moduleFilename), "{}"); - AST::Tree ast; - bool result = AST::OpenProject(ast, testProjectPath); + ast::Tree ast; + bool result = ast::OpenProject(ast, testProjectPath); AssertThat(result, Equals(true)); - AssertThat(AST::HasProject(ast), Equals(true)); + AssertThat(ast::HasProject(ast), Equals(true)); }); it("Project name equals the folder", [&]() { - files::SaveStringFile(p::JoinPaths(testProjectPath, AST::moduleFilename), "{}"); + SaveStringFile(p::JoinPaths(testProjectPath, ast::moduleFilename), "{}"); - AST::Tree ast; - bool result = AST::OpenProject(ast, testProjectPath); + ast::Tree ast; + bool result = ast::OpenProject(ast, testProjectPath); AssertThat(result, Equals(true)); - AssertThat(AST::HasProject(ast), Equals(true)); + AssertThat(ast::HasProject(ast), Equals(true)); - StringView projectName = AST::GetProjectName(ast).AsString(); + StringView projectName = ast::GetProjectName(ast).AsString(); AssertThat(projectName, Equals("TestProject")); }); // TODO: Fix module loading. They can't load from CFileRef pointing to the folder and not // the file it("Project name can be overriden", [&]() { - files::SaveStringFile( - p::JoinPaths(testProjectPath, AST::moduleFilename), "{\"name\": \"SomeProject\"}"); + SaveStringFile( + p::JoinPaths(testProjectPath, ast::moduleFilename), "{\"name\": \"SomeProject\"}"); - AST::Tree ast; - bool result = AST::OpenProject(ast, testProjectPath); + ast::Tree ast; + bool result = ast::OpenProject(ast, testProjectPath); AssertThat(result, Equals(true)); - AssertThat(AST::HasProject(ast), Equals(true)); + AssertThat(ast::HasProject(ast), Equals(true)); - StringView projectName = AST::GetProjectName(ast).AsString(); + StringView projectName = ast::GetProjectName(ast).AsString(); AssertThat(projectName, Equals("SomeProject")); }); }); diff --git a/Tests/main.cpp b/Tests/main.cpp index 9617fd27..23968e73 100644 --- a/Tests/main.cpp +++ b/Tests/main.cpp @@ -1,10 +1,10 @@ -// Copyright 2015-2023 Piperift - All rights reserved +// Copyright 2015-2024 Piperift - All rights reserved -#include +#include // Override as first include #include -#include +#include int main(int argc, char* argv[]) diff --git a/Tools/InitSubmodules.sh b/Tools/InitSubmodules.sh new file mode 100644 index 00000000..85080ca5 --- /dev/null +++ b/Tools/InitSubmodules.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +git submodule update --init --recursive diff --git a/Tools/Setup.sh b/Tools/Setup.sh index e2ab3455..d10f182a 100644 --- a/Tools/Setup.sh +++ b/Tools/Setup.sh @@ -10,4 +10,4 @@ sudo apt -y install libx11-dev xorg-dev xlibmesa-glu-dev #libglu1-mesa-devz sudo apt -y install gdb -sudo apt -y install cmake +sudo apt -y install cmake ninja-build diff --git a/Tools/SetupLLVM.py b/Tools/SetupLLVM.py deleted file mode 100644 index 0765dd25..00000000 --- a/Tools/SetupLLVM.py +++ /dev/null @@ -1,39 +0,0 @@ -import os -import subprocess -import sys -import argparse - - -def main(argv): - rift_llvm_version = 'v15.0.6' - - this_file_path = os.path.dirname(__file__) - rift_path = os.path.dirname(this_file_path) - - parser = argparse.ArgumentParser(description = "Setup Rift's LLVM toolchain", formatter_class=argparse.ArgumentDefaultsHelpFormatter) - args = parser.parse_args() - - rift_llvm_relpath = 'Extern/rift-llvm' - rift_llvm_path = os.path.join(rift_path, rift_llvm_relpath) - - if not os.path.exists(rift_llvm_path): - print('> Downloading rift-llvm') - subprocess.run('git clone -s --depth 1 --branch {} https://github.com/PipeRift/rift-llvm.git {}'.format(rift_llvm_version, rift_llvm_path), shell=True, check=True) - os.chdir(rift_llvm_path) - else: - print('> Updating rift-llvm') - os.chdir(rift_llvm_path) - os.system('git pull origin {}'.format(rift_llvm_version)) - - print('\n> Init LLVM') - os.system('python3 init.py') - - print('\n> Build LLVM') - os.system('python3 build.py --config Debug') - os.system('python3 build.py --config Release') - os.system('python3 build.py --config RelWithDebInfo') - os.system('python3 build.py --config MinSizeRel') - -if __name__ == "__main__": - main(sys.argv[1:]) - diff --git a/Tools/mir/b2m.exe b/Tools/mir/b2m.exe new file mode 100644 index 00000000..00a456ea Binary files /dev/null and b/Tools/mir/b2m.exe differ diff --git a/Tools/mir/c2m.exe b/Tools/mir/c2m.exe new file mode 100644 index 00000000..e4d9ad86 Binary files /dev/null and b/Tools/mir/c2m.exe differ diff --git a/Tools/mir/m2b.exe b/Tools/mir/m2b.exe new file mode 100644 index 00000000..8a4cf31a Binary files /dev/null and b/Tools/mir/m2b.exe differ diff --git a/Tools/mir/test/test.c b/Tools/mir/test/test.c new file mode 100644 index 00000000..4b09ba1f --- /dev/null +++ b/Tools/mir/test/test.c @@ -0,0 +1,38 @@ + +// Struct Declarations + +// Function Declarations + +// Struct Declarations +typedef struct TestStruct TestStruct; + +// Struct Declarations +typedef struct Welcome Welcome; +typedef struct TestClass TestClass; + +// Function Declarations +void Project_Main_Main(); +void Project_Welcome_Print(long long in1, long long in2); + +// Struct Definitions +struct TestStruct +{}; + +// Struct Definitions +struct Welcome +{}; +struct TestClass +{}; + +// Function Definitions +void Project_Main_Main() +{ + printf("hola"); +} +void Project_Welcome_Print(long long in1, long long in2) {} + +int main() +{ + Project_Main_Main(); + return 0; +} diff --git a/Tools/mir/test/test.mir b/Tools/mir/test/test.mir new file mode 100644 index 00000000..8d578ddd --- /dev/null +++ b/Tools/mir/test/test.mir @@ -0,0 +1,16 @@ +M0: module +proto0: proto i32, ... + import printf +main: func + local i64:u0_a, i64:I_0, i64:i0_q, i64:i0_nn, i64:i_1, i64:i_2 +# 0 args, 6 locals + uext8 I_0, 1 + mov u0_a, I_0 + mov i0_q, 4 + mov i0_nn, 2433 + adds i_2, i0_q, i0_nn + call proto0, printf, i_1, "%i\000", i_2 + ret + endfunc + export main + endmodule