Compare commits

...

10 Commits

Author SHA1 Message Date
0xdeadbeer
1919712792 Repository: refactor models loading and objects 2023-11-11 19:53:11 +01:00
Kevin J
ce7aff2a11
Update README.md 2023-11-10 23:33:26 +01:00
0xdeadbeer
cb348fe1b8 Repository: refactor the project
Created object and math files for operations
specific to objects and math.
2023-11-10 23:27:20 +01:00
0xdeadbeer
68f6e2eeb8 Camera: add lock functionality
Added functionality to lock camera to an object.
Also solved the problem where the colors weren't
loading on the fragments of the initial displays
2023-11-10 19:42:17 +01:00
0xdeadbeer
0cb0461658 Objects: add scale property 2023-10-31 16:18:21 +01:00
0xdeadbeer
ec6feaf8f5 Tracing: add functionality to toggle tracing 2023-10-26 22:10:52 +02:00
0xdeadbeer
02247a6182 Repository: add README.md file 2023-10-22 14:11:36 +02:00
0xdeadbeer
a19b1370ac Tracing: implement object tracing lines
Implementation includes an 'auto-delete' system
for the traces. Each object will hold no more than
MAX_PATHS vertices for its trace. For more information
see the record_path() function
2023-10-22 13:40:22 +02:00
0xdeadbeer
957c4b6f68 Physics: implement basic gravitational attraction 2023-10-21 13:08:30 +02:00
0xdeadbeer
ac479c7a69 Main: refactor code 2023-10-16 20:48:12 +02:00
14 changed files with 849 additions and 343 deletions

1
.gitignore vendored
View File

@ -3,3 +3,4 @@ cmake-build-debug/
build/ build/
.ccls-cache/ .ccls-cache/
*.mtl *.mtl
compile_commands.json

BIN
.imgs/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 251 KiB

View File

@ -1,7 +1,7 @@
cmake_minimum_required(VERSION 3.25) cmake_minimum_required(VERSION 3.25)
project(ssts C) project(gravity C)
set(SOURCE_FILES main.c) set(SOURCE_FILES gravity.c math.c object.c)
set(HEADER_FILES ) set(HEADER_FILES )
add_executable(${PROJECT_NAME} ${HEADER_FILES} ${SOURCE_FILES}) add_executable(${PROJECT_NAME} ${HEADER_FILES} ${SOURCE_FILES})
@ -12,7 +12,7 @@ add_custom_target(assets ALL
${PROJECT_BINARY_DIR}/assets ${PROJECT_BINARY_DIR}/assets
COMMENT "Copying assets to build folder") COMMENT "Copying assets to build folder")
add_dependencies(ssts assets) add_dependencies(gravity assets)
# We need a CMAKE_DIR with some code to find external dependencies # We need a CMAKE_DIR with some code to find external dependencies
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/") set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/")

0
README
View File

42
README.md Normal file
View File

@ -0,0 +1,42 @@
<p align="center">
<img src=".imgs/icon.png" width="200"/>
</p>
# Gravity
---
Pet project simulator for interactions between matter built off of OpenGL and C.
Goals and features:
- [x] Law of gravitation
- [x] Object tracing
- [x] Toggle object tracing
- [ ] Grid
- [ ] Toggle Grid
- [x] Scaling up/down objects
- [x] Locking camera view to an object
- [ ] File format for importing scenes
- [ ] Collision
- [ ] Soft-bodies and structures
## Installation
Gravity uses CMake as its build automation system. To download and run gravity, please follow these steps:
- Clone the repository `git clone https://github.com/0xdeadbeer/gravity`
- Create a build directory `mkdir build`
- Go into the build directory `cd build`
- Generate build files `cmake ..`
- Compile project `make all`
- Run `./gravity`
- Enjoy
## Contributions
We highly encourage playing around with the software and contributing to the project.
Before opening a pull request, the contributor is expected to open an issue in which they thoroughly describe the issue (or feature) they're solving (or implementing).
## License
Gravity is licensed under the GPL-3.0 license. See the `LICENSE` file for more information.

View File

