Skip to content
Snippets Groups Projects
Commit af124225 authored by Albu, Sebastian David's avatar Albu, Sebastian David
Browse files

Initial Commit

parent 0ca9392b
No related branches found
No related tags found
No related merge requests found
Showing
with 557 additions and 88 deletions
# LWJGL-Triangle # TriangleGPURenderer
Very simplistic GPU renderer of a triangle gradient using LWJGL and some GLSL for the vertex and fragment shader files.
Author: [[sebastian.albu@tugraz.at](mailto:sebastian.albu@tugraz.at)]
## Getting started
---
To make it easy for you to get started with GitLab, here's a list of recommended next steps.
# Simple Triangle Renderer with LWJGL and GLSL
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)!
This project demonstrates a real-time rendering example using **LWJGL (Lightweight Java Game Library)** and **GLSL shaders**. It draws a simple triangle that dynamically changes colors based on time.
## Add your files
## Features
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files - **Real-time Rendering**: Renders a triangle with OpenGL.
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command: - **GLSL Shaders**: Uses vertex and fragment shaders to process geometry and apply dynamic color effects.
- **GLFW Integration**: Manages the window and rendering loop.
---
## Project Structure
### Source Files
| File | Description |
|-------------------------------|------------------------------------------------------------------------------------------------------|
| `GpuRenderer.java` | The main rendering logic. Sets up OpenGL, compiles shaders, and manages the rendering loop. |
| `ShaderUtils.java` | Utility class for loading, compiling, and linking GLSL shaders. |
| `vertexShader.vert` | Vertex shader: Handles geometry transformation and passes color data to the fragment shader. |
| `fragmentShader.frag` | Fragment shader: Handles pixel-level coloring, including the real-time dynamic color-changing effect. |
### GLSL Files
| File | GLSL Functionality |
|--------------------------|-------------------------------------------------------------------------------------------------------------|
| `vertexShader.vert` | - Transforms vertex positions to clip space.<br>- Passes vertex colors (`vColor`) to the fragment shader. |
| `fragmentShader.frag` | - Receives interpolated colors from the vertex shader.<br>- Applies time-driven color changes using `uTime`. |
### Key GLFW/OpenGL Methods
| Method | Description |
|---------------------------|------------------------------------------------------------------------------------------------------|
| `glfwInit()` | Initializes GLFW. |
| `glfwCreateWindow()` | Creates a rendering window. |
| `glfwMakeContextCurrent()`| Sets the current OpenGL context. |
| `glfwSwapBuffers()` | Swaps the front and back buffers for double buffering. |
| `glfwPollEvents()` | Polls for window events, such as input and closing. |
| `glGenVertexArrays()` | Generates a Vertex Array Object (VAO) to store vertex attribute configurations. |
| `glGenBuffers()` | Generates a Vertex Buffer Object (VBO) for storing vertex data. |
| `glVertexAttribPointer()` | Defines how vertex attributes (positions, colors, etc.) are interpreted from the buffer. |
| `glUseProgram()` | Activates a shader program for rendering. |
| `glUniform1f()` | Sets a uniform float variable (`uTime` in this case) in the active shader program. |
---
## How to Run the Project
### Prerequisites
- Install **Java 17** or higher (this project uses Java 17).
- Install **Maven** (required for dependency management).
- Install IntelliJ IDEA (Community or Ultimate Edition).
- Ensure you have OpenGL 3.3 or later supported on your system.
### Steps to Run
1. **Clone the Project**:
Clone the repository or download the files to your local machine.
```bash
git clone <repository-url>
cd <project-folder>
``` ```
cd existing_repo
git remote add origin https://gitlab.tugraz.at/B68DC7FA01113758/lwjgl-triangle.git
git branch -M main
git push -uf origin main
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.tugraz.at/B68DC7FA01113758/lwjgl-triangle/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Set auto-merge](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html)
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing (SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
*** 2. **Open in IntelliJ**:
- Open IntelliJ IDEA.
# Editing this README - Click `File > Open` and select the project folder.
- Ensure IntelliJ recognizes the `pom.xml` file and automatically loads dependencies.
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thanks to [makeareadme.com](https://www.makeareadme.com/) for this template.
3. **Set the Working Directory**:
## Suggestions for a good README - Go to `Run > Edit Configurations`.
- In the **Run/Debug Configurations** window, select the `GpuRenderer` configuration.
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. - Set the **Working Directory** to the project root (where `resources` is located).
## Name 4. **Run the Project**:
Choose a self-explaining name for your project. - Right-click `GpuRenderer.java` in the project structure.
- Select `Run GpuRenderer.main()`.
## Description
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors. 5. **Expected Output**:
- A window will open displaying a triangle.
## Badges - The triangle will dynamically change colors in real time.
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
---
## Visuals
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method. ## File Overview
## Installation ### **`GpuRenderer.java`**
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection. Handles the OpenGL rendering process:
- Initializes GLFW and OpenGL context.
## Usage - Compiles and links shaders using `ShaderUtils`.
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. - Creates a triangle with vertex positions and colors.
- Passes time (`uTime`) to the fragment shader for dynamic effects.
## Support
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc. ### **`ShaderUtils.java`**
Provides helper methods for shader management:
## Roadmap - **`createShaderProgram()`**: Compiles and links vertex and fragment shaders into a single shader program.
If you have ideas for releases in the future, it is a good idea to list them in the README. - **`readFile()`**: Reads the GLSL shader files from the specified path.
- **`createShader()`**: Compiles a GLSL shader of a specified type (vertex or fragment).
## Contributing
State if you are open to contributions and what your requirements are for accepting them. ### **`vertexShader.vert`**
Vertex shader:
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. - Converts vertex coordinates from model space to clip space (`gl_Position`).
- Passes interpolated color data (`vColor`) to the fragment shader.
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
### **`fragmentShader.frag`**
Fragment shader:
- Modulates the triangle's color based on time (`uTime`) using sine functions for smooth transitions.
---
## Dependencies
The project uses Maven for dependency management. Key dependencies include:
- **LWJGL 3**: For OpenGL, GLFW, and related bindings.
### `pom.xml`
```xml
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
```
## Authors and acknowledgment ---
Show your appreciation to those who have contributed to the project.
## License ## Customization Ideas
For open source projects, say how it is licensed. - **Add Mouse Interaction**: Use GLFW input functions to interact with the triangle (e.g., changing its size or position).
- **Dynamic Vertex Data**: Modify vertex positions or colors in real-time for more dynamic visuals.
- **Add More Shapes**: Experiment with rendering additional shapes or complex objects.
## Project status ---
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
dependency-reduced-pom.xml
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<ScalaCodeStyleSettings>
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
</ScalaCodeStyleSettings>
</code_scheme>
</component>
\ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>at.tugraz.oop2</groupId>
<artifactId>FractalRenderer</artifactId>
<version>WS24</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<javaVersion>17</javaVersion>
<maven.compiler.source>${javaVersion}</maven.compiler.source>
<maven.compiler.target>${javaVersion}</maven.compiler.target>
<lwjgl.version>3.3.1</lwjgl.version>
</properties>
<profiles>
<profile>
<id>lwjgl-natives-linux</id>
<activation>
<os>
<family>unix</family>
</os>
</activation>
<properties>
<lwjgl.natives>natives-linux</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-macos</id>
<activation>
<os>
<family>mac</family>
</os>
</activation>
<properties>
<lwjgl.natives>natives-macos</lwjgl.natives>
</properties>
</profile>
<profile>
<id>lwjgl-natives-windows</id>
<activation>
<os>
<family>windows</family>
</os>
</activation>
<properties>
<lwjgl.natives>natives-windows</lwjgl.natives>
</properties>
</profile>
</profiles>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-bom</artifactId>
<version>${lwjgl.version}</version>
<scope>import</scope>
<type>pom</type>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-glfw</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
<dependency>
<groupId>org.lwjgl</groupId>
<artifactId>lwjgl-opengl</artifactId>
<classifier>${lwjgl.natives}</classifier>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${javaVersion}</source>
<target>${javaVersion}</target>
<optimize>true</optimize>
<compilerArgs>
<arg>-Xlint:all,-processing,-serial</arg>
<arg>-Werror</arg>
</compilerArgs>
<showWarnings>true</showWarnings>
<showDeprecation>false</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<mainClass>BonusAssignmentOOP2WS24.gpu.GpuRenderer</mainClass> <!-- Change this to your main class -->
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<finalName>FractalRendererOOP2</finalName> <!-- Specify your custom JAR name here -->
<transformers>
<transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>BonusAssignmentOOP2WS24.gpu.GpuRenderer</mainClass> <!-- Change this to your main class -->
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package BonusAssignmentOOP2WS24.gpu;
import static org.lwjgl.glfw.GLFW.*;
import org.lwjgl.opengl.*;
import static org.lwjgl.opengl.GL33.*;
import static org.lwjgl.system.MemoryUtil.*;
public class GpuRenderer {
private long window;
private int shaderProgram;
private int vao;
public static void main(String[] args) {
new GpuRenderer().run();
}
public void run() {
init();
loop();
glfwDestroyWindow(window);
glfwTerminate();
}
private void init() {
if (!glfwInit()) throw new IllegalStateException("Failed to initialize GLFW");
window = glfwCreateWindow(800, 600, "Simple Shader Example", NULL, NULL);
if (window == NULL) throw new RuntimeException("Failed to create GLFW window");
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
GL.createCapabilities();
System.out.println("Working Directory = " + System.getProperty("user.dir"));
shaderProgram = ShaderUtils.createShaderProgram("vertexShader.vert", "fragmentShader.frag");
vao = createTriangle();
}
private void loop() {
while (!glfwWindowShouldClose(window)) {
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT);
// Use the shader program
glUseProgram(shaderProgram);
// Update the time uniform
float time = (float) glfwGetTime();
int timeLocation = glGetUniformLocation(shaderProgram, "uTime");
glUniform1f(timeLocation, time);
// Bind the VAO and draw the triangle
glBindVertexArray(vao);
glDrawArrays(GL_TRIANGLES, 0, 3);
// Swap buffers and poll events
glfwSwapBuffers(window);
glfwPollEvents();
}
}
private int createTriangle() {
float[] vertices = {
// Positions // Colors
0.0f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.0f, 0.0f, 1.0f
};
int vao = glGenVertexArrays();
int vbo = glGenBuffers();
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 2, GL_FLOAT, false, 5 * Float.BYTES, 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, false, 5 * Float.BYTES, 2 * Float.BYTES);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
return vao;
}
}
package BonusAssignmentOOP2WS24.gpu;
import java.io.IOException;
import static org.lwjgl.opengl.GL20.*;
public class ShaderUtils {
public static int createShaderProgram(String vertexPath, String fragmentPath) {
int vertexShader = createShader(GL_VERTEX_SHADER, vertexPath);
int fragmentShader = createShader(GL_FRAGMENT_SHADER, fragmentPath);
int program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) {
throw new RuntimeException("Shader program linking failed: " + glGetProgramInfoLog(program));
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return program;
}
private static int createShader(int type, String path) {
int shader = glCreateShader(type);
String source = readFile(path);
glShaderSource(shader, source);
glCompileShader(shader);
if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) {
throw new RuntimeException("Shader compilation failed for " + path + ": " + glGetShaderInfoLog(shader));
}
return shader;
}
private static String readFile(String path) {
try (var inputStream = ShaderUtils.class.getClassLoader().getResourceAsStream(path)) {
if (inputStream == null) {
throw new RuntimeException("Shader file not found: " + path);
}
return new String(inputStream.readAllBytes());
} catch (IOException e) {
throw new RuntimeException("Failed to read shader file: " + path, e);
}
}
}
#version 330 core
in vec3 vColor; // Input from the vertex shader
out vec4 FragColor; // Final color output
uniform float uTime; // Time uniform passed from the CPU
void main() {
// Create a dynamic color shift based on time
vec3 dynamicColor = vColor * (0.5 + 0.5 * sin(uTime)); // Scale between 0 and 1
FragColor = vec4(dynamicColor, 1.0); // Set the final pixel color
}
#version 330 core
layout(location = 0) in vec2 aPos; // Vertex position (attribute 0)
layout(location = 1) in vec3 aColor; // Vertex color (attribute 1)
out vec3 vColor; // Output to the fragment shader
void main() {
gl_Position = vec4(aPos, 0.0, 1.0); // Convert to 4D homogeneous coordinate
vColor = aColor; // Pass color to fragment shader
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment