### vcpkg Package Manager Installation for nanoflann Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/nanoflann/README.md Illustrates the steps to install nanoflann using the vcpkg package manager. This involves cloning vcpkg, bootstrapping, integrating, and then installing the nanoflann package. ```bash $ git clone https://github.com/Microsoft/vcpkg.git $ cd vcpkg $ ./bootstrap-vcpkg.sh $ ./vcpkg integrate install $ ./vcpkg install nanoflann ``` -------------------------------- ### Install nlohmann-json with vcpkg Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Use vcpkg, Microsoft's C++ package manager, to install the `nlohmann-json` package. Follow the instructions provided after installation for integration. ```bash vcpkg install nlohmann-json ``` -------------------------------- ### Install nlohmann-json with cget Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Install the nlohmann-json library using cget. Specify a version or add flags like `-DJSON_MultipleHeaders=ON` for specific configurations. ```bash cget install nlohmann/json cget install nlohmann/json@v3.1.0 cget install nlohmann/json -DJSON_MultipleHeaders=ON ``` -------------------------------- ### Install nlohmann-json with Homebrew Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Use Homebrew, a package manager for macOS, to install the nlohmann-json library. The `--HEAD` flag installs the latest development version. ```bash brew install nlohmann-json brew install nlohmann-json --HEAD ``` -------------------------------- ### Conan Package Manager Installation for nanoflann Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/nanoflann/README.md Shows the command to install nanoflann using the Conan package manager. This command fetches pre-built binaries or builds from source, simplifying dependency management. ```bash $ conan install --requires="nanoflann/[*]" --build=missing ``` -------------------------------- ### Install nlohmann-json with Spack Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Use Spack, a flexible package manager for high-performance computing, to install the `nlohmann-json` package. ```bash spack install nlohmann-json ``` -------------------------------- ### Arbitrary Type Conversion Setup (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Shows the basic structure for enabling custom type to JSON conversion by defining `to_json` and `from_json` functions within the type's namespace. ```cpp namespace ns { // a simple struct to model a person struct person { std::string name; std::string address; int age; }; } ns::person p = {"Ned Flanders", "744 Evergreen Terrace", 60}; // convert to JSON: copy each value into the JSON object json j; j["name"] = p.name; j["address"] = p.address; j["age"] = p.age; // ... // convert from JSON: copy each value from the JSON object ns::person p2 { j["name"].template get(), j["address"].template get(), j["age"].template get() }; ``` -------------------------------- ### Install nlohmann-json with wsjcpp Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Fetches the latest version of the nlohmann/json library using the wsjcpp package manager. The 'develop' branch is used by default, but specific tags or other branches can also be specified. ```shell wsjcpp install "https://github.com/nlohmann/json:develop" ``` -------------------------------- ### Install nlohmann-json with Buckaroo Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Add the nlohmann-json module to your project using Buckaroo, a package manager for C/C++. This command fetches and integrates the library. ```bash buckaroo add github.com/buckaroo-pm/nlohmann-json ``` -------------------------------- ### Get include flags with pkg-config Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Retrieves the necessary compiler flags for including the nlohmann_json library when using bare Makefiles. This command assumes the library has been installed system-wide and pkg-config is aware of its location. ```sh pkg-config nlohmann_json --cflags ``` -------------------------------- ### Integrate nlohmann-json with Meson Build System Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Integrate the nlohmann-json library as a subproject in Meson. Alternatively, use a wrap file from Meson WrapDB or install it system-wide via the provided `meson.build`. ```meson # Example meson.build snippet for subproject integration json_dep = dependency('nlohmann_json', fallback : ['nlohmann_json', 'nlohmann_json_dep']) ``` -------------------------------- ### Install nlohmann-json with MSYS2 Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Installs the nlohmann-json package on MSYS2 using pacman. Supports both 32-bit (i686) and 64-bit (x86_64) architectures. Issues with the package should be reported to the MINGW-packages repository. ```shell pacman -S mingw-w64-i686-nlohmann-json pacman -S mingw-w64-x86_64-nlohmann-json ``` -------------------------------- ### Install nlohmann-json with MacPorts Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Installs the nlohmann-json package on macOS using MacPorts. Requires administrator privileges via sudo. Further information is available on the MacPorts website. ```shell sudo port install nlohmann-json ``` -------------------------------- ### Add nlohmann.json package via NuGet Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Install the `nlohmann.json` NuGet package for your .NET project. Refer to the provided issue comment for detailed usage instructions. ```powershell Install-Package nlohmann.json -Version 3.11.1 # Replace with desired version ``` -------------------------------- ### Install nlohmann_json with conda Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Use conda, a cross-platform package and environment manager, to install the `nlohmann_json` package from the conda-forge channel. ```bash conda install -c conda-forge nlohmann_json ``` -------------------------------- ### Execute Unit Tests with CMake Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This snippet outlines the shell commands required to build and execute unit tests for the project using CMake. It includes creating a build directory, configuring the build with tests enabled, compiling the project, and running the tests. It also mentions how to specify a custom directory for test data if needed. ```shell mkdir build cd build cmake .. -DJSON_BuildTests=On cmake --build . ctest --output-on-failure ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/tinygltf/README.md Compiles and runs unit tests for the glTF loader. This involves navigating to the 'tests' directory, running 'make' to build the test executables, and then executing `./tester` and `./tester_noexcept`. ```bash $ cd tests $ make $ ./tester $ ./tester_noexcept ``` -------------------------------- ### Get String Value from JSON (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Retrieves the stored string value from a JSON object that represents a string. The `.template get()` or `.get_to()` methods can be used for this purpose. Note the distinction between retrieving a string value and serializing the JSON object. ```cpp // store a string in a JSON value json j_string = "this is a string"; // retrieve the string value auto cpp_string = j_string.template get(); // retrieve the string value (alternative when a variable already exists) std::string cpp_string2; j_string.get_to(cpp_string2); // retrieve the serialized value (explicit JSON serialization) std::string serialized_string = j_string.dump(); // output of original string std::cout << cpp_string << " == " << cpp_string2 << " == " << j_string.template get() << '\n'; // output of serialized value std::cout << j_string << " == " << serialized_string << std::endl; ``` -------------------------------- ### Serialize and Deserialize JSON to Binary Formats (BSON, CBOR, MessagePack, UBJSON) in C++ Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Demonstrates how to convert JSON values to various binary formats (BSON, CBOR, MessagePack, UBJSON) and back using the json library. This is useful for efficient data exchange over networks. It covers serialization to byte vectors and subsequent deserialization. ```cpp // create a JSON value json j = R"({\"compact\": true, \"schema\": 0})"_json; // serialize to BSON std::vector v_bson = json::to_bson(j); // 0x1B, 0x00, 0x00, 0x00, 0x08, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x00, 0x01, 0x10, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 // roundtrip json j_from_bson = json::from_bson(v_bson); // serialize to CBOR std::vector v_cbor = json::to_cbor(j); // 0xA2, 0x67, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xF5, 0x66, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00 // roundtrip json j_from_cbor = json::from_cbor(v_cbor); // serialize to MessagePack std::vector v_msgpack = json::to_msgpack(j); // 0x82, 0xA7, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0xC3, 0xA6, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x00 // roundtrip json j_from_msgpack = json::from_msgpack(v_msgpack); // serialize to UBJSON std::vector v_ubjson = json::to_ubjson(j); // 0x7B, 0x69, 0x07, 0x63, 0x6F, 0x6D, 0x70, 0x61, 0x63, 0x74, 0x54, 0x69, 0x06, 0x73, 0x63, 0x68, 0x65, 0x6D, 0x61, 0x69, 0x00, 0x7D // roundtrip json j_from_ubjson = json::from_ubjson(v_ubjson); ``` -------------------------------- ### Skipping Non-Reproducible Tests Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This command shows how to run `ctest` while excluding tests that modify installed files, ensuring a reproducible testing environment. These tests are marked with the 'not_reproducible' label. ```shell ctest -LE not_reproducible ``` -------------------------------- ### CMake Integration for nanoflann Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/nanoflann/README.md Demonstrates how to find and link the nanoflann library within a CMake project. This ensures that the project can utilize nanoflann's headers and libraries for KD-tree operations. ```cmake # Find nanoflannConfig.cmake: find_package(nanoflann) add_executable(my_project test.cpp) # Make sure the include path is used: target_link_libraries(my_project nanoflann::nanoflann) ``` -------------------------------- ### Add nlohmann_json dependency using Meson Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Declares the nlohmann_json library as a required dependency within a Meson build configuration. This allows Meson to find and link against the system-wide installed library. ```meson json = dependency('nlohmann_json', required: true) ``` -------------------------------- ### Run glTF Parsing Test (Bash) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/tinygltf/README.md Executes the glTF parsing test using a Python script. This requires Python 2.6 or 2.7 and the glTF-Sample-Models repository cloned locally. The command assumes you have built the `loader_example` and configured `test_runner.py`. ```bash $ python test_runner.py ``` -------------------------------- ### Simplified Arbitrary Type Conversion (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Demonstrates a more concise way to convert custom types to and from JSON using overloaded `to_json` and `from_json` functions. ```cpp // create a person ns::person p {"Ned Flanders", "744 Evergreen Terrace", 60}; // conversion: person -> json json j = p; std::cout << j << std::endl; // {"address":"744 Evergreen Terrace","age":60,"name":"Ned Flanders"} // conversion: json -> person auto p2 = j.template get(); // that's it assert(p == p2); ``` -------------------------------- ### Custom `to_json` and `from_json` Implementation (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Provides the essential `to_json` and `from_json` functions required for custom type serialization and deserialization with the nlohmann::json library. ```cpp using json = nlohmann::json; namespace ns { void to_json(json& j, const person& p) { j = json{{"name", p.name}, {"address", p.address}, {"age", p.age}}; } void from_json(const json& j, person& p) { j.at("name").get_to(p.name); j.at("address").get_to(p.address); j.at("age").get_to(p.age); } } // namespace ns ``` -------------------------------- ### Add nlohmann-json with CPM.cmake Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Adds the nlohmann_json package to a CMake project using the CPM.cmake script. This example demonstrates specifying the GitHub repository and a specific version. Ensure CPM.cmake is added to your project first. ```cmake CPMAddPackage( NAME nlohmann_json GITHUB_REPOSITORY nlohmann/json VERSION 3.9.1) ``` -------------------------------- ### Explicit JSON Array and Object Creation in C++ Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Demonstrates explicit methods for creating JSON arrays and objects using `json::array()` and `json::object()`. Useful for expressing empty structures or when specific array/object types are required. ```cpp // a way to express the empty array [] json empty_array_explicit = json::array(); // ways to express the empty object {} json empty_object_implicit = json({}); json empty_object_explicit = json::object(); // a way to express an _array_ of key/value pairs [["currency", "USD"], ["value", 42.99]] json array_not_object = json::array({ {"currency", "USD"}, {"value", 42.99} }); ``` -------------------------------- ### Enum to JSON String Conversion Example Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This C++ snippet demonstrates the usage of the specialized enum serialization. It shows how to convert an enum value to its corresponding JSON string representation and how to deserialize a JSON string back into an enum value. ```cpp // enum to JSON as string json j = TS_STOPPED; assert(j == "stopped"); // json string to enum json j3 = "running"; assert(j3.template get() == TS_RUNNING); // undefined json value to enum (where the first map entry above is the default) json jPi = 3.14; assert(jPi.template get() == TS_INVALID ); ``` -------------------------------- ### Build scsdk using CMake Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/scsdk/README.md Instructions for building the scsdk library using CMake for an out-of-source build on Mac or Linux. This process involves creating a build directory, configuring with CMake, and compiling using make. ```bash mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Debug .. make -j `nproc` ./scsdk_test ``` -------------------------------- ### Example of a Potentially Stack Overflowing Serializer Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This C++ code demonstrates a 'bad_serializer' that can lead to stack overflows if not implemented carefully. It highlights the recursive call issue where the serializer might inadvertently call itself, causing infinite recursion and a crash. ```cpp template struct bad_serializer { template static void to_json(BasicJsonType& j, const T& value) { // this calls BasicJsonType::json_serializer::to_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! j = value; } template static void to_json(const BasicJsonType& j, T& value) { // this calls BasicJsonType::json_serializer::from_json(j, value); // if BasicJsonType::json_serializer == bad_serializer ... oops! value = j.template get(); // oops! } }; ``` -------------------------------- ### CMake: Link nlohmann_json::nlohmann_json target (External) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This CMake configuration demonstrates how to link against an externally installed nlohmann_json library. It uses `find_package` to locate the library and `target_link_libraries` to apply its usage requirements, including include directories and C++11 flags. ```cmake # CMakeLists.txt find_package(nlohmann_json 3.2.0 REQUIRED) ... add_library(foo ...) ... target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json) ``` -------------------------------- ### Implement STB Include Library Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/stb/README.md This code shows how to implement the STB Include library, which adds recursive `#include` support, particularly useful for GLSL shaders. Define `STB_INCLUDE_IMPLEMENTATION` in a single source file before including `stb_include.h` to compile its include handling functionality. ```c #define STB_INCLUDE_IMPLEMENTATION #include "stb_include.h" ``` -------------------------------- ### CMake: Support External or Embedded nlohmann/json Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This CMake pattern allows a project to dynamically choose between using an externally installed or an embedded version of the nlohmann/json library. It uses an option to control the choice and ensures the `nlohmann_json::nlohmann_json` target is always available. ```cmake # Top level CMakeLists.txt project(FOO) ... option(FOO_USE_EXTERNAL_JSON "Use an external JSON library" OFF) ... add_subdirectory(thirdparty) ... add_library(foo ...) ... # Note that the namespaced target will always be available regardless of the # import method target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json) ``` -------------------------------- ### Load glTF 2.0 Model from File (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/tinygltf/README.md Loads a glTF 2.0 model from an ASCII or binary file using the TinyGLTF library. It includes error and warning reporting. Ensure TINYGLTF_IMPLEMENTATION and STB_IMAGE_IMPLEMENTATION are defined in one .cc file. The function returns a boolean indicating success or failure. ```c++ // Define these only in *one* .cc file. #define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION // #define TINYGLTF_NOEXCEPTION // optional. disable exception handling. #include "tiny_gltf.h" using namespace tinygltf; Model model; TinyGLTF loader; std::string err; std::string warn; bool ret = loader.LoadASCIIFromFile(&model, &err, &warn, argv[1]); //bool ret = loader.LoadBinaryFromFile(&model, &err, &warn, argv[1]); // for binary glTF(.glb) if (!warn.empty()) { printf("Warn: %s\n", warn.c_str()); } if (!err.empty()) { printf("Err: %s\n", err.c_str()); } if (!ret) { printf("Failed to parse glTF\n"); return -1; } ``` -------------------------------- ### CMake: Embed nlohmann/json library using add_subdirectory Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This CMake snippet shows how to embed the nlohmann/json library directly into a project by adding its source directory. It includes options to disable tests and installation for the third-party library and links the `nlohmann_json::nlohmann_json` target. ```cmake # CMakeLists.txt set(JSON_BuildTests OFF CACHE INTERNAL "") # If you only include this third party in PRIVATE source files, you do not # need to install it when your main project gets installed. # set(JSON_Install OFF CACHE INTERNAL "") # Don't use include(nlohmann_json/CMakeLists.txt) since that carries with it # unintended consequences that will break the build. It's generally # discouraged (although not necessarily well documented as such) to use # include(...) for pulling in other CMake projects anyways. add_subdirectory(nlohmann_json) ... add_library(foo ...) ... target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json) ``` -------------------------------- ### Implicit Conversions to JSON (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Demonstrates implicit conversion of C++ standard types like strings, booleans, and numbers to JSON values. It also highlights recommended practices versus non-recommended direct assignments. ```cpp // strings std::string s1 = "Hello, world!"; json js = s1; auto s2 = js.template get(); // NOT RECOMMENDED std::string s3 = js; std::string s4; s4 = js; // Booleans bool b1 = true; json jb = b1; auto b2 = jb.template get(); // NOT RECOMMENDED bool b3 = jb; bool b4; b4 = jb; // numbers int i = 42; json jn = i; auto f = jn.template get(); // NOT RECOMMENDED double f2 = jb; double f3; f3 = jb; // etc. ``` -------------------------------- ### Include nlohmann_json Library using CMake Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This CMake code snippet demonstrates how to integrate the nlohmann_json library into a project. It allows for either finding an already installed version of the library using `find_package` or by adding the nlohmann_json source directory as a subdirectory. The `FOO_USE_EXTERNAL_JSON` variable controls which method is used. ```cmake if(FOO_USE_EXTERNAL_JSON) find_package(nlohmann_json 3.2.0 REQUIRED) else() set(JSON_BuildTests OFF CACHE INTERNAL "") add_subdirectory(nlohmann_json) endif() ``` -------------------------------- ### Create JSON Objects from Literals using C++ Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Shows multiple ways to create a json object from a JSON literal string. Includes using raw string literals with `json::parse()`, user-defined literals, and C++ initializer lists. ```cpp // Using (raw) string literals and json::parse json ex1 = json::parse(R"( { "pi": 3.141, "happy": true } )"); ``` ```cpp // Using user-defined (raw) string literals using namespace nlohmann::literals; json ex2 = R"( { "pi": 3.141, "happy": true } )"_json; ``` ```cpp // Using initializer lists json ex3 = { {"happy", true}, {"pi", 3.141}, }; ``` -------------------------------- ### Skipping Git-Required Tests Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This command demonstrates how to execute the `ctest` command while skipping tests that require Git to be present, typically when the library was downloaded rather than cloned. This is useful in environments where Git is not available or not desired for testing. ```shell ctest -LE git_required ``` -------------------------------- ### C++ Geometry File I/O and Transformations Source: https://context7.com/standardcyborg/standardcyborgcocoa/llms.txt Shows how to use the scsdk C++ library for reading and writing 3D geometry data, specifically PLY files. It demonstrates accessing vertex data, applying transformations (like rotation), and writing the modified geometry back to a file. Requires the scsdk library. ```cpp #include #include #include #include #include using namespace standard_cyborg; void processGeometryFile(const std::string& inputPath, const std::string& outputPath) { // Read PLY file sc3d::Geometry geometry; if (!io::ply::ReadGeometryFromPLYFile(geometry, inputPath)) { std::cerr << "Failed to read PLY file" << std::endl; return; } std::cout << "Loaded geometry with " << geometry.getPositions().size() << " vertices" << std::endl; // Access geometry data const auto& positions = geometry.getPositions(); const auto& normals = geometry.getNormals(); const auto& colors = geometry.getColors(); const auto& faces = geometry.getFaces(); // Create transformation matrix (90 degree rotation around Y axis) math::Mat3x4 transform = math::Mat3x4::Identity(); float angle = M_PI / 2.0f; transform(0, 0) = cos(angle); transform(0, 2) = sin(angle); transform(2, 0) = -sin(angle); transform(2, 2) = cos(angle); // Transform geometry geometry.transform(transform); // Write to file if (io::ply::WriteGeometryToPLYFile(outputPath, geometry)) { std::cout << "Saved transformed geometry" << std::endl; } } ``` -------------------------------- ### Handling Binary Types in CBOR and MessagePack using C++ Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Illustrates how to work with binary data types from formats like CBOR and MessagePack, which are stored as `std::vector`. This includes reading binary values, checking for subtypes, accessing the byte vector, and setting subtypes for serialization. ```cpp // CBOR byte string with payload 0xCAFE std::vector v = {0x42, 0xCA, 0xFE}; // read value json j = json::from_cbor(v); // the JSON value has type binary j.is_binary(); // true // get reference to stored binary value auto& binary = j.get_binary(); // the binary value has no subtype (CBOR has no binary subtypes) binary.has_subtype(); // false // access std::vector member functions binary.size(); // 2 binary[0]; // 0xCA binary[1]; // 0xFE // set subtype to 0x10 binary.set_subtype(0x10); // serialize to MessagePack auto cbor = json::to_msgpack(j); // 0xD5 (fixext2), 0x10, 0xCA, 0xFE ``` -------------------------------- ### Implement STB Sprintf Library Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/stb/README.md This code illustrates how to implement the STB Sprintf library, offering a fast `sprintf` and `snprintf` alternative for C/C++. Ensure you define `STB_SPRINTF_IMPLEMENTATION` in exactly one source file before including `stb_sprintf.h` to activate its functions. ```c #define STB_SPRINTF_IMPLEMENTATION #include "stb_sprintf.h" ``` -------------------------------- ### STL-like Container Access for JSON Arrays (C++) Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md Shows how to use the JSON class as an STL-like container, specifically for arrays. It covers adding elements using `push_back` and `emplace_back`, iterating through elements using iterators and range-based for loops, accessing elements by index, modifying elements, and checking container properties like size and emptiness. It also includes type-specific getters and convenience type checkers. ```cpp // create an array using push_back json j; j.push_back("foo"); j.push_back(1); j.push_back(true); // also use emplace_back j.emplace_back(1.78); // iterate the array for (json::iterator it = j.begin(); it != j.end(); ++it) { std::cout << *it << '\n'; } // range-based for for (auto& element : j) { std::cout << element << '\n'; } // getter/setter const auto tmp = j[0].template get(); j[1] = 42; bool foo = j.at(2); // comparison j == R ``` -------------------------------- ### Implement STB DXT Compression Library Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/stb/README.md This snippet illustrates the implementation of the STB DXT library, a real-time DXT compressor developed by Fabian "ryg" Giesen. Define `STB_DXT_IMPLEMENTATION` in one C/C++ source file before including `stb_dxt.h` to compile the compression functionality. ```c #define STB_DXT_IMPLEMENTATION #include "stb_dxt.h" ``` -------------------------------- ### Swift Point Cloud and Mesh Geometry Operations Source: https://context7.com/standardcyborg/standardcyborgcocoa/llms.txt Demonstrates how to use the SCPointCloud and SCMesh classes in Swift for geometry manipulation. It covers accessing data, transforming point clouds, converting to meshes, saving in PLY and OBJ formats, and loading meshes back. Requires the StandardCyborgFusion framework. ```swift import StandardCyborgFusion func processGeometry(pointCloud: SCPointCloud) { // Point cloud operations print("Point count: \(pointCloud.pointCount)") // Access geometry data let positions = pointCloud.positions let normals = pointCloud.normals let colors = pointCloud.colors // Transform point cloud var rotationMatrix = matrix_identity_float4x4 rotationMatrix = simd_mul(rotationMatrix, matrix_float4x4(rotationAngle: .pi / 4, axis: [0, 1, 0])) pointCloud.transform(by: rotationMatrix) // Convert to mesh let mesh = SCMesh(pointCloud: pointCloud) // Mesh operations print("Vertex count: \(mesh.vertexCount)") print("Face count: \(mesh.faceCount)") // Save in different formats let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! // PLY format let plyPath = documentsURL.appendingPathComponent("mesh.ply").path mesh.writeToPLY(atPath: plyPath) // OBJ format let objPath = documentsURL.appendingPathComponent("mesh.obj").path mesh.writeToOBJ(atPath: objPath) // Load mesh back if let loadedMesh = SCMesh(plyAtPath: plyPath) { print("Mesh loaded: \(loadedMesh.vertexCount) vertices") } } extension matrix_float4x4 { init(rotationAngle angle: Float, axis: simd_float3) { let c = cos(angle) let s = sin(angle) let t = 1 - c let n = normalize(axis) self.init(columns: ( simd_float4(t*n.x*n.x + c, t*n.x*n.y + s*n.z, t*n.x*n.z - s*n.y, 0), simd_float4(t*n.x*n.y - s*n.z, t*n.y*n.y + c, t*n.y*n.z + s*n.x, 0), simd_float4(t*n.x*n.z + s*n.y, t*n.y*n.z - s*n.x, t*n.z*n.z + c, 0), simd_float4(0, 0, 0, 1) )) } } ``` -------------------------------- ### Initiate and Handle Real-Time 3D Scan with ScanningViewController (Swift) Source: https://context7.com/standardcyborg/standardcyborgcocoa/llms.txt This Swift code demonstrates how to present `ScanningViewController` to initiate a real-time 3D scan using the TrueDepth camera. It configures scan parameters like mesh generation and resolution, and implements delegate methods to handle scan cancellation and successful completion, including saving the resulting point cloud to a PLY file. ```swift import StandardCyborgUI import StandardCyborgFusion import UIKit class ViewController: UIViewController, ScanningViewControllerDelegate { func startScanning() { let scanningVC = ScanningViewController() scanningVC.delegate = self scanningVC.generatesTexturedMeshes = true scanningVC.maxDepthResolution = 320 scanningVC.countdownStartCount = 3 scanningVC.modalPresentationStyle = .fullScreen present(scanningVC, animated: true) } // Called when user cancels scanning func scanningViewControllerDidCancel(_ controller: ScanningViewController) { dismiss(animated: true) } // Called when scan completes successfully func scanningViewController(_ controller: ScanningViewController, didScan pointCloud: SCPointCloud) { // Process the resulting point cloud print("Scan completed with \(pointCloud.pointCount) points") // Save to file let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! let plyPath = url.appendingPathComponent("scan.ply").path pointCloud.writeToPLY(atPath: plyPath) dismiss(animated: true) } } ``` -------------------------------- ### CMake: Embed nlohmann/json using FetchContent Source: https://github.com/standardcyborg/standardcyborgcocoa/blob/master/CppDependencies/json/README.md This CMake configuration utilizes the FetchContent module to automatically download and integrate the nlohmann/json library at configure time. It requires CMake v3.11 or later and links the `nlohmann_json::nlohmann_json` target. ```cmake include(FetchContent) FetchContent_Declare(json URL https://github.com/nlohmann/json/releases/download/v3.11.3/json.tar.xz) FetchContent_MakeAvailable(json) target_link_libraries(foo PRIVATE nlohmann_json::nlohmann_json) ```