@ -1,15 +1,21 @@
#version 330 core #version 330 core
in vec4 frag_pos; in vec4 frag_pos;
in vec4 frag_normal; in vec4 frag_normal;
in vec3 object_color;
out vec4 output; out vec4 output;
void main() { void main() {
vec4 ambient = vec4(0.0, 0.2, 0.46, 1.0); vec4 norm = normalize(frag_normal);
vec4 ambient = vec4(0.7, 0.7788, 0.46, 1.0);
vec4 light_color = vec4(0.7, 0.7, 0.7, 1.0);
vec4 color = vec4(object_color.xyz, 1.0f);
vec4 light_location = vec4(0.0, 10.0, 20.0, 0.0); vec4 light_location = vec4(0.0, 100.0, 0.0, 1.0);
vec4 light_color = vec4(0.1, 0.1, 0.2, 1.0); vec4 light_direction = normalize(light_location - frag_pos);
vec4 light_distance = frag_pos - light_location; float diff = max(dot(norm.xyz, light_direction.xyz), 0.0);
float inverted_dot = -dot(frag_normal.xyz, light_distance.xyz);
output = ambient * light_color * inverted_dot; vec4 diffuse = diff * light_color;
output = color + diffuse;
} }

View File

@ -2,15 +2,20 @@
layout (location = 0) in vec3 pos; layout (location = 0) in vec3 pos;
layout (location = 1) in vec3 normal; layout (location = 1) in vec3 normal;
uniform mat4 model;
uniform mat4 view; uniform mat4 view;
uniform mat4 projection; uniform mat4 projection;
uniform mat4 translation;
uniform mat4 rotation;
uniform vec3 color;
uniform float scale;
out vec4 frag_pos; out vec4 frag_pos;
out vec4 frag_normal; out vec4 frag_normal;
out vec3 object_color;
void main() { void main() {
gl_Position = projection * view * model * vec4(pos.xyz, 1.0); gl_Position = projection * view * translation * (vec4(pos.xyz, 1.0) * vec4(scale, scale, scale, 1.0));
frag_pos = gl_Position; frag_pos = gl_Position;
frag_normal = model * vec4(normal.xyz, 1.0); frag_normal = translation * vec4(normal.xyz, 1.0);
object_color = color;
} }

481
gravity.c Normal file
View File

@ -0,0 +1,481 @@
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <cglm/cglm.h>
#include "math.h"
#include "object.h"
// global settings
float fov = 80.0f; // default fov
float fov_change = 1.0f;
vec3 camera_pos = { 0.0f, 0.0f, 0.0f };
vec3 camera_front = { 0.0f, 0.0f, -1.0f };
vec3 camera_up = { 0.0f, 1.0f, 0.0f };
struct object *camera_lock = NULL; // is camera locked to any object?
float camera_yaw = -90.0f; // x rotation
float camera_pitch = 0.0f; // y rotation
float camera_sensitivity = 0.01f;
float movement_speed = 2.0f;
GLint screen_viewport[4]; // viewport: x,y,width,height
int toggle_tracing = 0; // true or false
long added_particles = 0;
// tmp
struct model *sphere_model;
// opengl
unsigned int shader_program;
unsigned int vertex_shader;
unsigned int fragment_shader;
// shaders
const char *object_vertex_shader_location = "assets/shaders/shader.vert";
const char *object_fragment_shader_location = "assets/shaders/shader.frag";
int load_shader(const char *path, unsigned int shader) {
FILE *fp = fopen(path, "r");
int len = 0;
char *ftext;
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file '%s'\n", path);
return -1;
}
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
if (len == -1) {
fprintf(stderr, "Error: Cannot fetch length of file '%s'\n", path);
return -1;
}
fseek(fp, 0L, SEEK_SET);
ftext = (char *) malloc(len);
if (ftext == NULL) {
fprintf(stderr, "Error: Cannot allocate enough memory for file's contents '%s'\n", path);
return -1;
}
fread(ftext, sizeof(char), len, fp);
fclose(fp);
glShaderSource(shader, 1, (const char **) &ftext, &len);
glCompileShader(shader);
int success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success != GL_TRUE) {
int log_length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
char log[log_length];
glGetShaderInfoLog(shader, log_length, NULL, log);
fprintf(stderr, "Shader Compilation Error: %s\n", log);
return -1;
}
free(ftext);
return 0;
}
int load_shaders() {
glDeleteProgram(shader_program);
shader_program = glCreateProgram();
// create and load new shaders
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
if (load_shader(object_vertex_shader_location, vertex_shader) == -1) {
return -1;
}
if (load_shader(object_fragment_shader_location, fragment_shader) == -1) {
return -1;
}
// compile object shader program
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
int success;
glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
if (success != GL_TRUE) {
int log_length;
glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &log_length);
char log[log_length];
glGetProgramInfoLog(shader_program, log_length, NULL, log);
fprintf(stderr, "[object program] Shader Compilation Error: %s\n", log);
return -1;
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return 0;
}
void display() {
mat4 view;
mat4 projection;
GLint translation_uniform;
GLint view_uniform;
GLint projection_uniform;
GLint color_uniform;
GLint scale_uniform;
glClearColor(0.13f, 0.13f, 0.13f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGetIntegerv(GL_VIEWPORT, screen_viewport);
glUseProgram(shader_program);
glm_mat4_identity(view);
vec3 camera_center;
glm_vec3_add(camera_pos, camera_front, camera_center);
glm_lookat(camera_pos, camera_center, camera_up, view);
glm_mat4_identity(projection);
glm_perspective(glm_rad(fov), (float) screen_viewport[2]/(float) screen_viewport[3], 0.01f, 100000.0f, projection);
view_uniform = glGetUniformLocation(shader_program, "view");
projection_uniform = glGetUniformLocation(shader_program, "projection");
translation_uniform = glGetUniformLocation(shader_program, "translation");
color_uniform = glGetUniformLocation(shader_program, "color");
scale_uniform = glGetUniformLocation(shader_program, "scale");
glUniformMatrix4fv(view_uniform, 1, GL_FALSE, (float *) view);
glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, (float *) projection);
for (struct object *obj = objects; obj != NULL; obj = obj->next) {
mat4 translation_matrix;
glm_mat4_identity(translation_matrix);
struct model *obj_model = obj->model;
// calculate gravity
for (struct object *target = objects; target != NULL; target = target->next) {
if (target == obj) {
continue;
}
vec3 force;
glm_vec3_zero(force);
calculate_gravity(obj, target, force);
vec4 force_new;
for (int i = 0; i < 3; i++) {
force_new[i] = force[i];
}
force_new[3] = 0.0f;
float n = obj->mass;
vec4 scaler = {n,n,n,1.0f};
glm_vec4_div(force_new, scaler, force_new);
glm_vec4_add(force_new, obj->translation_force, obj->translation_force);
}
glm_vec4_add(obj->position, obj->translation_force, obj->position);
// follow object if camera locked
if (camera_lock == obj) {
glm_vec3_add(camera_pos, obj->translation_force, camera_pos);
}
// record path
if (toggle_tracing == 1) {
if (record_path(obj) == -1) {
exit(EXIT_FAILURE);
}
}
glm_translate(translation_matrix, obj->position);
glUniformMatrix4fv(translation_uniform, 1, GL_FALSE, (float *) translation_matrix);
glUniform3fv(color_uniform, 1, (float *) obj->color);
glUniform1f(scale_uniform, obj->scale);
glBindVertexArray(obj->vao);
glDrawElements(GL_TRIANGLES, obj_model->indices_num, GL_UNSIGNED_INT, (void *) 0);
glBindVertexArray(obj->pvao);
glBindBuffer(GL_ARRAY_BUFFER, obj->pbo);
glBufferData(GL_ARRAY_BUFFER, obj->paths_num*3*sizeof(float),obj->paths, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *) 0);
glEnableVertexAttribArray(0);
glm_mat4_identity(translation_matrix);
glUniformMatrix4fv(translation_uniform, 1, GL_FALSE, (float *) translation_matrix);
glUniform1f(scale_uniform, 1.0f);
glDrawArrays(GL_LINE_STRIP, 0, obj->paths_num);
}
glutPostRedisplay();
glutSwapBuffers();
}
void setup() {
// setup default mouse position
glGetIntegerv(GL_VIEWPORT, screen_viewport);
for (struct object *obj = objects; obj != NULL; obj = obj->next) {
struct model *obj_model = obj->model;
glGenVertexArrays(1, &obj->vao);
glGenVertexArrays(1, &obj->pvao);
glGenBuffers(1, &obj->vbo);
glGenBuffers(1, &obj->ebo);
glGenBuffers(1, &obj->nbo);
glGenBuffers(1, &obj->pbo);
glBindVertexArray(obj->vao);
glBindBuffer(GL_ARRAY_BUFFER,obj->vbo);
glBufferData(GL_ARRAY_BUFFER,obj_model->vertices_num*3*sizeof(float),obj_model->vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *) 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, obj->nbo);
glBufferData(GL_ARRAY_BUFFER, obj_model->normals_num*3*sizeof(float), obj_model->normals, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *) 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,obj->ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, obj_model->indices_num*sizeof(unsigned int), obj_model->indices, GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
glEnable(GL_DEPTH_TEST);
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case '\x1B':
{
exit(EXIT_SUCCESS);
break;
}
case 'r':
case 'R':
if (load_shaders() != 0) {
fprintf(stderr, "Error: reloading shaders\n");
exit(EXIT_FAILURE);
}
fprintf(stdout, "Status: successfully reloaded shaders\n");
break;
case 'a':
case 'A': {
vec3 side_scalar = { movement_speed, movement_speed, movement_speed };
vec3 camera_side;
glm_cross(camera_front, camera_up, camera_side);
glm_normalize(camera_side);
glm_vec3_mul(camera_side, side_scalar, camera_side);
glm_vec3_sub(camera_pos, camera_side, camera_pos);
break;
}
case 'd':
case 'D': {
vec3 side_scalar = { movement_speed, movement_speed, movement_speed };
vec3 camera_side;
glm_cross(camera_front, camera_up, camera_side);
glm_normalize(camera_side);
glm_vec3_mul(camera_side, side_scalar, camera_side);
glm_vec3_add(camera_pos, camera_side, camera_pos);
break;
}
case 's':
case 'S': {
vec3 front_scalar = { movement_speed, movement_speed, movement_speed};
glm_vec3_mul(front_scalar, camera_front, front_scalar);
glm_vec3_sub(camera_pos, front_scalar, camera_pos);
break;
}
case 'w':
case 'W': {
vec3 front_scalar = { movement_speed, movement_speed, movement_speed };
glm_vec3_mul(front_scalar, camera_front, front_scalar);
glm_vec3_add(camera_pos, front_scalar, camera_pos);
break;
}
case 't':
case 'T':
toggle_tracing = !toggle_tracing;
if (toggle_tracing == 0) {
break;
}
// remove all the recorded paths of objects
for (struct object *obj = objects; obj != NULL; obj = obj->next) {
obj->paths_num=0;
free(obj->paths);
obj->paths = NULL;
}
break;
case 'c':
case 'C': {
added_particles++;
fprintf(stdout, "INFO: ADDED PARTICLES COUNT %ld\n", added_particles);
struct object *a = create_object(1000000.0f, sphere_model);
float n = 0.05f;
vec4 a_pos = {frand48() * 100, frand48() * 100, -150.0f, 0.0f};
glm_vec4_add(a->position, a_pos, a->position);
//vec3 a_boost = {-10 * n, 0.0f, 0.0f};
//glm_vec3_add(a->translation_force, a_boost, a->translation_force);
setup();
break;
}
default:
break;
}
}
void mouse(int button, int state, int x, int y) {
switch (button) {
case 3:
if (fov-fov_change < 0.0f) {
break;
}
fov -= fov_change;
break;
case 4:
if (fov+fov_change > 180.0f) {
break;
}
fov += fov_change;
break;
default:
break;
}
}
int warped_pointer = 0;
int first_pointer = 1;
void mouse_motion(int x, int y) {
if (warped_pointer == 1) {
warped_pointer = 0;
return;
}
warped_pointer = 1;
glutWarpPointer((screen_viewport[2]/2), screen_viewport[3]/2);
if (first_pointer == 1) {
first_pointer = 0;
return;
}
float offset_x = (float) (x - (screen_viewport[2]/2)) * camera_sensitivity;
float offset_y = (float) (y - (screen_viewport[3]/2)) * camera_sensitivity;
camera_yaw += offset_x;
camera_pitch -= offset_y;
// limit view rotation
if (camera_pitch < -89.9f) {
camera_pitch = -89.9f;
}
if (camera_pitch > 89.9f) {
camera_pitch = 89.9f;
}
vec3 view_direction;
view_direction[0] = cos(glm_rad(camera_yaw)) * cos(glm_rad(camera_pitch));
view_direction[1] = sin(glm_rad(camera_pitch));
view_direction[2] = sin(glm_rad(camera_yaw)) * cos(glm_rad(camera_pitch));
glm_normalize_to(view_direction, camera_front);
}
int main(int argc, char **argv) {
srandom(time(NULL));
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("gravity");
GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
return EXIT_FAILURE;
}
fprintf(stdout, "Status: using with GLEW %s\n", glewGetString(GLEW_VERSION));
glutKeyboardFunc(&keyboard);
glutMouseFunc(&mouse);
glutPassiveMotionFunc(&mouse_motion);
glutDisplayFunc(&display);
if (load_shaders() != 0) {
fprintf(stderr, "Error: loading shaders\n");
return EXIT_FAILURE;
}
// scene setup
sphere_model = load_model("assets/models/sphere.obj");
if (sphere_model == NULL) {
fprintf(stderr, "Error: loading model");
return EXIT_FAILURE;
}
struct object *a = create_object(100000000.0f, sphere_model);
struct object *b = create_object(100000.0f, sphere_model);
struct object *c = create_object(10000000.0f, sphere_model);
float distance = -500.0f;
vec4 a_pos = {0.0f, 0.0f, distance, 0.0f};
glm_vec4_add(a->position, a_pos, a->position);
vec4 b_pos= {100.0f, 300.0f, distance, 0.0f};
glm_vec4_add(b->position, b_pos, b->position);
//vec4 a_pos = {0.0f, -0.0f, -150.0f, 0.0f};
//glm_vec4_add(a->position, a_pos, a->position);
// vec4 b_pos = {0.0f, -75.0f, -150.0f, 0.0f};
// glm_vec4_add(b->position, b_pos, b->position);
vec4 c_pos = {-100.0f, -400.0f, distance, 0.0f};
glm_vec4_add(c->position, c_pos, c->position);
float n = 0.05f;
vec3 b_boost = {-70*n, 0.0f, 0.0f};
glm_vec3_add(b->translation_force, b_boost , b->translation_force);
glm_vec3_add(c->translation_force, b_boost , c->translation_force);
// b->scale = 2.0f;
a->scale = 5.0f;
b->scale = 10.0f;
// camera_lock = b;
setup();
glutMainLoop();
return EXIT_SUCCESS;
}

329
main.c
View File

@ -1,329 +0,0 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <GL/glew.h>
#include <GL/freeglut.h>
#include <cglm/cglm.h>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
unsigned int vao;
unsigned int vbo;
unsigned int ebo;
unsigned int nbo;
unsigned int shader_program;
unsigned int vertex_shader;
unsigned int fragment_shader;
// shaders
const char *vertex_shader_location = "../assets/shaders/shader.vert";
const char *fragment_shader_location = "../assets/shaders/shader.frag";
// GPU data
float *vertices = NULL;
unsigned int *indices = NULL;
float *normals = NULL;
long vertices_num = 0;
long indices_num = 0;
long normals_num = 0;
// Camera / LookAt
vec3 camera_position;
vec3 world_origin;
vec3 up;
vec3 right;
vec3 forward;
int load_shader(const char *path, unsigned int shader) {
FILE *fp = fopen(path, "r");
int len = 0;
char *ftext;
if (fp == NULL) {
fprintf(stderr, "Error: Cannot open file '%s'\n", path);
return -1;
}
fseek(fp, 0L, SEEK_END);
len = ftell(fp);
if (len == -1) {
fprintf(stderr, "Error: Cannot fetch length of file '%s'\n", path);
return -1;
}
fseek(fp, 0L, SEEK_SET);
ftext = (char *) malloc(len);
if (ftext == NULL) {
fprintf(stderr, "Error: Cannot allocate enough memory for file's contents '%s'\n", path);
return -1;
}
fread(ftext, sizeof(char), len, fp);
fclose(fp);
glShaderSource(shader, 1, (const char **) &ftext, &len);
glCompileShader(shader);
int success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (success != GL_TRUE) {
int log_length;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length);
char log[log_length];
glGetShaderInfoLog(shader, log_length, NULL, log);
fprintf(stderr, "Shader Compilation Error: %s\n", log);
return -1;
}
// RUD
free(ftext);
return 0;
}
int load_model(const char *path) {
const struct aiScene *scene = aiImportFile(path, aiProcess_Triangulate);
if (scene == NULL) {
return -1;
}
// allocate enough memory
vertices = (float *) malloc(1);
for (int mesh_index = 0; mesh_index < scene->mNumMeshes; mesh_index++) {
struct aiMesh *mesh = scene->mMeshes[mesh_index];
fprintf(stdout, "Number of vertices in mesh %d: %d\n", mesh_index, mesh->mNumVertices);
// fetch vertices
for (int vertex_index = 0; vertex_index < mesh->mNumVertices; vertex_index++) {
struct aiVector3D *vertex = &(mesh->mVertices[vertex_index]);
long start = vertices_num*3;
vertices_num++;
vertices = (float *) realloc(vertices, vertices_num*3*sizeof(float));
if (vertices == NULL) {
return -1;
}
memcpy(&vertices[start], vertex, sizeof(float)*3);
}
// fetch indices
for (int face_index = 0; face_index < mesh->mNumFaces; face_index++) {
struct aiFace *face = &(mesh->mFaces[face_index]);
long start = indices_num;
indices_num += face->mNumIndices;
indices = (unsigned int *) realloc(indices, sizeof(unsigned int)*indices_num);
if (indices == NULL) {
return -1;
}
memcpy(&indices[start], face->mIndices, sizeof(unsigned int)*face->mNumIndices);
}
// fetch normals
for (int normal_index = 0; normal_index < mesh->mNumVertices; normal_index++) {
struct aiVector3D *normal = &(mesh->mNormals[normal_index]);
long start = normals_num*3;
normals_num++;
normals = (float *) realloc(normals, normals_num*3*sizeof(float));
if (normals == NULL) {
return -1;
}
memcpy(&normals[start], normal, sizeof(float)*3);
}
}
aiReleaseImport(scene);
return 0;
}
int load_shaders() {
glDeleteProgram(shader_program);
shader_program = glCreateProgram();
// create and load new shaders
vertex_shader = glCreateShader(GL_VERTEX_SHADER);
fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
if (load_shader(vertex_shader_location, vertex_shader) == -1) {
return -1;
}
if (load_shader(fragment_shader_location, fragment_shader) == -1) {
return -1;
}
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glLinkProgram(shader_program);
int success;
glGetProgramiv(shader_program, GL_LINK_STATUS, &success);
if (success != GL_TRUE) {
int log_length;
glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &log_length);
char log[log_length];
glGetProgramInfoLog(shader_program, log_length, NULL, log);
fprintf(stderr, "Shader Compilation Error: %s\n", log);
return -1;
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return 0;
}
float deg = 0;
void display() {
mat4 model;
vec3 model_axis = {1.0f, 1.0f, 0.0f};
mat4 view;
vec3 view_translate = {0.0f, 0.0f, -10.0f};
mat4 projection;
GLint viewport[4]; // viewport: x, y, width, height
GLint model_uniform;
GLint view_uniform;
GLint projection_uniform;
glClearColor(0.13f, 0.13f, 0.13f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glGetIntegerv(GL_VIEWPORT, viewport);
glm_mat4_identity(model);
glm_rotate(model, glm_rad((float)deg), model_axis);
deg += 1;
model_uniform = glGetUniformLocation(shader_program, "model");
glUniformMatrix4fv(model_uniform, 1, GL_FALSE, (float *) model);
glm_mat4_identity(view);
glm_translate(view, view_translate);
view_uniform = glGetUniformLocation(shader_program, "view");
glUniformMatrix4fv(view_uniform, 1, GL_FALSE, (float *) view);
glm_mat4_identity(projection);
glm_perspective(glm_rad(45.0f), (float)viewport[2]/(float)viewport[3], 0.01f, 100.0f, projection);
projection_uniform = glGetUniformLocation(shader_program, "projection");
glUniformMatrix4fv(projection_uniform, 1, GL_FALSE, (float *) projection);
glUseProgram(shader_program);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, indices_num, GL_UNSIGNED_INT, (void *) 0);
glutSwapBuffers();
glutPostRedisplay();
}
void keyboard(unsigned char key, int x, int y) {
switch (key) {
case '\x1B':
{
exit(EXIT_SUCCESS);
break;
}
case 'r':
case 'R':
if (load_shaders() != 0) {
fprintf(stderr, "Error: reloading shaders\n");
exit(EXIT_FAILURE);
}
fprintf(stdout, "Status: successfully reloaded shaders\n");
break;
default:
break;
}
}
int setup() {
if (load_shaders() != 0) {
fprintf(stderr, "Error: loading shaders\n");
return -1;
}
if (load_model("assets/models/sphere.obj") == -1) {
fprintf(stderr, "Error: loading model\n");
return -1;
}
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glGenBuffers(1, &ebo);
glGenBuffers(1, &nbo);
return 0;
}
void post_setup() {
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, 3*vertices_num*sizeof(float), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*) 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, nbo);
glBufferData(GL_ARRAY_BUFFER, 3*normals_num*sizeof(float), normals, GL_STATIC_DRAW);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*) 0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices_num*sizeof(unsigned int), indices, GL_STATIC_DRAW);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_DEPTH_TEST);
}
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
glutCreateWindow("Simple Space Time Simulator");
GLenum err = glewInit();
if (err != GLEW_OK) {
fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
return EXIT_FAILURE;
}
fprintf(stdout, "Status: using with GLEW %s\n", glewGetString(GLEW_VERSION));
glutKeyboardFunc(&keyboard);
glutDisplayFunc(&display);
if (setup() == -1) {
fprintf(stderr, "Error: Failed to setup\n");
return -1;
}
post_setup();
glutMainLoop();
return EXIT_SUCCESS;
}

42
math.c Normal file
View File

@ -0,0 +1,42 @@
#include "math.h"
#include "object.h"
#include <cglm/cglm.h>
float frand48(void) {
float number = (float) rand() / (float) (RAND_MAX + 1.0);
float side = rand() % 2;
if (side == 0) {
number = -number;
}
return number;
}
void calculate_gravity(struct object *src, struct object *target, vec3 force) {
vec4 v4distance;
glm_vec4_sub(target->position, src->position, v4distance);
vec3 v3distance;
glm_vec3(v4distance, v3distance);
float distance_xy = sqrt((v3distance[0] * v3distance[0]) + (v3distance[1] * v3distance[1]));
float distance_xyz = sqrt((distance_xy * distance_xy) + (v3distance[2] * v3distance[2]));
float force_scale = 4.0f;
float g = 6.67f * 1e-11f;
float top = g * src->mass * target->mass;
for (int i = 0; i < 3; i++) {
v3distance[i] = (v3distance[i] * v3distance[i] * v3distance[i]);
}
for (int i = 0; i < 3; i++) {
if (v3distance[i] == 0) {
force[i] = 0.0f;
continue;
}
force[i] = (top / (distance_xyz / (target->position[i] - src->position[i]))) * force_scale;
}
}

10
math.h Normal file
View File

