I have a GLSL function that I want to call from my c++ program on an array of 3D points,…
- User
I have a GLSL function that I want to call from my c++ program on an array of 3D points, n=100 float inverseSF(float3 p, float n) { .... }
Write a cross-platform cmake based project to do that
- Assistant
To call a GLSL function from a C++ program and process an array of 3D points, you'll need to leverage OpenGL's shader capabilities. Below is a cross-platform CMake-based project that demonstrates how to achieve this using GLFW for context creation and GLAD for loading OpenGL functions.
Project Structure
GLSL_Cpp_Project/ ├── CMakeLists.txt ├── shaders/ │ └── compute.glsl ├── src/ │ └── main.cpp └── include/ └── stb_image.h (if needed)Step-by-Step Guide
-
Set Up CMake Project
Create a
CMakeLists.txtfile to manage the build process and dependencies. -
Initialize OpenGL Context
Use GLFW to create an OpenGL context which is necessary to run GLSL shaders.
-
Load OpenGL Functions
Use GLAD to load the necessary OpenGL functions.
-
Create and Compile GLSL Compute Shader
The compute shader will contain your
inverseSFfunction and process the array of 3D points. -
Dispatch Compute Shader
Pass the data to the GPU, execute the shader, and retrieve the results.
-
Build and Run
Use CMake to build the project across different platforms.
1. CMakeLists.txt
cmake_minimum_required(VERSION 3.10) project(GLSL_CPP_Project) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Add sources set(SOURCES src/main.cpp # Add other source files here ) # Include directories include_directories( ${CMAKE_SOURCE_DIR}/include # GLAD include ${CMAKE_SOURCE_DIR}/external/glad/include # GLFW include ${CMAKE_SOURCE_DIR}/external/glfw/include ) # Add GLAD add_library(glad external/glad/src/glad.c) target_include_directories(glad PUBLIC external/glad/include) # Add GLFW set(GLFW_BUILD_DOCS OFF CACHE BOOL "GLFW lib only" FORCE) set(GLFW_BUILD_TESTS OFF CACHE BOOL "GLFW lib only" FORCE) set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "GLFW lib only" FORCE) add_subdirectory(external/glfw) # Create executable add_executable(GLSL_CPP_Project ${SOURCES}) # Link libraries target_link_libraries(GLSL_CPP_Project glad glfw ${CMAKE_DL_LIBS}) # For Windows, link OpenGL if (WIN32) target_link_libraries(GLSL_CPP_Project opengl32) elseif(APPLE) find_library(OpenGL_LIBRARY OpenGL) target_link_libraries(GLSL_CPP_Project ${OpenGL_LIBRARY}) else() find_package(OpenGL REQUIRED) target_link_libraries(GLSL_CPP_Project ${OPENGL_LIBRARIES}) endif()Notes:
-
GLAD and GLFW: It's assumed that GLAD and GLFW are placed in the
external/directory. You can obtain them as follows:- GLAD: Download from glad.dav1d.de with the desired specifications and extract to
external/glad/. - GLFW: Clone from GLFW GitHub into
external/glfw/.
- GLAD: Download from glad.dav1d.de with the desired specifications and extract to
-
stb_image.h: If needed for image loading, place it in the
include/directory.
2. GLSL Compute Shader (
shaders/compute.glsl)#version 430 layout(local_size_x = 100) in; // Define the structure of a 3D point struct Point3D { float x; float y; float z; }; // Input and Output buffers layout(std430, binding = 0) buffer InputBuffer { Point3D pointsIn[]; }; layout(std430, binding = 1) buffer OutputBuffer { float results[]; }; // The inverseSF function float inverseSF(vec3 p, float n) { // Example implementation (replace with your actual logic) return 1.0 / (length(p) + n); } void main() { uint idx = gl_GlobalInvocationID.x; Point3D p = pointsIn[idx]; float n = float(idx) * 0.1; // Example n value, replace as needed results[idx] = inverseSF(vec3(p.x, p.y, p.z), n); }Notes:
- Shader Version: Ensure that your OpenGL context supports at least version 4.3 for compute shaders.
- InverseSF Implementation: Replace the example implementation with your actual
inverseSFlogic.
3. C++ Source Code (
src/main.cpp)#include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <vector> #include <fstream> #include <sstream> // Struct to represent a 3D point struct Point3D { float x, y, z; }; // Function to read shader files std::string readShaderSource(const std::string& filepath) { std::ifstream file(filepath); if (!file.is_open()) { std::cerr << "Failed to open shader: " << filepath << std::endl; exit(EXIT_FAILURE); } std::stringstream ss; ss << file.rdbuf(); return ss.str(); } // Function to compile shader GLuint compileShader(const std::string& source, GLenum shaderType) { GLuint shader = glCreateShader(shaderType); const char* src = source.c_str(); glShaderSource(shader, 1, &src, nullptr); glCompileShader(shader); // Check compilation GLint success; glGetShaderiv(shader, GL_COMPILE_STATUS, &success); if (!success){ char infoLog[512]; glGetShaderInfoLog(shader, 512, NULL, infoLog); std::cerr << "ERROR::SHADER::COMPILATION_FAILED\n" << infoLog << std::endl; exit(EXIT_FAILURE); } return shader; } // Function to create compute shader program GLuint createComputeProgram(const std::string& computePath) { std::string computeSource = readShaderSource(computePath); GLuint computeShader = compileShader(computeSource, GL_COMPUTE_SHADER); GLuint program = glCreateProgram(); glAttachShader(program, computeShader); glLinkProgram(program); // Check linking GLint success; glGetProgramiv(program, GL_LINK_STATUS, &success); if(!success){ char infoLog[512]; glGetProgramInfoLog(program, 512, NULL, infoLog); std::cerr << "ERROR::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl; exit(EXIT_FAILURE); } glDeleteShader(computeShader); return program; } int main() { // Initialize GLFW if (!glfwInit()){ std::cerr << "Failed to initialize GLFW\n"; return -1; } // Specify OpenGL version and profile (4.3 for compute shaders) glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // Hide window glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Create window GLFWwindow* window = glfwCreateWindow(1, 1, "Compute Shader", NULL, NULL); if (!window){ std::cerr << "Failed to create GLFW window\n"; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Load OpenGL functions using GLAD if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)){ std::cerr << "Failed to initialize GLAD\n"; return -1; } // Create data const unsigned int NUM_POINTS = 100; std::vector<Point3D> points(NUM_POINTS); for (unsigned int i = 0; i < NUM_POINTS; ++i){ points[i] = Point3D{ static_cast<float>(i), static_cast<float>(i + 1), static_cast<float>(i + 2) }; } // Create output buffer std::vector<float> results(NUM_POINTS, 0.0f); // Create and bind SSBOs GLuint ssboInput, ssboOutput; // Input SSBO glGenBuffers(1, &ssboInput); glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssboInput); glBufferData(GL_SHADER_STORAGE_BUFFER, NUM_POINTS * sizeof(Point3D), points.data(), GL_STATIC_DRAW); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssboInput); // Output SSBO glGenBuffers(1, &ssboOutput); glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssboOutput); glBufferData(GL_SHADER_STORAGE_BUFFER, NUM_POINTS * sizeof(float), results.data(), GL_DYNAMIC_COPY); glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 1, ssboOutput); // Create compute shader program GLuint computeProgram = createComputeProgram("shaders/compute.glsl"); glUseProgram(computeProgram); // Dispatch compute shader GLuint workGroupSize = 100; // As defined in the shader's local_size_x glDispatchCompute((NUM_POINTS + workGroupSize - 1) / workGroupSize, 1, 1); // Make sure writing to SSBO has finished glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT); // Read back results glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssboOutput); float* ptr = (float*)glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY); if(ptr){ for(unsigned int i = 0; i < NUM_POINTS; ++i){ results[i] = ptr[i]; } glUnmapBuffer(GL_SHADER_STORAGE_BUFFER); } else { std::cerr << "Failed to map buffer\n"; } // Print results for(unsigned int i = 0; i < NUM_POINTS; ++i){ std::cout << "Result[" << i << "] = " << results[i] << std::endl; } // Cleanup glDeleteBuffers(1, &ssboInput); glDeleteBuffers(1, &ssboOutput); glDeleteProgram(computeProgram); glfwDestroyWindow(window); glfwTerminate(); return 0; }Explanation:
-
Initialize GLFW and Create Invisible Window:
- An OpenGL context is necessary to run shaders. The window is hidden since rendering is not required.
-
Load OpenGL Functions with GLAD:
- GLAD manages OpenGL function pointers.
-
Prepare Data:
- An array of 100
Point3Dstructs is initialized.
- An array of 100
-
Setup Shader Storage Buffer Objects (SSBOs):
- Input SSBO: Contains the array of points.
- Output SSBO: Will store the results from the compute shader.
-
Compile and Link Compute Shader:
- The compute shader is loaded, compiled, and linked into a shader program.
-
Dispatch Compute Shader:
- The shader is executed with sufficient workgroups to cover all points.
-
Memory Barrier:
- Ensures that all shader writes to the SSBO are complete before reading.
-
Read Back Results:
- Maps the output buffer to CPU memory and copies the results.
-
Cleanup:
- Deletes buffers and terminates GLFW.
4. Building the Project
-
Clone/Download Dependencies:
- GLAD: Download and place in
external/glad/. - GLFW: Clone into
external/glfw/using:git clone https://github.com/glfw/glfw.git external/glfw - CMake Modules: You might need additional modules if dependencies require them.
- GLAD: Download and place in
-
Create Build Directory and Run CMake
mkdir build cd build cmake .. cmake --build . -
Run the Executable
After a successful build, run the executable:
./GLSL_CPP_ProjectThe program should output the results computed by the
inverseSFfunction for each point.
Additional Notes
-
Error Handling: The provided code includes basic error handling. For production code, consider more robust checks and exception handling.
-
Performance Considerations: For larger datasets, optimizing buffer usage and minimizing data transfers between CPU and GPU can lead to performance gains.
-
Extending Functionality: You can modify the compute shader and C++ code to handle more complex data structures or multiple dispatches.
-
Platform Compatibility: The provided CMake configuration should work across Windows, macOS, and Linux. Ensure that the appropriate OpenGL drivers are installed on your system.
-
Dependencies: Ensure that all dependencies (GLAD, GLFW) are correctly placed in the
external/directory or adjust theCMakeLists.txtpaths accordingly.
Conclusion
This project sets up a basic framework to call a GLSL function (
inverseSF) from a C++ application using OpenGL compute shaders. By following this structure, you can adapt the compute shader and C++ code to fit your specific computational needs, processing arrays of 3D points or other data structures as required. -