@ -0,0 +1,10 @@
#ifndef MATH_H
#define MATH_H
#include "object.h"
#include <cglm/cglm.h>
float frand48(void);
void calculate_gravity(struct object *src, struct object *target, vec3 force);
#endif

196
object.c Normal file
View File

@ -0,0 +1,196 @@
#include "object.h"
#include "math.h"
#include <math.h>
#include <assimp/cimport.h>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
struct object *objects;
/*int load_model_to_object(const char *path, struct object *obj) {
const struct aiScene *scene = aiImportFile(path, aiProcess_Triangulate);
if (scene == NULL) {
fprintf(stderr, "Error: failed importing file from path '%s'", path);
}
for (int mesh_index = 0; mesh_index < scene->mNumMeshes; mesh_index++) {
struct aiMesh *mesh = scene->mMeshes[mesh_index];
// fetch vertices
for (int vertex_index = 0; vertex_index < mesh->mNumVertices; vertex_index++) {
struct aiVector3D *vertex = &(mesh->mVertices[vertex_index]);
long start = obj->vertices_num*3;
obj->vertices_num++;
obj->vertices = (float *) realloc(obj->vertices, obj->vertices_num*3*sizeof(float));
if (obj->vertices == NULL) {
return -1;
}
memcpy(&obj->vertices[start], vertex, sizeof(float)*3);
}
// fetch indices
for (int face_index = 0; face_index < mesh->mNumFaces; face_index++) {
struct aiFace *face = &(mesh->mFaces[face_index]);
long start = obj->indices_num;
obj->indices_num += face->mNumIndices;
obj->indices = (unsigned int *) realloc(obj->indices, sizeof(unsigned int)*obj->indices_num);
if (obj->indices == NULL) {
return -1;
}
memcpy(&obj->indices[start], face->mIndices, sizeof(unsigned int)*face->mNumIndices);
}
// fetch normals
for (int normal_index = 0; normal_index < mesh->mNumVertices; normal_index++) {
struct aiVector3D *normal = &(mesh->mNormals[normal_index]);
long start = obj->normals_num*3;
obj->normals_num++;
obj->normals = (float *) realloc(obj->normals,obj->normals_num*3*sizeof(float));
if (obj->normals == NULL) {
return -1;
}
memcpy(&obj->normals[start], normal, sizeof(float)*3);
}
}
aiReleaseImport(scene);
return 0;
}*/
struct model *load_model(const char *path) {
struct model *new_model = (struct model *) calloc(1, sizeof(struct model));
const struct aiScene *scene = aiImportFile(path, aiProcess_Triangulate);
if (scene == NULL) {
fprintf(stderr, "Error: failed importing file from path '%s'", path);
}
for (int mesh_index = 0; mesh_index < scene->mNumMeshes; mesh_index++) {
struct aiMesh *mesh = scene->mMeshes[mesh_index];
// fetch vertices
for (int vertex_index = 0; vertex_index < mesh->mNumVertices; vertex_index++) {
struct aiVector3D *vertex = &(mesh->mVertices[vertex_index]);
long start = new_model->vertices_num*3;
new_model->vertices_num++;
new_model->vertices = (float *) realloc(new_model->vertices, new_model->vertices_num*3*sizeof(float));
if (new_model->vertices == NULL) {
fprintf(stderr, "Error: failed allocating memory for vertices\n");
goto error;
}
memcpy(&new_model->vertices[start], vertex, sizeof(float)*3);
}
// fetch indices
for (int face_index = 0; face_index < mesh->mNumFaces; face_index++) {
struct aiFace *face = &(mesh->mFaces[face_index]);
long start = new_model->indices_num;
new_model->indices_num += face->mNumIndices;
new_model->indices = (unsigned int *) realloc(new_model->indices, sizeof(unsigned int)*new_model->indices_num);
if (new_model->indices == NULL) {
fprintf(stderr, "Error: failed allocating memory for indices\n");
goto error;
}
memcpy(&new_model->indices[start], face->mIndices, sizeof(unsigned int)*face->mNumIndices);
}
// fetch normals
for (int normal_index = 0; normal_index < mesh->mNumVertices; normal_index++) {
struct aiVector3D *normal = &(mesh->mNormals[normal_index]);
long start = new_model->normals_num*3;
new_model->normals_num++;
new_model->normals = (float *) realloc(new_model->normals, new_model->normals_num*3*sizeof(float));
if (new_model->normals == NULL) {
fprintf(stderr, "Error: failed allocating memory for normals\n");
goto error;
}
memcpy(&new_model->normals[start], normal, sizeof(float)*3);
}
}
return new_model;
error:
aiReleaseImport(scene);
free(new_model->vertices);
free(new_model->indices);
free(new_model->normals);
free(new_model);
return NULL;
}
int record_path(struct object *obj) {
if (obj->paths_num <= obj->paths_max) {
obj->paths = (float *) reallocarray(obj->paths, (obj->paths_num+1)*3, sizeof(float));
}
if (obj->paths == NULL) {
fprintf(stderr, "Error: failed allocating memory for paths of object\n");
return -1;
}
memcpy(obj->paths+(obj->paths_num*3), obj->position, 3*sizeof(float));
if (obj->paths_num < obj->paths_max) {
obj->paths_num++;
goto end;
}
// pop first element
memmove(obj->paths, &obj->paths[3], (obj->paths_num)*3*sizeof(float));
end:
return 0;
}
struct object *create_object(float mass, struct model *model) {
struct object *new_object = (struct object *) calloc(1, sizeof(struct object));
if (new_object == NULL) {
fprintf(stderr, "Error: failed allocating memory for a new object\n");
goto error;
}
// initialize default values
new_object->mass = mass;
new_object->scale = 1.0f;
new_object->paths_max = MAX_PATHS;
new_object->model = model;
glm_vec4_one(new_object->position);
glm_vec3_one(new_object->color);
// choose random color
for (int i = 0; i < 3; i++) {
new_object->color[i] = 0.5f + (fabs(frand48()) / 2);
}
if (objects == NULL) {
objects = new_object;
goto end;
}
struct object *previous_object = objects;
new_object->next = previous_object;
objects = new_object;
end:
return new_object;
error:
return NULL;
}

48
object.h Normal file
View File

@ -0,0 +1,48 @@
#ifndef OBJECT_H
#define OBJECT_H
#include <cglm/cglm.h>
#define MAX_PATHS 2000
struct model {
float *vertices;
unsigned int *indices;
float *normals;
long vertices_num;
long indices_num;
long normals_num;
};
struct object {
vec4 translation_force;
vec4 position;
vec3 color;
float mass;
void *next;
float *paths;
int paths_num;
int paths_max;
struct model *model;
float scale;
unsigned int vao; // array object for the actual object
unsigned int vbo; // buffer for vertices
unsigned int ebo; // buffer for indices
unsigned int nbo; // buffer for normals
unsigned int pvao; // array object for paths
unsigned int pbo; // buffer for paths
};
extern struct object *objects;
//int load_model_to_object(const char *path, struct object *obj);
struct model *load_model(const char *path);
int record_path(struct object *obj);
struct object *create_object(float mass, struct model *model);
#endif

4
scenes/planets.grv Normal file
View File

@ -0,0 +1,4 @@
#mass,model_filename,x_pos,y_pos,z_pos,x_boost,y_boost,z_boost
1.0,"sphere.obj",0.0,-50.0,-150.0,-0.5,0.0,-0.5
10000000.0,"sphere.obj",0.0,-20.0,-200.0,0.05,0.05,0.05