From be6d237b9ebbe245de4384c17b84e75dab0f4981 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 29 Mar 2019 20:22:50 +0100 Subject: Review models examples --- examples/models/models_cubicmap.c | 2 +- examples/models/models_heightmap.c | 2 +- examples/models/models_material_pbr.c | 14 +++++++------- examples/models/models_mesh_generation.c | 13 ++++++++++++- examples/models/models_mesh_picking.c | 6 +++--- examples/models/models_obj_loading.c | 2 +- examples/models/models_obj_viewer.c | 18 +++++++++--------- examples/models/models_skybox.c | 6 +++--- examples/models/models_yaw_pitch_roll.c | 6 +++--- 9 files changed, 40 insertions(+), 29 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_cubicmap.c b/examples/models/models_cubicmap.c index c8d62c46..ac24188e 100644 --- a/examples/models/models_cubicmap.c +++ b/examples/models/models_cubicmap.c @@ -31,7 +31,7 @@ int main() // NOTE: By default each cube is mapped to one part of texture atlas Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture - model.material.maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture + model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position diff --git a/examples/models/models_heightmap.c b/examples/models/models_heightmap.c index d131b127..e0475f18 100644 --- a/examples/models/models_heightmap.c +++ b/examples/models/models_heightmap.c @@ -29,7 +29,7 @@ int main() Mesh mesh = GenMeshHeightmap(image, (Vector3){ 16, 8, 16 }); // Generate heightmap mesh (RAM and VRAM) Model model = LoadModelFromMesh(mesh); // Load model from generated mesh - model.material.maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture + model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture Vector3 mapPosition = { -8.0f, 0.0f, -8.0f }; // Define model position UnloadImage(image); // Unload heightmap image from RAM, already uploaded to VRAM diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index f93c7a68..adb4762b 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -38,16 +38,16 @@ int main() // Load model and PBR material Model model = LoadModel("resources/pbr/trooper.obj"); - MeshTangents(&model.mesh); - model.material = LoadMaterialPBR((Color){ 255, 255, 255, 255 }, 1.0f, 1.0f); + MeshTangents(&model.meshes[0]); + model.materials[0] = LoadMaterialPBR((Color){ 255, 255, 255, 255 }, 1.0f, 1.0f); // Define lights attributes // NOTE: Shader is passed to every light on creation to define shader bindings internally Light lights[MAX_LIGHTS] = { - CreateLight(LIGHT_POINT, (Vector3){ LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 0, 255 }, model.material.shader), - CreateLight(LIGHT_POINT, (Vector3){ 0.0f, LIGHT_HEIGHT, LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 255, 0, 255 }, model.material.shader), - CreateLight(LIGHT_POINT, (Vector3){ -LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 0, 255, 255 }, model.material.shader), - CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.material.shader) + CreateLight(LIGHT_POINT, (Vector3){ LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 0, 255 }, model.materials[0].shader), + CreateLight(LIGHT_POINT, (Vector3){ 0.0f, LIGHT_HEIGHT, LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 255, 0, 255 }, model.materials[0].shader), + CreateLight(LIGHT_POINT, (Vector3){ -LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 0, 255, 255 }, model.materials[0].shader), + CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.materials[0].shader) }; SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode @@ -64,7 +64,7 @@ int main() // Send to material PBR shader camera view position float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z }; - SetShaderValue(model.material.shader, model.material.shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3); + SetShaderValue(model.materials[0].shader, model.materials[0].shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3); //---------------------------------------------------------------------------------- // Draw diff --git a/examples/models/models_mesh_generation.c b/examples/models/models_mesh_generation.c index d64889bd..2b4b75ab 100644 --- a/examples/models/models_mesh_generation.c +++ b/examples/models/models_mesh_generation.c @@ -39,7 +39,7 @@ int main() models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f)); // Set checked texture as default diffuse component for all models material - for (int i = 0; i < NUM_MODELS; i++) models[i].material.maps[MAP_DIFFUSE].texture = texture; + for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MAP_DIFFUSE].texture = texture; // Define the camera to look into our 3d world Camera camera = {{ 5.0f, 5.0f, 5.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; @@ -65,6 +65,17 @@ int main() { currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures } + + if (IsKeyPressed(KEY_RIGHT)) + { + currentModel++; + if (currentModel >= NUM_MODELS) currentModel = 0; + } + else if (IsKeyPressed(KEY_LEFT)) + { + currentModel--; + if (currentModel < 0) currentModel = NUM_MODELS - 1; + } //---------------------------------------------------------------------------------- // Draw diff --git a/examples/models/models_mesh_picking.c b/examples/models/models_mesh_picking.c index 9b12e98c..42028829 100644 --- a/examples/models/models_mesh_picking.c +++ b/examples/models/models_mesh_picking.c @@ -26,7 +26,7 @@ int main() // Define the camera to look into our 3d world Camera camera = { 0 }; - camera.position = (Vector3){ 20.0f, 20.0f, 20.0f }; // Camera position + camera.position = (Vector3){ 20.0f, 20.0f, 20.0f }; // Camera position camera.target = (Vector3){ 0.0f, 8.0f, 0.0f }; // Camera looking at point camera.up = (Vector3){ 0.0f, 1.6f, 0.0f }; // Camera up vector (rotation towards target) camera.fovy = 45.0f; // Camera field-of-view Y @@ -36,10 +36,10 @@ int main() Model tower = LoadModel("resources/models/turret.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load model texture - tower.material.maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture + tower.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position - BoundingBox towerBBox = MeshBoundingBox(tower.mesh); // Get mesh bounding box + BoundingBox towerBBox = MeshBoundingBox(tower.meshes[0]); // Get mesh bounding box bool hitMeshBBox = false; bool hitTriangle = false; diff --git a/examples/models/models_obj_loading.c b/examples/models/models_obj_loading.c index 7ec2d3f0..0251fd3e 100644 --- a/examples/models/models_obj_loading.c +++ b/examples/models/models_obj_loading.c @@ -30,7 +30,7 @@ int main() Model model = LoadModel("resources/models/castle.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/castle_diffuse.png"); // Load model texture - model.material.maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture + model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position SetTargetFPS(60); // Set our game to run at 60 frames-per-second diff --git a/examples/models/models_obj_viewer.c b/examples/models/models_obj_viewer.c index 15f79549..ffa609e0 100644 --- a/examples/models/models_obj_viewer.c +++ b/examples/models/models_obj_viewer.c @@ -27,13 +27,13 @@ int main() Model model = LoadModel("resources/models/turret.obj"); // Load default model obj Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load default model texture - model.material.maps[MAP_DIFFUSE].texture = texture; // Bind texture to model + model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model - Vector3 position = { 0.0, 0.0, 0.0 }; // Set model position - BoundingBox bounds = MeshBoundingBox(model.mesh); // Set model bounds - bool selected = false; // Selected object flag + Vector3 position = { 0.0, 0.0, 0.0 }; // Set model position + BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds + bool selected = false; // Selected object flag - SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode + SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode char objFilename[64] = "turret.obj"; @@ -54,15 +54,15 @@ int main() { if (IsFileExtension(droppedFiles[0], ".obj")) { - UnloadMesh(&model.mesh); - model.mesh = LoadMesh(droppedFiles[0]); - bounds = MeshBoundingBox(model.mesh); + UnloadMesh(&model.meshes[0]); + model.meshes[0] = LoadMesh(droppedFiles[0]); + bounds = MeshBoundingBox(model.meshes[0]); } else if (IsFileExtension(droppedFiles[0], ".png")) { UnloadTexture(texture); texture = LoadTexture(droppedFiles[0]); - model.material.maps[MAP_DIFFUSE].texture = texture; + model.materials[0].maps[MAP_DIFFUSE].texture = texture; } strcpy(objFilename, GetFileName(droppedFiles[0])); diff --git a/examples/models/models_skybox.c b/examples/models/models_skybox.c index c7f76ecf..759c79c6 100644 --- a/examples/models/models_skybox.c +++ b/examples/models/models_skybox.c @@ -29,8 +29,8 @@ int main() // Load skybox shader and set required locations // NOTE: Some locations are automatically set at shader loading - skybox.material.shader = LoadShader("resources/shaders/skybox.vs", "resources/shaders/skybox.fs"); - SetShaderValue(skybox.material.shader, GetShaderLocation(skybox.material.shader, "environmentMap"), (int[1]){ MAP_CUBEMAP }, UNIFORM_INT); + skybox.materials[0].shader = LoadShader("resources/shaders/skybox.vs", "resources/shaders/skybox.fs"); + SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MAP_CUBEMAP }, UNIFORM_INT); // Load cubemap shader and setup required shader locations Shader shdrCubemap = LoadShader("resources/shaders/cubemap.vs", "resources/shaders/cubemap.fs"); @@ -41,7 +41,7 @@ int main() // Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture // NOTE: New texture is generated rendering to texture, shader computes the sphre->cube coordinates mapping - skybox.material.maps[MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, texHDR, 512); + skybox.materials[0].maps[MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, texHDR, 512); UnloadTexture(texHDR); // Texture not required anymore, cubemap already generated UnloadShader(shdrCubemap); // Unload cubemap generation shader, not required anymore diff --git a/examples/models/models_yaw_pitch_roll.c b/examples/models/models_yaw_pitch_roll.c index 88b0a610..7eaaf0be 100644 --- a/examples/models/models_yaw_pitch_roll.c +++ b/examples/models/models_yaw_pitch_roll.c @@ -37,10 +37,10 @@ int main() RenderTexture2D framebuffer = LoadRenderTexture(192, 192); // Model loading - Model model = LoadModel("resources/plane.obj"); // Load OBJ model - model.material.maps[MAP_DIFFUSE].texture = LoadTexture("resources/plane_diffuse.png"); // Set map diffuse texture + Model model = LoadModel("resources/plane.obj"); // Load OBJ model + model.materials[0].maps[MAP_DIFFUSE].texture = LoadTexture("resources/plane_diffuse.png"); // Set map diffuse texture - GenTextureMipmaps(&model.material.maps[MAP_DIFFUSE].texture); + GenTextureMipmaps(&model.materials[0].maps[MAP_DIFFUSE].texture); Camera camera = { 0 }; camera.position = (Vector3){ 0.0f, 60.0f, -120.0f };// Camera position perspective -- cgit v1.2.3 From 26fb2e0f3a5047dd77bfea82543a341aa25dda7a Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 1 Apr 2019 00:15:14 +0200 Subject: Update cube.obj --- examples/models/resources/models/cube.obj | 44 +++++-------------------------- 1 file changed, 7 insertions(+), 37 deletions(-) (limited to 'examples/models') diff --git a/examples/models/resources/models/cube.obj b/examples/models/resources/models/cube.obj index 0e9d6597..bf7e3bee 100644 --- a/examples/models/resources/models/cube.obj +++ b/examples/models/resources/models/cube.obj @@ -1,7 +1,7 @@ # reference material -mtllib myCube.mtl +#mtllib cube.mtl -# object Pau_Box +# object box # vertex (XZY) v 5.5 0 1.5 @@ -14,85 +14,55 @@ v 5.5 3 -1.5 v 8.5 3 -1.5 # normals (XYZ) -# red vn 0 -1 0 -#blue vn 0 1 0 -#top vn 0 0 1 -#yellow vn 1 0 0 -#bottom vn 0 0 -1 -#green vn -1 0 0 - # UVs (XY) -# yellow (1234) vt 0.5 0 0 vt 1 0 0 vt 1 0.5 0 vt 0.5 0.5 0 -# red (5678) vt 0.5 0.5 0 vt 1 0.5 0 vt 0.5 1 0 vt 1 1 0 -#bottom (9101112) vt 0 0.5 0 vt 1 0.5 0 vt 1 0 0 vt 0 0 0 -#top (13141516) vt 0 0.5 0 vt 1 0.5 0 vt 1 1 0 vt 0 1 0 -#green (17181920) vt 0.5 0 0 vt 0 0 0 vt 0 0.5 0 vt 0.5 0.5 0 -#blue (21222324) vt 0 0.5 0 vt 0.5 0.5 0 vt 0.5 1 0 vt 0 1 0 # merger -g Pau_Box +g box # reference material -usemtl Material_1 - -# bottom -f 1/9/1 3/10/1 4/11/1 -f 4/11/1 2/12/1 1/9/1 +#usemtl mat01 -# top +# faces +f 1/9/1 3/10/1 4/11/1 +f 4/11/1 2/12/1 1/9/1 f 5/13/2 6/14/2 8/15/2 f 8/15/2 7/16/2 5/13/2 - -# front-yellow f 1/17/6 2/18/6 6/19/6 f 6/19/6 5/20/6 1/17/6 - -# right-blue f 2/6/1 4/5/1 8/7/1 f 8/7/1 6/8/1 2/6/1 - -# back-green f 4/2/3 3/1/3 7/4/3 f 7/4/3 8/3/3 4/2/3 - -# left-red f 3/22/5 1/21/5 5/24/5 f 5/24/5 7/23/5 3/22/5 - - - - - - - -- cgit v1.2.3 From 38a13b76d13c6e4f6f6c02bfd63900de56de4a42 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:13:42 +0200 Subject: Corrected issue with LoadMesh() --- examples/models/models_obj_loading.c | 2 +- examples/models/models_obj_viewer.c | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_obj_loading.c b/examples/models/models_obj_loading.c index 0251fd3e..74e7d08a 100644 --- a/examples/models/models_obj_loading.c +++ b/examples/models/models_obj_loading.c @@ -59,7 +59,7 @@ int main() DrawGizmo(position); // Draw gizmo EndMode3D(); - + DrawText("(c) Castle 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawFPS(10, 10); diff --git a/examples/models/models_obj_viewer.c b/examples/models/models_obj_viewer.c index ffa609e0..0581df34 100644 --- a/examples/models/models_obj_viewer.c +++ b/examples/models/models_obj_viewer.c @@ -28,11 +28,11 @@ int main() Model model = LoadModel("resources/models/turret.obj"); // Load default model obj Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load default model texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model - + Vector3 position = { 0.0, 0.0, 0.0 }; // Set model position - BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds + BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds bool selected = false; // Selected object flag - + SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode char objFilename[64] = "turret.obj"; @@ -49,13 +49,13 @@ int main() { int count = 0; char **droppedFiles = GetDroppedFiles(&count); - + if (count == 1) { if (IsFileExtension(droppedFiles[0], ".obj")) { - UnloadMesh(&model.meshes[0]); - model.meshes[0] = LoadMesh(droppedFiles[0]); + for (int i = 0; i < model.meshCount; i++) UnloadMesh(&model.meshes[i]); + model.meshes = LoadMeshes(droppedFiles[0], &model.meshCount); bounds = MeshBoundingBox(model.meshes[0]); } else if (IsFileExtension(droppedFiles[0], ".png")) @@ -67,12 +67,12 @@ int main() strcpy(objFilename, GetFileName(droppedFiles[0])); } - + ClearDroppedFiles(); // Clear internal buffers } - + UpdateCamera(&camera); - + // Select model on mouse click if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) { @@ -93,21 +93,21 @@ int main() DrawModel(model, position, 1.0f, WHITE); // Draw 3d model with texture DrawGrid(20.0, 10.0); // Draw a grid - + if (selected) DrawBoundingBox(bounds, GREEN); - + EndMode3D(); - + DrawText("Free camera default controls:", 10, 20, 10, DARKGRAY); DrawText("- Mouse Wheel to Zoom in-out", 20, 40, 10, GRAY); DrawText("- Mouse Wheel Pressed to Pan", 20, 60, 10, GRAY); DrawText("- Alt + Mouse Wheel Pressed to Rotate", 20, 80, 10, GRAY); DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 20, 100, 10, GRAY); - + DrawText("Drag & drop .obj/.png to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY); DrawText(FormatText("Current file: %s", objFilename), 250, GetScreenHeight() - 20, 10, GRAY); if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN); - + DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); EndDrawing(); @@ -119,7 +119,7 @@ int main() UnloadModel(model); // Unload model ClearDroppedFiles(); // Clear internal buffers - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- -- cgit v1.2.3 From 92733d6695e0cdab3b42972f2cd6ed48d98ec689 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 13:15:56 +0200 Subject: BIG UPDATE: New models functions for animations! Multiple functions added and some reviewed to adapt to the new multi-mesh, multi-material and animated models. --- examples/models/models_animation.c | 101 +++ examples/models/resources/guy/guy.blend | Bin 0 -> 665304 bytes examples/models/resources/guy/guy.iqm | Bin 0 -> 39408 bytes examples/models/resources/guy/guyanim.iqm | Bin 0 -> 18244 bytes examples/models/resources/guy/guytex.png | Bin 0 -> 302388 bytes examples/others/iqm_loader/models_iqm_animation.c | 98 --- examples/others/iqm_loader/resources/guy.blend | Bin 665304 -> 0 bytes examples/others/iqm_loader/resources/guy.iqm | Bin 39408 -> 0 bytes examples/others/iqm_loader/resources/guyanim.iqm | Bin 18244 -> 0 bytes examples/others/iqm_loader/resources/guytex.png | Bin 302388 -> 0 bytes examples/others/iqm_loader/riqm.h | 739 +--------------------- src/models.c | 652 ++++++++++++++----- src/raylib.h | 33 +- 13 files changed, 617 insertions(+), 1006 deletions(-) create mode 100644 examples/models/models_animation.c create mode 100644 examples/models/resources/guy/guy.blend create mode 100644 examples/models/resources/guy/guy.iqm create mode 100644 examples/models/resources/guy/guyanim.iqm create mode 100644 examples/models/resources/guy/guytex.png delete mode 100644 examples/others/iqm_loader/models_iqm_animation.c delete mode 100644 examples/others/iqm_loader/resources/guy.blend delete mode 100644 examples/others/iqm_loader/resources/guy.iqm delete mode 100644 examples/others/iqm_loader/resources/guyanim.iqm delete mode 100644 examples/others/iqm_loader/resources/guytex.png (limited to 'examples/models') diff --git a/examples/models/models_animation.c b/examples/models/models_animation.c new file mode 100644 index 00000000..a75241b3 --- /dev/null +++ b/examples/models/models_animation.c @@ -0,0 +1,101 @@ +/******************************************************************************************* +* +* raylib [models] example - Load 3d model with animations and play them +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2019 Ramon Santamaria (@raysan5) and @culacant +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation"); + + // Define the camera to look into our 3d world + Camera camera = { 0 }; + camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.type = CAMERA_PERSPECTIVE; // Camera mode type + + + Model model = LoadModel("resources/guy/guy.iqm"); // Load the animated model mesh and basic data + Texture2D texture = LoadTexture("resources/guy/guytex.png"); // Load model texture and set material + SetMaterialTexture(&model.materials[0], MAP_DIFFUSE, texture); // Set model material map texture + + Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position + + // Load animation data + int animsCount = 0; + ModelAnimation *anims = LoadModelAnimations("resources/guy/guyanim.iqm", &animsCount); + int animFrameCounter = 0; + + SetCameraMode(camera, CAMERA_FREE); // Set free camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); + + // Play animation when spacebar is held down + if (IsKeyDown(KEY_SPACE)) + { + animFrameCounter++; + UpdateModelAnimation(model, anims[0], animFrameCounter); + if (animFrameCounter >= anims[0].frameCount) animFrameCounter = 0; + } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModelEx(model, position, (Vector3){ 1.0f, 0.0f, 0.0f }, -90.0f, (Vector3){ 1.0f, 1.0f, 1.0f }, WHITE); + + for (int i = 0; i < model.boneCount; i++) + { + DrawCube(anims[0].framePoses[animFrameCounter][i].translation, 0.2f, 0.2f, 0.2f, RED); + } + + DrawGrid(10, 1.0f); // Draw a grid + + EndMode3D(); + + DrawText("PRESS SPACE to PLAY MODEL ANIMATION", 10, 10, 20, MAROON); + DrawText("(c) Guy IQM 3D model by @culacant", screenWidth - 200, screenHeight - 20, 10, GRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + // Unload model animations data + for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); + + UnloadModel(model); // Unload model + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/models/resources/guy/guy.blend b/examples/models/resources/guy/guy.blend new file mode 100644 index 00000000..3880467d Binary files /dev/null and b/examples/models/resources/guy/guy.blend differ diff --git a/examples/models/resources/guy/guy.iqm b/examples/models/resources/guy/guy.iqm new file mode 100644 index 00000000..36bed5e0 Binary files /dev/null and b/examples/models/resources/guy/guy.iqm differ diff --git a/examples/models/resources/guy/guyanim.iqm b/examples/models/resources/guy/guyanim.iqm new file mode 100644 index 00000000..824a68a3 Binary files /dev/null and b/examples/models/resources/guy/guyanim.iqm differ diff --git a/examples/models/resources/guy/guytex.png b/examples/models/resources/guy/guytex.png new file mode 100644 index 00000000..7f813552 Binary files /dev/null and b/examples/models/resources/guy/guytex.png differ diff --git a/examples/others/iqm_loader/models_iqm_animation.c b/examples/others/iqm_loader/models_iqm_animation.c deleted file mode 100644 index 18dd8577..00000000 --- a/examples/others/iqm_loader/models_iqm_animation.c +++ /dev/null @@ -1,98 +0,0 @@ -/******************************************************************************************* -* -* raylib [models] example - Load IQM 3d model with animations and play them -* -* This example has been created using raylib 2.0 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2018 @culacant and @raysan5 -* -********************************************************************************************/ - -#include "raylib.h" - -#define RIQM_IMPLEMENTATION -#include "riqm.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [models] example - iqm animation"); - - // Define the camera to look into our 3d world - Camera camera = { 0 }; - camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position - camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point - camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) - camera.fovy = 45.0f; // Camera field-of-view Y - camera.type = CAMERA_PERSPECTIVE; // Camera mode type - - // Load the animated model mesh and basic data - AnimatedModel model = LoadAnimatedModel("resources/guy.iqm"); - - // Load model texture and set material - // NOTE: There is only 1 mesh and 1 material (both at index 0), thats what the 2 0's are - model = AnimatedModelAddTexture(model, "resources/guytex.png"); // REPLACE! - model = SetMeshMaterial(model, 0, 0); // REPLACE! - - // Load animation data - Animation anim = LoadAnimationFromIQM("resources/guyanim.iqm"); - - int animFrameCounter = 0; - - SetCameraMode(camera, CAMERA_FREE); // Set free camera mode - - SetTargetFPS(60); // Set our game to run at 60 frames-per-second - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - UpdateCamera(&camera); - - // Play animation when spacebar is held down - if (IsKeyDown(KEY_SPACE)) - { - animFrameCounter++; - AnimateModel(model, anim, animFrameCounter); // Animate the model with animation data and frame - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - BeginMode3D(camera); - - DrawAnimatedModel(model, Vector3Zero(), 1.0f, WHITE); // Draw animated model - - DrawGrid(10, 1.0f); // Draw a grid - - EndMode3D(); - - DrawText("PRESS SPACE to PLAY IQM MODEL ANIMATION", 10, 10, 20, MAROON); - - DrawText("(c) Guy IQM 3D model by @culacant", screenWidth - 200, screenHeight - 20, 10, GRAY); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - UnloadAnimation(anim); // Unload animation data - UnloadAnimatedModel(model); // Unload animated model - - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} diff --git a/examples/others/iqm_loader/resources/guy.blend b/examples/others/iqm_loader/resources/guy.blend deleted file mode 100644 index 3880467d..00000000 Binary files a/examples/others/iqm_loader/resources/guy.blend and /dev/null differ diff --git a/examples/others/iqm_loader/resources/guy.iqm b/examples/others/iqm_loader/resources/guy.iqm deleted file mode 100644 index 36bed5e0..00000000 Binary files a/examples/others/iqm_loader/resources/guy.iqm and /dev/null differ diff --git a/examples/others/iqm_loader/resources/guyanim.iqm b/examples/others/iqm_loader/resources/guyanim.iqm deleted file mode 100644 index 824a68a3..00000000 Binary files a/examples/others/iqm_loader/resources/guyanim.iqm and /dev/null differ diff --git a/examples/others/iqm_loader/resources/guytex.png b/examples/others/iqm_loader/resources/guytex.png deleted file mode 100644 index 7f813552..00000000 Binary files a/examples/others/iqm_loader/resources/guytex.png and /dev/null differ diff --git a/examples/others/iqm_loader/riqm.h b/examples/others/iqm_loader/riqm.h index 694e3a95..41ef8a14 100644 --- a/examples/others/iqm_loader/riqm.h +++ b/examples/others/iqm_loader/riqm.h @@ -49,67 +49,13 @@ // Types and Structures Definition //---------------------------------------------------------------------------------- -#define JOINT_NAME_LENGTH 32 // Joint name string length -#define MESH_NAME_LENGTH 32 // Mesh name string length - -typedef struct Joint { - char name[JOINT_NAME_LENGTH]; - int parent; -} Joint; - -typedef struct Pose { - Vector3 translation; - Quaternion rotation; - Vector3 scale; -} Pose; - -typedef struct Animation { - int jointCount; // Number of joints (bones) - Joint *joints; // Joints array - // NOTE: Joints in anims do not have names - - int frameCount; // Number of animation frames - float framerate; // Frame change speed - - Pose **framepose; // Poses array by frame (and one pose by joint) -} Animation; - -// Animated Model type -typedef struct AnimatedModel { - Matrix transform; // Local transform matrix - - int meshCount; // Number of meshes - Mesh *meshes; // Meshes array - - int materialCount; // Number of materials - Material *materials; // Materials array - - int *meshMaterialId; // Mesh materials ids - - // Animation required data - int jointCount; // Number of joints (and keyposes) - Joint *joints; // Mesh joints (bones) - Pose *basepose; // Mesh base-poses by joint -} AnimatedModel; +#define BONE_NAME_LENGTH 32 // BoneInfo name string length +#define MESH_NAME_LENGTH 32 // Mesh name string length //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -// Loading/Unloading functions -RIQMDEF AnimatedModel LoadAnimatedModel(const char *filename); -RIQMDEF void UnloadAnimatedModel(AnimatedModel model); -RIQMDEF Animation LoadAnimation(const char *filename); -RIQMDEF void UnloadAnimation(Animation anim); - -RIQMDEF AnimatedModel AnimatedModelAddTexture(AnimatedModel model, const char *filename); // GENERIC! -RIQMDEF AnimatedModel SetMeshMaterial(AnimatedModel model, int meshid, int textureid); // GENERIC! - -// Usage functionality -RIQMDEF bool CheckSkeletonsMatch(AnimatedModel model, Animation anim); -RIQMDEF void AnimateModel(AnimatedModel model, Animation anim, int frame); -RIQMDEF void DrawAnimatedModel(AnimatedModel model, Vector3 position, float scale, Color tint); -RIQMDEF void DrawAnimatedModelEx(AnimatedModel model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint); #endif // RIQM_H @@ -133,90 +79,6 @@ RIQMDEF void DrawAnimatedModelEx(AnimatedModel model, Vector3 position, Vector3 //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -#define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number -#define IQM_VERSION 2 // only IQM version 2 supported -#define ANIMJOINTNAME "ANIMJOINT" // default joint name (used in Animation) - -//---------------------------------------------------------------------------------- -// Types and Structures Definition -//---------------------------------------------------------------------------------- -// iqm file structs -typedef struct IQMHeader { - char magic[16]; - unsigned int version; - unsigned int filesize; - unsigned int flags; - unsigned int num_text, ofs_text; - unsigned int num_meshes, ofs_meshes; - unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; - unsigned int num_triangles, ofs_triangles, ofs_adjacency; - unsigned int num_joints, ofs_joints; - unsigned int num_poses, ofs_poses; - unsigned int num_anims, ofs_anims; - unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; - unsigned int num_comment, ofs_comment; - unsigned int num_extensions, ofs_extensions; -} IQMHeader; - -typedef struct IQMMesh { - unsigned int name; - unsigned int material; - unsigned int first_vertex, num_vertexes; - unsigned int first_triangle, num_triangles; -} IQMMesh; - -typedef struct IQMTriangle { - unsigned int vertex[3]; -} IQMTriangle; - -typedef struct IQMAdjacency { // adjacency unused by default - unsigned int triangle[3]; -} IQMAdjacency; - -typedef struct IQMJoint { - unsigned int name; - int parent; - float translate[3], rotate[4], scale[3]; -} IQMJoint; - -typedef struct IQMPose { - int parent; - unsigned int mask; - float channeloffset[10]; - float channelscale[10]; -} IQMPose; - -typedef struct IQMAnim { - unsigned int name; - unsigned int first_frame, num_frames; - float framerate; - unsigned int flags; -} IQMAnim; - -typedef struct IQMVertexArray { - unsigned int type; - unsigned int flags; - unsigned int format; - unsigned int size; - unsigned int offset; -} IQMVertexArray; - -typedef struct IQMBounds { // bounds unused by default - float bbmin[3], bbmax[3]; - float xyradius, radius; -} IQMBounds; - - -typedef enum { - IQM_POSITION = 0, - IQM_TEXCOORD = 1, - IQM_NORMAL = 2, - IQM_TANGENT = 3, // tangents unused by default - IQM_BLENDINDEXES = 4, - IQM_BLENDWEIGHTS = 5, - IQM_COLOR = 6, // vertex colors unused by default - IQM_CUSTOM = 0x10 // custom vertex values unused by default -} IQMVertexType; //---------------------------------------------------------------------------------- // Global Variables Definition @@ -225,609 +87,12 @@ typedef enum { //---------------------------------------------------------------------------------- // Module specific Functions Declaration //---------------------------------------------------------------------------------- -static AnimatedModel LoadIQM(const char *filename); #ifdef __cplusplus extern "C" { // Prevents name mangling of functions #endif -// Load .iqm file and initialize animated model -AnimatedModel LoadAnimatedModel(const char *filename) -{ - AnimatedModel out = LoadIQM(filename); - - for (int i = 0; i < out.meshCount; i++) rlLoadMesh(&out.meshes[i], false); - - out.transform = MatrixIdentity(); - out.meshMaterialId = malloc(sizeof(int)*out.meshCount); - out.materials = NULL; - out.materialCount = 0; - - for (int i = 0; i < out.meshCount; i++) out.meshMaterialId[i] = -1; - - return out; -} - -// Add a texture to an animated model -AnimatedModel AnimatedModelAddTexture(AnimatedModel model, const char *filename) -{ - Texture2D texture = LoadTexture(filename); - - model.materials = realloc(model.materials, sizeof(Material)*(model.materialCount + 1)); - model.materials[model.materialCount] = LoadMaterialDefault(); - model.materials[model.materialCount].maps[MAP_DIFFUSE].texture = texture; - model.materialCount++; - - return model; -} - -// Set the material for a meshes -AnimatedModel SetMeshMaterial(AnimatedModel model, int meshid, int textureid) -{ - if (meshid > model.meshCount) - { - TraceLog(LOG_WARNING, "MeshId greater than meshCount\n"); - return model; - } - - if (textureid > model.materialCount) - { - TraceLog(LOG_WARNING,"textureid greater than materialCount\n"); - return model; - } - - model.meshMaterialId[meshid] = textureid; - - return model; -} - -// Load animations from a .iqm file -Animation LoadAnimationFromIQM(const char *filename) -{ - Animation animation = { 0 }; - - FILE *iqmFile; - IQMHeader iqm; - - iqmFile = fopen(filename,"rb"); - - if (!iqmFile) - { - TraceLog(LOG_ERROR, "[%s] Unable to open file", filename); - return animation; - } - - // header - fread(&iqm, sizeof(IQMHeader), 1, iqmFile); - - if (strncmp(iqm.magic, IQM_MAGIC, sizeof(IQM_MAGIC))) - { - TraceLog(LOG_ERROR, "Magic Number \"%s\"does not match.", iqm.magic); - fclose(iqmFile); - return animation; - } - - if (iqm.version != IQM_VERSION) - { - TraceLog(LOG_ERROR, "IQM version %i is incorrect.", iqm.version); - fclose(iqmFile); - return animation; - } - - // header - if (iqm.num_anims > 1) TraceLog(LOG_WARNING, "More than 1 animation in file, only the first one will get loaded"); - - // joints - IQMPose *poses; - poses = malloc(sizeof(IQMPose)*iqm.num_poses); - fseek(iqmFile, iqm.ofs_poses, SEEK_SET); - fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile); - - animation.jointCount = iqm.num_poses; - animation.joints = malloc(sizeof(Joint)*iqm.num_poses); - - for (int j = 0; j < iqm.num_poses; j++) - { - strcpy(animation.joints[j].name, ANIMJOINTNAME); - animation.joints[j].parent = poses[j].parent; - } - - // animations - IQMAnim anim = {0}; - fseek(iqmFile, iqm.ofs_anims, SEEK_SET); - fread(&anim, sizeof(IQMAnim), 1, iqmFile); - - animation.frameCount = anim.num_frames; - animation.framerate = anim.framerate; - - // frameposes - unsigned short *framedata = malloc(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); - fseek(iqmFile, iqm.ofs_frames, SEEK_SET); - fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile); - - animation.framepose = malloc(sizeof(Pose*)*anim.num_frames); - for (int j = 0; j < anim.num_frames; j++) animation.framepose[j] = malloc(sizeof(Pose)*iqm.num_poses); - - int dcounter = anim.first_frame*iqm.num_framechannels; - - for (int frame = 0; frame < anim.num_frames; frame++) - { - for (int i = 0; i < iqm.num_poses; i++) - { - animation.framepose[frame][i].translation.x = poses[i].channeloffset[0]; - - if (poses[i].mask & 0x01) - { - animation.framepose[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0]; - dcounter++; - } - - animation.framepose[frame][i].translation.y = poses[i].channeloffset[1]; - - if (poses[i].mask & 0x02) - { - animation.framepose[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1]; - dcounter++; - } - - animation.framepose[frame][i].translation.z = poses[i].channeloffset[2]; - - if (poses[i].mask & 0x04) - { - animation.framepose[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2]; - dcounter++; - } - - animation.framepose[frame][i].rotation.x = poses[i].channeloffset[3]; - - if (poses[i].mask & 0x08) - { - animation.framepose[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3]; - dcounter++; - } - - animation.framepose[frame][i].rotation.y = poses[i].channeloffset[4]; - - if (poses[i].mask & 0x10) - { - animation.framepose[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4]; - dcounter++; - } - - animation.framepose[frame][i].rotation.z = poses[i].channeloffset[5]; - - if (poses[i].mask & 0x20) - { - animation.framepose[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5]; - dcounter++; - } - - animation.framepose[frame][i].rotation.w = poses[i].channeloffset[6]; - - if (poses[i].mask & 0x40) - { - animation.framepose[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6]; - dcounter++; - } - - animation.framepose[frame][i].scale.x = poses[i].channeloffset[7]; - - if (poses[i].mask & 0x80) - { - animation.framepose[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7]; - dcounter++; - } - - animation.framepose[frame][i].scale.y = poses[i].channeloffset[8]; - - if (poses[i].mask & 0x100) - { - animation.framepose[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8]; - dcounter++; - } - - animation.framepose[frame][i].scale.z = poses[i].channeloffset[9]; - - if (poses[i].mask & 0x200) - { - animation.framepose[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9]; - dcounter++; - } - - animation.framepose[frame][i].rotation = QuaternionNormalize(animation.framepose[frame][i].rotation); - } - } - - // Build frameposes - for (int frame = 0; frame < anim.num_frames; frame++) - { - for (int i = 0; i < animation.jointCount; i++) - { - if (animation.joints[i].parent >= 0) - { - animation.framepose[frame][i].rotation = QuaternionMultiply(animation.framepose[frame][animation.joints[i].parent].rotation, animation.framepose[frame][i].rotation); - animation.framepose[frame][i].translation = Vector3RotateByQuaternion(animation.framepose[frame][i].translation, animation.framepose[frame][animation.joints[i].parent].rotation); - animation.framepose[frame][i].translation = Vector3Add(animation.framepose[frame][i].translation, animation.framepose[frame][animation.joints[i].parent].translation); - animation.framepose[frame][i].scale = Vector3MultiplyV(animation.framepose[frame][i].scale, animation.framepose[frame][animation.joints[i].parent].scale); - } - } - } - - free(framedata); - free(poses); - - fclose(iqmFile); - - return animation; -} - -// Unload animated model -void UnloadAnimatedModel(AnimatedModel model) -{ - free(model.materials); - free(model.meshMaterialId); - free(model.joints); - free(model.basepose); - - for (int i = 0; i < model.meshCount; i++) rlUnloadMesh(&model.meshes[i]); - - free(model.meshes); -} - -// Unload animation -void UnloadAnimation(Animation anim) -{ - free(anim.joints); - free(anim.framepose); - - for (int i = 0; i < anim.frameCount; i++) free(anim.framepose[i]); -} - -// Check if skeletons match, only parents and jointCount are checked -bool CheckSkeletonsMatch(AnimatedModel model, Animation anim) -{ - if (model.jointCount != anim.jointCount) return 0; - - for (int i = 0; i < model.jointCount; i++) - { - if (model.joints[i].parent != anim.joints[i].parent) return 0; - } - - return 1; -} - -// Calculate the animated vertex positions and normals based on an animation at a given frame -void AnimateModel(AnimatedModel model, Animation anim, int frame) -{ - if (frame >= anim.frameCount) frame = frame%anim.frameCount; - - for (int m = 0; m < model.meshCount; m++) - { - Vector3 outv = {0}; - Vector3 outn = {0}; - - Vector3 baset = {0}; - Quaternion baser = {0}; - Vector3 bases = {0}; - - Vector3 outt = {0}; - Quaternion outr = {0}; - Vector3 outs = {0}; - - int vcounter = 0; - int wcounter = 0; - int weightId = 0; - - for (int i = 0; i < model.meshes[m].vertexCount; i++) - { - weightId = model.meshes[m].weightId[wcounter]; - baset = model.basepose[weightId].translation; - baser = model.basepose[weightId].rotation; - bases = model.basepose[weightId].scale; - outt = anim.framepose[frame][weightId].translation; - outr = anim.framepose[frame][weightId].rotation; - outs = anim.framepose[frame][weightId].scale; - - // vertices - // NOTE: We use meshes.baseVertices (default position) to calculate meshes.vertices (animated position) - outv = (Vector3){ model.meshes[m].baseVertices[vcounter], model.meshes[m].baseVertices[vcounter + 1], model.meshes[m].baseVertices[vcounter + 2] }; - outv = Vector3MultiplyV(outv, outs); - outv = Vector3Subtract(outv, baset); - outv = Vector3RotateByQuaternion(outv, QuaternionMultiply(outr, QuaternionInvert(baser))); - outv = Vector3Add(outv, outt); - model.meshes[m].vertices[vcounter] = outv.x; - model.meshes[m].vertices[vcounter + 1] = outv.y; - model.meshes[m].vertices[vcounter + 2] = outv.z; - - // normals - // NOTE: We use meshes.baseNormals (default normal) to calculate meshes.normals (animated normals) - outn = (Vector3){ model.meshes[m].baseNormals[vcounter], model.meshes[m].baseNormals[vcounter + 1], model.meshes[m].baseNormals[vcounter + 2] }; - outn = Vector3RotateByQuaternion(outn, QuaternionMultiply(outr, QuaternionInvert(baser))); - model.meshes[m].normals[vcounter] = outn.x; - model.meshes[m].normals[vcounter + 1] = outn.y; - model.meshes[m].normals[vcounter + 2] = outn.z; - vcounter += 3; - wcounter += 4; - } - } -} - -// Draw an animated model -void DrawAnimatedModel(AnimatedModel model, Vector3 position, float scale, Color tint) -{ - Vector3 vScale = { scale, scale, scale }; - Vector3 rotationAxis = { 1.0f, 0.0f,0.0f }; - - DrawAnimatedModelEx(model, position, rotationAxis, -90.0f, vScale, tint); -} - -// Draw an animated model with extended parameters -void DrawAnimatedModelEx(AnimatedModel model, Vector3 position, Vector3 rotationAxis, float rotationAngle, Vector3 scale, Color tint) -{ - if (model.materialCount == 0) - { - TraceLog(LOG_WARNING,"No materials set, can't draw animated meshes\n"); - return; - } - - Matrix matScale = MatrixScale(scale.x, scale.y, scale.z); - Matrix matRotation = MatrixRotate(rotationAxis, rotationAngle*DEG2RAD); - Matrix matTranslation = MatrixTranslate(position.x, position.y, position.z); - - Matrix matTransform = MatrixMultiply(MatrixMultiply(matScale, matRotation), matTranslation); - model.transform = MatrixMultiply(model.transform, matTransform); - - for (int i = 0; i < model.meshCount; i++) - { - rlUpdateMesh(model.meshes[i], 0, model.meshes[i].vertexCount); // Update vertex position - rlUpdateMesh(model.meshes[i], 2, model.meshes[i].vertexCount); // Update vertex normals - rlDrawMesh(model.meshes[i], model.materials[model.meshMaterialId[i]], model.transform); // Draw meshes - } -} - -// Load animated model meshes from IQM file -static AnimatedModel LoadIQM(const char *filename) -{ - AnimatedModel model = { 0 }; - - FILE *iqmFile; - IQMHeader iqm; - - IQMMesh *imesh; - IQMTriangle *tri; - IQMVertexArray *va; - IQMJoint *ijoint; - - float *vertex; - float *normal; - float *text; - char *blendi; - unsigned char *blendw; - - iqmFile = fopen(filename, "rb"); - - if (!iqmFile) - { - TraceLog(LOG_ERROR, "[%s] Unable to open file", filename); - return model; - } - - // header - fread(&iqm,sizeof(IQMHeader), 1, iqmFile); - - if (strncmp(iqm.magic, IQM_MAGIC, sizeof(IQM_MAGIC))) - { - TraceLog(LOG_ERROR, "Magic Number \"%s\"does not match.", iqm.magic); - fclose(iqmFile); - return model; - } - - if(iqm.version != IQM_VERSION) - { - TraceLog(LOG_ERROR, "IQM version %i is incorrect.", iqm.version); - fclose(iqmFile); - return model; - } - - // meshes - imesh = malloc(sizeof(IQMMesh)*iqm.num_meshes); - fseek(iqmFile, iqm.ofs_meshes, SEEK_SET); - fread(imesh, sizeof(IQMMesh)*iqm.num_meshes, 1, iqmFile); - - model.meshCount = iqm.num_meshes; - model.meshes = malloc(sizeof(Mesh)*iqm.num_meshes); - - char name[MESH_NAME_LENGTH]; - - for (int i = 0; i < iqm.num_meshes; i++) - { - fseek(iqmFile,iqm.ofs_text+imesh[i].name,SEEK_SET); - fread(name, sizeof(char)*MESH_NAME_LENGTH, 1, iqmFile); // Mesh name not used... - model.meshes[i].vertexCount = imesh[i].num_vertexes; - - model.meshes[i].baseVertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default IQM base position - model.meshes[i].baseNormals = malloc(sizeof(float)*imesh[i].num_vertexes*3); // Default IQM base normal - - model.meshes[i].texcoords = malloc(sizeof(float)*imesh[i].num_vertexes*2); - model.meshes[i].weightId = malloc(sizeof(int)*imesh[i].num_vertexes*4); - model.meshes[i].weightBias = malloc(sizeof(float)*imesh[i].num_vertexes*4); - - model.meshes[i].triangleCount = imesh[i].num_triangles; - model.meshes[i].indices = malloc(sizeof(unsigned short)*imesh[i].num_triangles*3); - - // What we actually process for rendering, should be updated transforming meshes.vertices and meshes.normals - model.meshes[i].vertices = malloc(sizeof(float)*imesh[i].num_vertexes*3); - model.meshes[i].normals = malloc(sizeof(float)*imesh[i].num_vertexes*3); - } - - // tris - tri = malloc(sizeof(IQMTriangle)*iqm.num_triangles); - fseek(iqmFile, iqm.ofs_triangles, SEEK_SET); - fread(tri, sizeof(IQMTriangle)*iqm.num_triangles, 1, iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int tcounter = 0; - - for (int i = imesh[m].first_triangle; i < imesh[m].first_triangle+imesh[m].num_triangles; i++) - { - // IQM triangles are stored counter clockwise, but raylib sets opengl to clockwise drawing, so we swap them around - model.meshes[m].indices[tcounter+2] = tri[i].vertex[0] - imesh[m].first_vertex; - model.meshes[m].indices[tcounter+1] = tri[i].vertex[1] - imesh[m].first_vertex; - model.meshes[m].indices[tcounter] = tri[i].vertex[2] - imesh[m].first_vertex; - tcounter += 3; - } - } - - // vertarrays - va = malloc(sizeof(IQMVertexArray)*iqm.num_vertexarrays); - fseek(iqmFile, iqm.ofs_vertexarrays, SEEK_SET); - fread(va, sizeof(IQMVertexArray)*iqm.num_vertexarrays, 1, iqmFile); - - for (int i = 0; i < iqm.num_vertexarrays; i++) - { - switch (va[i].type) - { - case IQM_POSITION: - { - vertex = malloc(sizeof(float)*iqm.num_vertexes*3); - fseek(iqmFile, va[i].offset, SEEK_SET); - fread(vertex, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int vcounter = 0; - for (int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++) - { - model.meshes[m].vertices[vcounter] = vertex[i]; - model.meshes[m].baseVertices[vcounter] = vertex[i]; - vcounter++; - } - } - } break; - case IQM_NORMAL: - { - normal = malloc(sizeof(float)*iqm.num_vertexes*3); - fseek(iqmFile, va[i].offset, SEEK_SET); - fread(normal, sizeof(float)*iqm.num_vertexes*3, 1, iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int vcounter = 0; - for (int i = imesh[m].first_vertex*3; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*3; i++) - { - model.meshes[m].normals[vcounter] = normal[i]; - model.meshes[m].baseNormals[vcounter] = normal[i]; - vcounter++; - } - } - } break; - case IQM_TEXCOORD: - { - text = malloc(sizeof(float)*iqm.num_vertexes*2); - fseek(iqmFile, va[i].offset, SEEK_SET); - fread(text, sizeof(float)*iqm.num_vertexes*2, 1, iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int vcounter = 0; - for (int i = imesh[m].first_vertex*2; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*2; i++) - { - model.meshes[m].texcoords[vcounter] = text[i]; - vcounter++; - } - } - } break; - case IQM_BLENDINDEXES: - { - blendi = malloc(sizeof(char)*iqm.num_vertexes*4); - fseek(iqmFile, va[i].offset, SEEK_SET); - fread(blendi, sizeof(char)*iqm.num_vertexes*4, 1, iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int vcounter = 0; - for (int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++) - { - model.meshes[m].weightId[vcounter] = blendi[i]; - vcounter++; - } - } - } break; - case IQM_BLENDWEIGHTS: - { - blendw = malloc(sizeof(unsigned char)*iqm.num_vertexes*4); - fseek(iqmFile,va[i].offset,SEEK_SET); - fread(blendw,sizeof(unsigned char)*iqm.num_vertexes*4,1,iqmFile); - - for (int m = 0; m < iqm.num_meshes; m++) - { - int vcounter = 0; - for (int i = imesh[m].first_vertex*4; i < (imesh[m].first_vertex + imesh[m].num_vertexes)*4; i++) - { - model.meshes[m].weightBias[vcounter] = blendw[i]/255.0f; - vcounter++; - } - } - } break; - } - } - - // joints, include base poses - ijoint = malloc(sizeof(IQMJoint)*iqm.num_joints); - fseek(iqmFile, iqm.ofs_joints, SEEK_SET); - fread(ijoint, sizeof(IQMJoint)*iqm.num_joints, 1, iqmFile); - - model.jointCount = iqm.num_joints; - model.joints = malloc(sizeof(Joint)*iqm.num_joints); - model.basepose = malloc(sizeof(Pose)*iqm.num_joints); - - for (int i = 0; i < iqm.num_joints; i++) - { - // joints - model.joints[i].parent = ijoint[i].parent; - fseek(iqmFile, iqm.ofs_text + ijoint[i].name, SEEK_SET); - fread(model.joints[i].name,sizeof(char)*JOINT_NAME_LENGTH, 1, iqmFile); - - // basepose - model.basepose[i].translation.x = ijoint[i].translate[0]; - model.basepose[i].translation.y = ijoint[i].translate[1]; - model.basepose[i].translation.z = ijoint[i].translate[2]; - - model.basepose[i].rotation.x = ijoint[i].rotate[0]; - model.basepose[i].rotation.y = ijoint[i].rotate[1]; - model.basepose[i].rotation.z = ijoint[i].rotate[2]; - model.basepose[i].rotation.w = ijoint[i].rotate[3]; - - model.basepose[i].scale.x = ijoint[i].scale[0]; - model.basepose[i].scale.y = ijoint[i].scale[1]; - model.basepose[i].scale.z = ijoint[i].scale[2]; - } - - // build base pose - for (int i = 0; i < model.jointCount; i++) - { - if (model.joints[i].parent >= 0) - { - model.basepose[i].rotation = QuaternionMultiply(model.basepose[model.joints[i].parent].rotation, model.basepose[i].rotation); - model.basepose[i].translation = Vector3RotateByQuaternion(model.basepose[i].translation, model.basepose[model.joints[i].parent].rotation); - model.basepose[i].translation = Vector3Add(model.basepose[i].translation, model.basepose[model.joints[i].parent].translation); - model.basepose[i].scale = Vector3MultiplyV(model.basepose[i].scale, model.basepose[model.joints[i].parent].scale); - } - } - fclose(iqmFile); - free(imesh); - free(tri); - free(va); - free(vertex); - free(normal); - free(text); - free(blendi); - free(blendw); - free(ijoint); - return model; -} #endif diff --git a/src/models.c b/src/models.c index 239ab5d8..e437a0ab 100644 --- a/src/models.c +++ b/src/models.c @@ -697,6 +697,18 @@ void UnloadModel(Model model) TraceLog(LOG_INFO, "Unloaded model data from RAM and VRAM"); } +// Load meshes from model file +Mesh *LoadMeshes(const char *fileName, int *meshCount) +{ + Mesh *meshes = NULL; + int count = 0; + + // TODO: Load meshes from file (OBJ, IQM, GLTF) + + *meshCount = count; + return meshes; +} + // Unload mesh from memory (RAM and/or VRAM) void UnloadMesh(Mesh *mesh) { @@ -759,6 +771,386 @@ void ExportMesh(Mesh mesh, const char *fileName) else TraceLog(LOG_WARNING, "Mesh could not be exported."); } +// Load materials from model file +Material *LoadMaterials(const char *fileName, int *materialCount) +{ + Material *materials = NULL; + unsigned int count = 0; + + // TODO: Support IQM and GLTF for materials parsing + +#if defined(SUPPORT_FILEFORMAT_MTL) + if (IsFileExtension(fileName, ".mtl")) + { + tinyobj_material_t *mats; + + int result = tinyobj_parse_mtl_file(&mats, &count, fileName); + + // TODO: Process materials to return + + tinyobj_materials_free(mats, count); + } +#else + TraceLog(LOG_WARNING, "[%s] Materials file not supported", fileName); +#endif + + // Set materials shader to default (DIFFUSE, SPECULAR, NORMAL) + for (int i = 0; i < count; i++) materials[i].shader = GetShaderDefault(); + + *materialCount = count; + return materials; +} + +// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +Material LoadMaterialDefault(void) +{ + Material material = { 0 }; + + material.shader = GetShaderDefault(); + material.maps[MAP_DIFFUSE].texture = GetTextureDefault(); // White texture (1x1 pixel) + //material.maps[MAP_NORMAL].texture; // NOTE: By default, not set + //material.maps[MAP_SPECULAR].texture; // NOTE: By default, not set + + material.maps[MAP_DIFFUSE].color = WHITE; // Diffuse color + material.maps[MAP_SPECULAR].color = WHITE; // Specular color + + return material; +} + +// Unload material from memory +void UnloadMaterial(Material material) +{ + // Unload material shader (avoid unloading default shader, managed by raylib) + if (material.shader.id != GetShaderDefault().id) UnloadShader(material.shader); + + // Unload loaded texture maps (avoid unloading default texture, managed by raylib) + for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + { + if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); + } +} + +// Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...) +// NOTE: Previous texture should be manually unloaded +void SetMaterialTexture(Material *material, int mapType, Texture2D texture) +{ + material->maps[mapType].texture = texture; +} + +// Set the material for a mesh +void SetModelMeshMaterial(Model *model, int meshId, int materialId) +{ + if (meshId >= model->meshCount) TraceLog(LOG_WARNING, "Mesh id greater than mesh count"); + else if (materialId >= model->materialCount) TraceLog(LOG_WARNING,"Material id greater than material count"); + else model->meshMaterial[meshId] = materialId; +} + +// Load model animations from file +ModelAnimation *LoadModelAnimations(const char *filename, int *animCount) +{ + ModelAnimation *animations = (ModelAnimation *)malloc(1*sizeof(ModelAnimation)); + int count = 1; + + #define IQM_MAGIC "INTERQUAKEMODEL" // IQM file magic number + #define IQM_VERSION 2 // only IQM version 2 supported + + typedef struct IQMHeader { + char magic[16]; + unsigned int version; + unsigned int filesize; + unsigned int flags; + unsigned int num_text, ofs_text; + unsigned int num_meshes, ofs_meshes; + unsigned int num_vertexarrays, num_vertexes, ofs_vertexarrays; + unsigned int num_triangles, ofs_triangles, ofs_adjacency; + unsigned int num_joints, ofs_joints; + unsigned int num_poses, ofs_poses; + unsigned int num_anims, ofs_anims; + unsigned int num_frames, num_framechannels, ofs_frames, ofs_bounds; + unsigned int num_comment, ofs_comment; + unsigned int num_extensions, ofs_extensions; + } IQMHeader; + + typedef struct IQMPose { + int parent; + unsigned int mask; + float channeloffset[10]; + float channelscale[10]; + } IQMPose; + + typedef struct IQMAnim { + unsigned int name; + unsigned int first_frame, num_frames; + float framerate; + unsigned int flags; + } IQMAnim; + + ModelAnimation animation = { 0 }; + + FILE *iqmFile; + IQMHeader iqm; + + iqmFile = fopen(filename,"rb"); + + if (!iqmFile) + { + TraceLog(LOG_ERROR, "[%s] Unable to open file", filename); + } + + // header + fread(&iqm, sizeof(IQMHeader), 1, iqmFile); + + if (strncmp(iqm.magic, IQM_MAGIC, sizeof(IQM_MAGIC))) + { + TraceLog(LOG_ERROR, "Magic Number \"%s\"does not match.", iqm.magic); + fclose(iqmFile); + } + + if (iqm.version != IQM_VERSION) + { + TraceLog(LOG_ERROR, "IQM version %i is incorrect.", iqm.version); + fclose(iqmFile); + } + + // header + if (iqm.num_anims > 1) TraceLog(LOG_WARNING, "More than 1 animation in file, only the first one will be loaded"); + + // bones + IQMPose *poses; + poses = malloc(sizeof(IQMPose)*iqm.num_poses); + fseek(iqmFile, iqm.ofs_poses, SEEK_SET); + fread(poses, sizeof(IQMPose)*iqm.num_poses, 1, iqmFile); + + animation.boneCount = iqm.num_poses; + animation.bones = malloc(sizeof(BoneInfo)*iqm.num_poses); + + for (int j = 0; j < iqm.num_poses; j++) + { + strcpy(animation.bones[j].name, "ANIMJOINTNAME"); + animation.bones[j].parent = poses[j].parent; + } + + // animations + IQMAnim anim = {0}; + fseek(iqmFile, iqm.ofs_anims, SEEK_SET); + fread(&anim, sizeof(IQMAnim), 1, iqmFile); + + animation.frameCount = anim.num_frames; + //animation.framerate = anim.framerate; + + // frameposes + unsigned short *framedata = malloc(sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels); + fseek(iqmFile, iqm.ofs_frames, SEEK_SET); + fread(framedata, sizeof(unsigned short)*iqm.num_frames*iqm.num_framechannels, 1, iqmFile); + + animation.framePoses = malloc(sizeof(Transform*)*anim.num_frames); + for (int j = 0; j < anim.num_frames; j++) animation.framePoses[j] = malloc(sizeof(Transform)*iqm.num_poses); + + int dcounter = anim.first_frame*iqm.num_framechannels; + + for (int frame = 0; frame < anim.num_frames; frame++) + { + for (int i = 0; i < iqm.num_poses; i++) + { + animation.framePoses[frame][i].translation.x = poses[i].channeloffset[0]; + + if (poses[i].mask & 0x01) + { + animation.framePoses[frame][i].translation.x += framedata[dcounter]*poses[i].channelscale[0]; + dcounter++; + } + + animation.framePoses[frame][i].translation.y = poses[i].channeloffset[1]; + + if (poses[i].mask & 0x02) + { + animation.framePoses[frame][i].translation.y += framedata[dcounter]*poses[i].channelscale[1]; + dcounter++; + } + + animation.framePoses[frame][i].translation.z = poses[i].channeloffset[2]; + + if (poses[i].mask & 0x04) + { + animation.framePoses[frame][i].translation.z += framedata[dcounter]*poses[i].channelscale[2]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.x = poses[i].channeloffset[3]; + + if (poses[i].mask & 0x08) + { + animation.framePoses[frame][i].rotation.x += framedata[dcounter]*poses[i].channelscale[3]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.y = poses[i].channeloffset[4]; + + if (poses[i].mask & 0x10) + { + animation.framePoses[frame][i].rotation.y += framedata[dcounter]*poses[i].channelscale[4]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.z = poses[i].channeloffset[5]; + + if (poses[i].mask & 0x20) + { + animation.framePoses[frame][i].rotation.z += framedata[dcounter]*poses[i].channelscale[5]; + dcounter++; + } + + animation.framePoses[frame][i].rotation.w = poses[i].channeloffset[6]; + + if (poses[i].mask & 0x40) + { + animation.framePoses[frame][i].rotation.w += framedata[dcounter]*poses[i].channelscale[6]; + dcounter++; + } + + animation.framePoses[frame][i].scale.x = poses[i].channeloffset[7]; + + if (poses[i].mask & 0x80) + { + animation.framePoses[frame][i].scale.x += framedata[dcounter]*poses[i].channelscale[7]; + dcounter++; + } + + animation.framePoses[frame][i].scale.y = poses[i].channeloffset[8]; + + if (poses[i].mask & 0x100) + { + animation.framePoses[frame][i].scale.y += framedata[dcounter]*poses[i].channelscale[8]; + dcounter++; + } + + animation.framePoses[frame][i].scale.z = poses[i].channeloffset[9]; + + if (poses[i].mask & 0x200) + { + animation.framePoses[frame][i].scale.z += framedata[dcounter]*poses[i].channelscale[9]; + dcounter++; + } + + animation.framePoses[frame][i].rotation = QuaternionNormalize(animation.framePoses[frame][i].rotation); + } + } + + // Build frameposes + for (int frame = 0; frame < anim.num_frames; frame++) + { + for (int i = 0; i < animation.boneCount; i++) + { + if (animation.bones[i].parent >= 0) + { + animation.framePoses[frame][i].rotation = QuaternionMultiply(animation.framePoses[frame][animation.bones[i].parent].rotation, animation.framePoses[frame][i].rotation); + animation.framePoses[frame][i].translation = Vector3RotateByQuaternion(animation.framePoses[frame][i].translation, animation.framePoses[frame][animation.bones[i].parent].rotation); + animation.framePoses[frame][i].translation = Vector3Add(animation.framePoses[frame][i].translation, animation.framePoses[frame][animation.bones[i].parent].translation); + animation.framePoses[frame][i].scale = Vector3MultiplyV(animation.framePoses[frame][i].scale, animation.framePoses[frame][animation.bones[i].parent].scale); + } + } + } + + free(framedata); + free(poses); + + fclose(iqmFile); + + animations[0] = animation; + + *animCount = count; + return animations; +} + +// Update model animated vertex data (positions and normals) for a given frame +// NOTE: Updated data is uploaded to GPU +void UpdateModelAnimation(Model model, ModelAnimation anim, int frame) +{ + if (frame >= anim.frameCount) frame = frame%anim.frameCount; + + for (int m = 0; m < model.meshCount; m++) + { + Vector3 animVertex = { 0 }; + Vector3 animNormal = { 0 }; + + Vector3 inTranslation = { 0 }; + Quaternion inRotation = { 0 }; + Vector3 inScale = { 0 }; + + Vector3 outTranslation = { 0 }; + Quaternion outRotation = { 0 }; + Vector3 outScale = { 0 }; + + int vCounter = 0; + int boneCounter = 0; + int boneId = 0; + + for (int i = 0; i < model.meshes[m].vertexCount; i++) + { + boneId = model.meshes[m].boneIds[boneCounter]; + inTranslation = model.bindPose[boneId].translation; + inRotation = model.bindPose[boneId].rotation; + inScale = model.bindPose[boneId].scale; + outTranslation = anim.framePoses[frame][boneId].translation; + outRotation = anim.framePoses[frame][boneId].rotation; + outScale = anim.framePoses[frame][boneId].scale; + + // Vertices processing + // NOTE: We use meshes.vertices (default vertex position) to calculate meshes.animVertices (animated vertex position) + animVertex = (Vector3){ model.meshes[m].vertices[vCounter], model.meshes[m].vertices[vCounter + 1], model.meshes[m].vertices[vCounter + 2] }; + animVertex = Vector3MultiplyV(animVertex, outScale); + animVertex = Vector3Subtract(animVertex, inTranslation); + animVertex = Vector3RotateByQuaternion(animVertex, QuaternionMultiply(outRotation, QuaternionInvert(inRotation))); + animVertex = Vector3Add(animVertex, outTranslation); + model.meshes[m].animVertices[vCounter] = animVertex.x; + model.meshes[m].animVertices[vCounter + 1] = animVertex.y; + model.meshes[m].animVertices[vCounter + 2] = animVertex.z; + + // Normals processing + // NOTE: We use meshes.baseNormals (default normal) to calculate meshes.normals (animated normals) + animNormal = (Vector3){ model.meshes[m].normals[vCounter], model.meshes[m].normals[vCounter + 1], model.meshes[m].normals[vCounter + 2] }; + animNormal = Vector3RotateByQuaternion(animNormal, QuaternionMultiply(outRotation, QuaternionInvert(inRotation))); + model.meshes[m].animNormals[vCounter] = animNormal.x; + model.meshes[m].animNormals[vCounter + 1] = animNormal.y; + model.meshes[m].animNormals[vCounter + 2] = animNormal.z; + vCounter += 3; + + boneCounter += 4; + } + + // Upload new vertex data to GPU for model drawing + rlUpdateBuffer(model.meshes[m].vboId[0], model.meshes[m].animVertices, model.meshes[m].vertexCount*3*sizeof(float)); // Update vertex position + rlUpdateBuffer(model.meshes[m].vboId[2], model.meshes[m].animVertices, model.meshes[m].vertexCount*3*sizeof(float)); // Update vertex normals + } +} + +// Unload animation data +void UnloadModelAnimation(ModelAnimation anim) +{ + for (int i = 0; i < anim.frameCount; i++) free(anim.framePoses[i]); + + free(anim.bones); + free(anim.framePoses); +} + +// Check model animation skeleton match +// NOTE: Only number of bones and parent connections are checked +bool IsModelAnimationValid(Model model, ModelAnimation anim) +{ + int result = true; + + if (model.boneCount != anim.boneCount) result = false; + else + { + for (int i = 0; i < model.boneCount; i++) + { + if (model.bones[i].parent != anim.bones[i].parent) { result = false; break; } + } + } + + return result; +} + #if defined(SUPPORT_MESH_GENERATION) // Generate polygonal mesh Mesh GenMeshPoly(int sides, float radius) @@ -1807,59 +2199,124 @@ Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize) } #endif // SUPPORT_MESH_GENERATION -// Load material data (from file) -Material LoadMaterial(const char *fileName) +// Compute mesh bounding box limits +// NOTE: minVertex and maxVertex should be transformed by model transform matrix +BoundingBox MeshBoundingBox(Mesh mesh) { - Material material = { 0 }; + // Get min and max vertex to construct bounds (AABB) + Vector3 minVertex = { 0 }; + Vector3 maxVertex = { 0 }; -#if defined(SUPPORT_FILEFORMAT_MTL) - if (IsFileExtension(fileName, ".mtl")) + if (mesh.vertices != NULL) { - tinyobj_material_t *materials; - unsigned int materialCount = 0; - - int result = tinyobj_parse_mtl_file(&materials, &materialCount, fileName); - - // TODO: Process materials to return + minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; + maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - tinyobj_materials_free(materials, materialCount); + for (int i = 1; i < mesh.vertexCount; i++) + { + minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); + maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); + } } -#else - TraceLog(LOG_WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); -#endif - // Our material uses the default shader (DIFFUSE, SPECULAR, NORMAL) - material.shader = GetShaderDefault(); + // Create the bounding box + BoundingBox box = { 0 }; + box.min = minVertex; + box.max = maxVertex; - return material; + return box; } -// Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -Material LoadMaterialDefault(void) +// Compute mesh tangents +// NOTE: To calculate mesh tangents and binormals we need mesh vertex positions and texture coordinates +// Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html +void MeshTangents(Mesh *mesh) { - Material material = { 0 }; + if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); + else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - material.shader = GetShaderDefault(); - material.maps[MAP_DIFFUSE].texture = GetTextureDefault(); // White texture (1x1 pixel) - //material.maps[MAP_NORMAL].texture; // NOTE: By default, not set - //material.maps[MAP_SPECULAR].texture; // NOTE: By default, not set + Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); + Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - material.maps[MAP_DIFFUSE].color = WHITE; // Diffuse color - material.maps[MAP_SPECULAR].color = WHITE; // Specular color + for (int i = 0; i < mesh->vertexCount; i += 3) + { + // Get triangle vertices + Vector3 v1 = { mesh->vertices[(i + 0)*3 + 0], mesh->vertices[(i + 0)*3 + 1], mesh->vertices[(i + 0)*3 + 2] }; + Vector3 v2 = { mesh->vertices[(i + 1)*3 + 0], mesh->vertices[(i + 1)*3 + 1], mesh->vertices[(i + 1)*3 + 2] }; + Vector3 v3 = { mesh->vertices[(i + 2)*3 + 0], mesh->vertices[(i + 2)*3 + 1], mesh->vertices[(i + 2)*3 + 2] }; - return material; + // Get triangle texcoords + Vector2 uv1 = { mesh->texcoords[(i + 0)*2 + 0], mesh->texcoords[(i + 0)*2 + 1] }; + Vector2 uv2 = { mesh->texcoords[(i + 1)*2 + 0], mesh->texcoords[(i + 1)*2 + 1] }; + Vector2 uv3 = { mesh->texcoords[(i + 2)*2 + 0], mesh->texcoords[(i + 2)*2 + 1] }; + + float x1 = v2.x - v1.x; + float y1 = v2.y - v1.y; + float z1 = v2.z - v1.z; + float x2 = v3.x - v1.x; + float y2 = v3.y - v1.y; + float z2 = v3.z - v1.z; + + float s1 = uv2.x - uv1.x; + float t1 = uv2.y - uv1.y; + float s2 = uv3.x - uv1.x; + float t2 = uv3.y - uv1.y; + + float div = s1*t2 - s2*t1; + float r = (div == 0.0f)? 0.0f : 1.0f/div; + + Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; + Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; + + tan1[i + 0] = sdir; + tan1[i + 1] = sdir; + tan1[i + 2] = sdir; + + tan2[i + 0] = tdir; + tan2[i + 1] = tdir; + tan2[i + 2] = tdir; + } + + // Compute tangents considering normals + for (int i = 0; i < mesh->vertexCount; ++i) + { + Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; + Vector3 tangent = tan1[i]; + + // TODO: Review, not sure if tangent computation is right, just used reference proposed maths... + #if defined(COMPUTE_TANGENTS_METHOD_01) + Vector3 tmp = Vector3Subtract(tangent, Vector3Multiply(normal, Vector3DotProduct(normal, tangent))); + tmp = Vector3Normalize(tmp); + mesh->tangents[i*4 + 0] = tmp.x; + mesh->tangents[i*4 + 1] = tmp.y; + mesh->tangents[i*4 + 2] = tmp.z; + mesh->tangents[i*4 + 3] = 1.0f; + #else + Vector3OrthoNormalize(&normal, &tangent); + mesh->tangents[i*4 + 0] = tangent.x; + mesh->tangents[i*4 + 1] = tangent.y; + mesh->tangents[i*4 + 2] = tangent.z; + mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f)? -1.0f : 1.0f; + #endif + } + + free(tan1); + free(tan2); + + TraceLog(LOG_INFO, "Tangents computed for mesh"); } -// Unload material from memory -void UnloadMaterial(Material material) +// Compute mesh binormals (aka bitangent) +void MeshBinormals(Mesh *mesh) { - // Unload material shader (avoid unloading default shader, managed by raylib) - if (material.shader.id != GetShaderDefault().id) UnloadShader(material.shader); - - // Unload loaded texture maps (avoid unloading default texture, managed by raylib) - for (int i = 0; i < MAX_MATERIAL_MAPS; i++) + for (int i = 0; i < mesh->vertexCount; i++) { - if (material.maps[i].texture.id != GetTextureDefault().id) rlDeleteTextures(material.maps[i].texture.id); + Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; + Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; + float tangentW = mesh->tangents[i*4 + 3]; + + // TODO: Register computed binormal in mesh->binormal? + // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); } } @@ -2239,129 +2696,6 @@ RayHitInfo GetCollisionRayGround(Ray ray, float groundHeight) return result; } -// Compute mesh bounding box limits -// NOTE: minVertex and maxVertex should be transformed by model transform matrix -BoundingBox MeshBoundingBox(Mesh mesh) -{ - // Get min and max vertex to construct bounds (AABB) - Vector3 minVertex = { 0 }; - Vector3 maxVertex = { 0 }; - - printf("Mesh vertex count: %i\n", mesh.vertexCount); - - if (mesh.vertices != NULL) - { - minVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - maxVertex = (Vector3){ mesh.vertices[0], mesh.vertices[1], mesh.vertices[2] }; - - for (int i = 1; i < mesh.vertexCount; i++) - { - minVertex = Vector3Min(minVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - maxVertex = Vector3Max(maxVertex, (Vector3){ mesh.vertices[i*3], mesh.vertices[i*3 + 1], mesh.vertices[i*3 + 2] }); - } - } - - // Create the bounding box - BoundingBox box = { 0 }; - box.min = minVertex; - box.max = maxVertex; - - return box; -} - -// Compute mesh tangents -// NOTE: To calculate mesh tangents and binormals we need mesh vertex positions and texture coordinates -// Implementation base don: https://answers.unity.com/questions/7789/calculating-tangents-vector4.html -void MeshTangents(Mesh *mesh) -{ - if (mesh->tangents == NULL) mesh->tangents = (float *)malloc(mesh->vertexCount*4*sizeof(float)); - else TraceLog(LOG_WARNING, "Mesh tangents already exist"); - - Vector3 *tan1 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - Vector3 *tan2 = (Vector3 *)malloc(mesh->vertexCount*sizeof(Vector3)); - - for (int i = 0; i < mesh->vertexCount; i += 3) - { - // Get triangle vertices - Vector3 v1 = { mesh->vertices[(i + 0)*3 + 0], mesh->vertices[(i + 0)*3 + 1], mesh->vertices[(i + 0)*3 + 2] }; - Vector3 v2 = { mesh->vertices[(i + 1)*3 + 0], mesh->vertices[(i + 1)*3 + 1], mesh->vertices[(i + 1)*3 + 2] }; - Vector3 v3 = { mesh->vertices[(i + 2)*3 + 0], mesh->vertices[(i + 2)*3 + 1], mesh->vertices[(i + 2)*3 + 2] }; - - // Get triangle texcoords - Vector2 uv1 = { mesh->texcoords[(i + 0)*2 + 0], mesh->texcoords[(i + 0)*2 + 1] }; - Vector2 uv2 = { mesh->texcoords[(i + 1)*2 + 0], mesh->texcoords[(i + 1)*2 + 1] }; - Vector2 uv3 = { mesh->texcoords[(i + 2)*2 + 0], mesh->texcoords[(i + 2)*2 + 1] }; - - float x1 = v2.x - v1.x; - float y1 = v2.y - v1.y; - float z1 = v2.z - v1.z; - float x2 = v3.x - v1.x; - float y2 = v3.y - v1.y; - float z2 = v3.z - v1.z; - - float s1 = uv2.x - uv1.x; - float t1 = uv2.y - uv1.y; - float s2 = uv3.x - uv1.x; - float t2 = uv3.y - uv1.y; - - float div = s1*t2 - s2*t1; - float r = (div == 0.0f)? 0.0f : 1.0f/div; - - Vector3 sdir = { (t2*x1 - t1*x2)*r, (t2*y1 - t1*y2)*r, (t2*z1 - t1*z2)*r }; - Vector3 tdir = { (s1*x2 - s2*x1)*r, (s1*y2 - s2*y1)*r, (s1*z2 - s2*z1)*r }; - - tan1[i + 0] = sdir; - tan1[i + 1] = sdir; - tan1[i + 2] = sdir; - - tan2[i + 0] = tdir; - tan2[i + 1] = tdir; - tan2[i + 2] = tdir; - } - - // Compute tangents considering normals - for (int i = 0; i < mesh->vertexCount; ++i) - { - Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; - Vector3 tangent = tan1[i]; - - // TODO: Review, not sure if tangent computation is right, just used reference proposed maths... - #if defined(COMPUTE_TANGENTS_METHOD_01) - Vector3 tmp = Vector3Subtract(tangent, Vector3Multiply(normal, Vector3DotProduct(normal, tangent))); - tmp = Vector3Normalize(tmp); - mesh->tangents[i*4 + 0] = tmp.x; - mesh->tangents[i*4 + 1] = tmp.y; - mesh->tangents[i*4 + 2] = tmp.z; - mesh->tangents[i*4 + 3] = 1.0f; - #else - Vector3OrthoNormalize(&normal, &tangent); - mesh->tangents[i*4 + 0] = tangent.x; - mesh->tangents[i*4 + 1] = tangent.y; - mesh->tangents[i*4 + 2] = tangent.z; - mesh->tangents[i*4 + 3] = (Vector3DotProduct(Vector3CrossProduct(normal, tangent), tan2[i]) < 0.0f)? -1.0f : 1.0f; - #endif - } - - free(tan1); - free(tan2); - - TraceLog(LOG_INFO, "Tangents computed for mesh"); -} - -// Compute mesh binormals (aka bitangent) -void MeshBinormals(Mesh *mesh) -{ - for (int i = 0; i < mesh->vertexCount; i++) - { - Vector3 normal = { mesh->normals[i*3 + 0], mesh->normals[i*3 + 1], mesh->normals[i*3 + 2] }; - Vector3 tangent = { mesh->tangents[i*4 + 0], mesh->tangents[i*4 + 1], mesh->tangents[i*4 + 2] }; - float tangentW = mesh->tangents[i*4 + 3]; - - // TODO: Register computed binormal in mesh->binormal? - // Vector3 binormal = Vector3Multiply(Vector3CrossProduct(normal, tangent), tangentW); - } -} - //---------------------------------------------------------------------------------- // Module specific Functions Definition //---------------------------------------------------------------------------------- diff --git a/src/raylib.h b/src/raylib.h index c365fa47..55943baf 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -752,7 +752,7 @@ typedef enum { MAP_IRRADIANCE, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_PREFILTER, // NOTE: Uses GL_TEXTURE_CUBE_MAP MAP_BRDF -} TexmapIndex; +} MaterialMapType; #define MAP_DIFFUSE MAP_ALBEDO #define MAP_SPECULAR MAP_METALNESS @@ -1256,16 +1256,25 @@ RLAPI void DrawGizmo(Vector3 position); // Model loading/unloading functions RLAPI Model LoadModel(const char *fileName); // Load model from files (meshes and materials) RLAPI Model LoadModelFromMesh(Mesh mesh); // Load model from generated mesh -//RLAPI void LoadModelAnimations(const char fileName, ModelAnimation *anims, int *animsCount); // Load model animations from file -//RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose RLAPI void UnloadModel(Model model); // Unload model from memory (RAM and/or VRAM) -// Mesh manipulation functions -RLAPI BoundingBox MeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits -RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents -RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals -RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) +// Mesh loading/unloading functions +RLAPI Mesh *LoadMeshes(const char *fileName, int *meshCount); // Load meshes from model file RLAPI void ExportMesh(Mesh mesh, const char *fileName); // Export mesh data to file +RLAPI void UnloadMesh(Mesh *mesh); // Unload mesh from memory (RAM and/or VRAM) + +// Material loading/unloading functions +RLAPI Material *LoadMaterials(const char *fileName, int *materialCount); // Load materials from model file +RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) +RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +RLAPI void SetMaterialTexture(Material *material, int mapType, Texture2D texture); // Set texture for a material map type (MAP_DIFFUSE, MAP_SPECULAR...) +RLAPI void SetModelMeshMaterial(Model *model, int meshId, int materialId); // Set material for a mesh + +// Model animations loading/unloading functions +RLAPI ModelAnimation *LoadModelAnimations(const char *fileName, int *animsCount); // Load model animations from file +RLAPI void UpdateModelAnimation(Model model, ModelAnimation anim, int frame); // Update model animation pose +RLAPI void UnloadModelAnimation(ModelAnimation anim); // Unload animation data +RLAPI bool IsModelAnimationValid(Model model, ModelAnimation anim); // Check model animation skeleton match // Mesh generation functions RLAPI Mesh GenMeshPoly(int sides, float radius); // Generate polygonal mesh @@ -1279,10 +1288,10 @@ RLAPI Mesh GenMeshKnot(float radius, float size, int radSeg, int sides); RLAPI Mesh GenMeshHeightmap(Image heightmap, Vector3 size); // Generate heightmap mesh from image data RLAPI Mesh GenMeshCubicmap(Image cubicmap, Vector3 cubeSize); // Generate cubes-based map mesh from image data -// Material loading/unloading functions -RLAPI Material LoadMaterial(const char *fileName); // Load material from file -RLAPI Material LoadMaterialDefault(void); // Load default material (Supports: DIFFUSE, SPECULAR, NORMAL maps) -RLAPI void UnloadMaterial(Material material); // Unload material from GPU memory (VRAM) +// Mesh manipulation functions +RLAPI BoundingBox MeshBoundingBox(Mesh mesh); // Compute mesh bounding box limits +RLAPI void MeshTangents(Mesh *mesh); // Compute mesh tangents +RLAPI void MeshBinormals(Mesh *mesh); // Compute mesh binormals // Model drawing functions RLAPI void DrawModel(Model model, Vector3 position, float scale, Color tint); // Draw a model (with texture if set) -- cgit v1.2.3 From c600dd07668f301fc1a986326d807f341e6ecb78 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 16:43:09 +0200 Subject: Review PBR shaders Issue was related to vertex tangent attibutes not uploaded to GPU, a quick solution was implemented for new vertex attributes loading for already existing meshes... I don't like it specially but it will work for now. --- examples/models/models_material_pbr.c | 8 ++++++++ examples/models/resources/shaders/brdf.fs | 4 ++-- examples/models/resources/shaders/irradiance.fs | 4 ++-- examples/models/resources/shaders/prefilter.fs | 4 ++-- src/models.c | 3 +++ src/rlgl.h | 24 ++++++++++++++++++++++++ 6 files changed, 41 insertions(+), 6 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index adb4762b..d393a20d 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -38,7 +38,11 @@ int main() // Load model and PBR material Model model = LoadModel("resources/pbr/trooper.obj"); + + // Mesh tangents are generated... and uploaded to GPU + // NOTE: New VBO for tangents is generated at default location and also binded to mesh VAO MeshTangents(&model.meshes[0]); + model.materials[0] = LoadMaterialPBR((Color){ 255, 255, 255, 255 }, 1.0f, 1.0f); // Define lights attributes @@ -143,9 +147,13 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) #define PATH_BRDF_FS "resources/shaders/brdf.fs" // Path to bidirectional reflectance distribution function fragment shader Shader shdrCubemap = LoadShader(PATH_CUBEMAP_VS, PATH_CUBEMAP_FS); + printf("Loaded shader: cubemap\n"); Shader shdrIrradiance = LoadShader(PATH_SKYBOX_VS, PATH_IRRADIANCE_FS); + printf("Loaded shader: irradiance\n"); Shader shdrPrefilter = LoadShader(PATH_SKYBOX_VS, PATH_PREFILTER_FS); + printf("Loaded shader: prefilter\n"); Shader shdrBRDF = LoadShader(PATH_BRDF_VS, PATH_BRDF_FS); + printf("Loaded shader: brdf\n"); // Setup required shader locations SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); diff --git a/examples/models/resources/shaders/brdf.fs b/examples/models/resources/shaders/brdf.fs index 3e8777d2..d04bc661 100644 --- a/examples/models/resources/shaders/brdf.fs +++ b/examples/models/resources/shaders/brdf.fs @@ -10,13 +10,13 @@ #version 330 -#define MAX_SAMPLES 1024u // Input vertex attributes (from vertex shader) in vec2 fragTexCoord; // Constant values const float PI = 3.14159265359; +const uint MAX_SAMPLES = 1024u; // Output fragment color out vec4 finalColor; @@ -93,7 +93,7 @@ vec2 IntegrateBRDF(float NdotV, float roughness) vec3 V = vec3(sqrt(1.0 - NdotV*NdotV), 0.0, NdotV); vec3 N = vec3(0.0, 0.0, 1.0); - for (int i = 0; i < MAX_SAMPLES; i++) + for (uint i = 0u; i < MAX_SAMPLES; i++) { // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) diff --git a/examples/models/resources/shaders/irradiance.fs b/examples/models/resources/shaders/irradiance.fs index 87113673..b42d2143 100644 --- a/examples/models/resources/shaders/irradiance.fs +++ b/examples/models/resources/shaders/irradiance.fs @@ -9,7 +9,7 @@ #version 330 // Input vertex attributes (from vertex shader) -in vec3 fragPos; +in vec3 fragPosition; // Input uniform values uniform samplerCube environmentMap; @@ -23,7 +23,7 @@ out vec4 finalColor; void main() { // The sample direction equals the hemisphere's orientation - vec3 normal = normalize(fragPos); + vec3 normal = normalize(fragPosition); vec3 irradiance = vec3(0.0); diff --git a/examples/models/resources/shaders/prefilter.fs b/examples/models/resources/shaders/prefilter.fs index f5cf64be..9439810d 100644 --- a/examples/models/resources/shaders/prefilter.fs +++ b/examples/models/resources/shaders/prefilter.fs @@ -11,7 +11,7 @@ #define CUBEMAP_RESOLUTION 1024.0 // Input vertex attributes (from vertex shader) -in vec3 fragPos; +in vec3 fragPosition; // Input uniform values uniform samplerCube environmentMap; @@ -79,7 +79,7 @@ vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) void main() { // Make the simplyfying assumption that V equals R equals the normal - vec3 N = normalize(fragPos); + vec3 N = normalize(fragPosition); vec3 R = N; vec3 V = R; diff --git a/src/models.c b/src/models.c index e437a0ab..7a9acdf7 100644 --- a/src/models.c +++ b/src/models.c @@ -2302,6 +2302,9 @@ void MeshTangents(Mesh *mesh) free(tan1); free(tan2); + + // Load a new tangent attributes buffer + mesh->vboId[LOC_VERTEX_TANGENT] = rlLoadAttribBuffer(mesh->vaoId, LOC_VERTEX_TANGENT, mesh->tangents, mesh->vertexCount*4*sizeof(float), false); TraceLog(LOG_INFO, "Tangents computed for mesh"); } diff --git a/src/rlgl.h b/src/rlgl.h index 3d433377..bf50ad0d 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -456,6 +456,7 @@ void rlDeleteBuffers(unsigned int id); // Unload vertex data (V void rlClearColor(byte r, byte g, byte b, byte a); // Clear color buffer with color void rlClearScreenBuffers(void); // Clear used screen buffers (color and depth) void rlUpdateBuffer(int bufferId, void *data, int dataSize); // Update GPU buffer with new data +unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic); // Load a new attributes buffer //------------------------------------------------------------------------------------ // Functions Declaration - rlgl functionality @@ -2532,6 +2533,29 @@ void rlLoadMesh(Mesh *mesh, bool dynamic) #endif } +// Load a new attributes buffer +unsigned int rlLoadAttribBuffer(unsigned int vaoId, int shaderLoc, void *buffer, int size, bool dynamic) +{ + unsigned int id = 0; + +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + int drawHint = GL_STATIC_DRAW; + if (dynamic) drawHint = GL_DYNAMIC_DRAW; + + if (vaoSupported) glBindVertexArray(vaoId); + + glGenBuffers(1, &id); + glBindBuffer(GL_ARRAY_BUFFER, id); + glBufferData(GL_ARRAY_BUFFER, size, buffer, drawHint); + glVertexAttribPointer(shaderLoc, 2, GL_FLOAT, 0, 0, 0); + glEnableVertexAttribArray(shaderLoc); + + if (vaoSupported) glBindVertexArray(0); +#endif + + return id; +} + // Update vertex data on GPU (upload new data to one buffer) void rlUpdateMesh(Mesh mesh, int buffer, int numVertex) { -- cgit v1.2.3 From 9282b8ba83909b353fd34a9f584597338c1928bd Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 17:08:46 +0200 Subject: ADDED: SetShaderValueTexture() Some tweaks --- examples/models/models_material_pbr.c | 7 ++++++- src/raylib.h | 3 ++- src/rlgl.h | 16 ++++++++++++++-- 3 files changed, 22 insertions(+), 4 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index d393a20d..c1d43a24 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -34,7 +34,12 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [models] example - pbr material"); // Define the camera to look into our 3d world - Camera camera = {{ 4.0f, 4.0f, 4.0f }, { 0.0f, 0.5f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { 0 }; + camera.position = (Vector3){ 4.0f, 4.0f, 4.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.5f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.type = CAMERA_PERSPECTIVE; // Camera mode type // Load model and PBR material Model model = LoadModel("resources/pbr/trooper.obj"); diff --git a/src/raylib.h b/src/raylib.h index 55943baf..dc864b8d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1331,7 +1331,8 @@ RLAPI Texture2D GetTextureDefault(void); // Get RLAPI int GetShaderLocation(Shader shader, const char *uniformName); // Get shader uniform location RLAPI void SetShaderValue(Shader shader, int uniformLoc, const void *value, int uniformType); // Set shader uniform value RLAPI void SetShaderValueV(Shader shader, int uniformLoc, const void *value, int uniformType, int count); // Set shader uniform value vector -RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat); // Set shader uniform value (matrix 4x4) +RLAPI void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture); // Set shader uniform value for texture RLAPI void SetMatrixProjection(Matrix proj); // Set a custom projection matrix (replaces internal projection matrix) RLAPI void SetMatrixModelview(Matrix view); // Set a custom modelview matrix (replaces internal modelview matrix) RLAPI Matrix GetMatrixModelview(); // Get internal modelview matrix diff --git a/src/rlgl.h b/src/rlgl.h index bf50ad0d..81f39d68 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -207,8 +207,8 @@ typedef unsigned char byte; // Animation vertex data float *animVertices; // Animated vertex positions (after bones transformations) float *animNormals; // Animated normals (after bones transformations) - float *weightBias; // Vertex weight bias - int *weightId; // Vertex weight id + int *boneIds; // Vertex bone ids, up to 4 bones influence by vertex (skinning) + float *boneWeights; // Vertex bone weight, up to 4 bones influence by vertex (skinning) // OpenGL identifiers unsigned int vaoId; // OpenGL Vertex Array Object id @@ -3169,6 +3169,18 @@ void SetShaderValueMatrix(Shader shader, int uniformLoc, Matrix mat) #endif } +// Set shader uniform value for texture +void SetShaderValueTexture(Shader shader, int uniformLoc, Texture2D texture) +{ +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) + glUseProgram(shader.id); + + glUniform1i(uniformLoc, texture.id); + + //glUseProgram(0); +#endif +} + // Set a custom projection matrix (replaces internal projection matrix) void SetMatrixProjection(Matrix proj) { -- cgit v1.2.3 From c23ceec338ac46c28d0b1fe2ab286775efc7f041 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 5 Apr 2019 17:29:30 +0200 Subject: Added missing include -_- --- examples/models/models_material_pbr.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'examples/models') diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index c1d43a24..5c308cfc 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -12,6 +12,8 @@ #include "raylib.h" #include "raymath.h" +#include + #define RLIGHTS_IMPLEMENTATION #include "rlights.h" -- cgit v1.2.3 From f21761fbbb02f0b58b5b54342f0c3ad3abc0003e Mon Sep 17 00:00:00 2001 From: ChillerDragon Date: Sun, 7 Apr 2019 17:49:12 +0200 Subject: Happy new year 2019 --- examples/Makefile | 2 +- examples/audio/audio_raw_stream.c | 2 +- examples/models/models_obj_viewer.c | 2 +- examples/others/rlgl_standalone.c | 2 +- games/Makefile | 2 +- games/cat_vs_roomba/Makefile | 2 +- games/cat_vs_roomba/roomba.c | 2 +- games/cat_vs_roomba/screens/screen_ending.c | 2 +- games/cat_vs_roomba/screens/screen_gameplay.c | 2 +- games/cat_vs_roomba/screens/screen_logo.c | 2 +- games/cat_vs_roomba/screens/screen_title.c | 2 +- games/cat_vs_roomba/screens/screens.h | 2 +- games/drturtle/Makefile | 2 +- games/just_do/Makefile | 2 +- games/koala_seasons/Makefile | 2 +- games/light_my_ritual/Makefile | 2 +- games/skully_escape/Makefile | 2 +- games/transmission/Makefile | 2 +- games/transmission/screens/screen_ending.c | 2 +- games/transmission/screens/screen_gameplay.c | 2 +- games/transmission/screens/screen_logo.c | 2 +- games/transmission/screens/screen_mission.c | 2 +- games/transmission/screens/screen_title.c | 2 +- games/transmission/screens/screens.h | 2 +- games/transmission/transmission.c | 2 +- games/wave_collector/Makefile | 2 +- projects/VSCode/Makefile | 2 +- src/Makefile | 2 +- src/core.c | 2 +- src/gestures.h | 2 +- src/models.c | 2 +- src/raylib.h | 2 +- src/rglfw.c | 2 +- src/rlgl.h | 2 +- src/shapes.c | 2 +- src/text.c | 2 +- src/textures.c | 2 +- src/utils.c | 2 +- src/utils.h | 2 +- templates/advance_game/Makefile | 2 +- templates/advance_game/advance_game.c | 2 +- templates/advance_game/screens/screen_ending.c | 2 +- templates/advance_game/screens/screen_gameplay.c | 2 +- templates/advance_game/screens/screen_logo.c | 2 +- templates/advance_game/screens/screen_options.c | 2 +- templates/advance_game/screens/screen_title.c | 2 +- templates/advance_game/screens/screens.h | 2 +- templates/simple_game/Makefile | 2 +- templates/simple_game/simple_game.c | 2 +- templates/standard_game/Makefile | 2 +- templates/standard_game/screens/screen_ending.c | 2 +- templates/standard_game/screens/screen_gameplay.c | 2 +- templates/standard_game/screens/screen_logo.c | 2 +- templates/standard_game/screens/screen_options.c | 2 +- templates/standard_game/screens/screen_title.c | 2 +- templates/standard_game/screens/screens.h | 2 +- templates/standard_game/standard_game.c | 2 +- 57 files changed, 57 insertions(+), 57 deletions(-) (limited to 'examples/models') diff --git a/examples/Makefile b/examples/Makefile index e14762b3..b35e39f9 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/examples/audio/audio_raw_stream.c b/examples/audio/audio_raw_stream.c index 7eee46f6..d7fa5d79 100644 --- a/examples/audio/audio_raw_stream.c +++ b/examples/audio/audio_raw_stream.c @@ -7,7 +7,7 @@ * This example has been created using raylib 1.6 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2015-2018 Ramon Santamaria (@raysan5) and James Hofmann (@triplefox) +* Copyright (c) 2015-2019 Ramon Santamaria (@raysan5) and James Hofmann (@triplefox) * ********************************************************************************************/ diff --git a/examples/models/models_obj_viewer.c b/examples/models/models_obj_viewer.c index 0581df34..7d387441 100644 --- a/examples/models/models_obj_viewer.c +++ b/examples/models/models_obj_viewer.c @@ -5,7 +5,7 @@ * This example has been created using raylib 2.0 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/others/rlgl_standalone.c b/examples/others/rlgl_standalone.c index 4b262bbd..42aec2e2 100644 --- a/examples/others/rlgl_standalone.c +++ b/examples/others/rlgl_standalone.c @@ -24,7 +24,7 @@ * This example is licensed under an unmodified zlib/libpng license, which is an OSI-certified, * BSD-like license that allows static linking with closed source software: * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/Makefile b/games/Makefile index 5d60f15d..44e053c6 100644 --- a/games/Makefile +++ b/games/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/Makefile b/games/cat_vs_roomba/Makefile index 6662a6be..b1304656 100644 --- a/games/cat_vs_roomba/Makefile +++ b/games/cat_vs_roomba/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/roomba.c b/games/cat_vs_roomba/roomba.c index 0d236775..eeee7a71 100644 --- a/games/cat_vs_roomba/roomba.c +++ b/games/cat_vs_roomba/roomba.c @@ -8,7 +8,7 @@ * This game has been created using raylib (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/games/cat_vs_roomba/screens/screen_ending.c b/games/cat_vs_roomba/screens/screen_ending.c index ef2a5f74..466d9b91 100644 --- a/games/cat_vs_roomba/screens/screen_ending.c +++ b/games/cat_vs_roomba/screens/screen_ending.c @@ -4,7 +4,7 @@ * * Ending Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/screens/screen_gameplay.c b/games/cat_vs_roomba/screens/screen_gameplay.c index 49a0bb6b..4dd13856 100644 --- a/games/cat_vs_roomba/screens/screen_gameplay.c +++ b/games/cat_vs_roomba/screens/screen_gameplay.c @@ -4,7 +4,7 @@ * * Gameplay Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/screens/screen_logo.c b/games/cat_vs_roomba/screens/screen_logo.c index 9fc704c7..a697013e 100644 --- a/games/cat_vs_roomba/screens/screen_logo.c +++ b/games/cat_vs_roomba/screens/screen_logo.c @@ -4,7 +4,7 @@ * * Logo Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/screens/screen_title.c b/games/cat_vs_roomba/screens/screen_title.c index 009fbd0a..6acadce5 100644 --- a/games/cat_vs_roomba/screens/screen_title.c +++ b/games/cat_vs_roomba/screens/screen_title.c @@ -4,7 +4,7 @@ * * Title Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/cat_vs_roomba/screens/screens.h b/games/cat_vs_roomba/screens/screens.h index 9cc07eab..0ad4f9af 100644 --- a/games/cat_vs_roomba/screens/screens.h +++ b/games/cat_vs_roomba/screens/screens.h @@ -4,7 +4,7 @@ * * Screens Functions Declarations (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/drturtle/Makefile b/games/drturtle/Makefile index 8f1934b5..4cd5033e 100644 --- a/games/drturtle/Makefile +++ b/games/drturtle/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/just_do/Makefile b/games/just_do/Makefile index b6c935f6..af9b31c1 100644 --- a/games/just_do/Makefile +++ b/games/just_do/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/koala_seasons/Makefile b/games/koala_seasons/Makefile index 8482bf2d..25dbe696 100644 --- a/games/koala_seasons/Makefile +++ b/games/koala_seasons/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/light_my_ritual/Makefile b/games/light_my_ritual/Makefile index fbc34aac..3291bb3e 100644 --- a/games/light_my_ritual/Makefile +++ b/games/light_my_ritual/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/skully_escape/Makefile b/games/skully_escape/Makefile index 8875ad52..4673a549 100644 --- a/games/skully_escape/Makefile +++ b/games/skully_escape/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/Makefile b/games/transmission/Makefile index a1b7e764..f62fe080 100644 --- a/games/transmission/Makefile +++ b/games/transmission/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screen_ending.c b/games/transmission/screens/screen_ending.c index bb355b8b..0492a0cc 100644 --- a/games/transmission/screens/screen_ending.c +++ b/games/transmission/screens/screen_ending.c @@ -4,7 +4,7 @@ * * Ending Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screen_gameplay.c b/games/transmission/screens/screen_gameplay.c index ee70632a..3dfce714 100644 --- a/games/transmission/screens/screen_gameplay.c +++ b/games/transmission/screens/screen_gameplay.c @@ -4,7 +4,7 @@ * * Gameplay Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screen_logo.c b/games/transmission/screens/screen_logo.c index 37543302..dc016423 100644 --- a/games/transmission/screens/screen_logo.c +++ b/games/transmission/screens/screen_logo.c @@ -4,7 +4,7 @@ * * Logo Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screen_mission.c b/games/transmission/screens/screen_mission.c index 1cd2563b..77777c73 100644 --- a/games/transmission/screens/screen_mission.c +++ b/games/transmission/screens/screen_mission.c @@ -3,7 +3,7 @@ * raylib - transmission mission * * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screen_title.c b/games/transmission/screens/screen_title.c index 2a30a6ba..e9023b08 100644 --- a/games/transmission/screens/screen_title.c +++ b/games/transmission/screens/screen_title.c @@ -3,7 +3,7 @@ * raylib - transmission mission * * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/screens/screens.h b/games/transmission/screens/screens.h index be5e31d9..49698f0d 100644 --- a/games/transmission/screens/screens.h +++ b/games/transmission/screens/screens.h @@ -4,7 +4,7 @@ * * Screens Functions Declarations (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/games/transmission/transmission.c b/games/transmission/transmission.c index 91ca28c1..9fc3d802 100644 --- a/games/transmission/transmission.c +++ b/games/transmission/transmission.c @@ -7,7 +7,7 @@ * This game has been created using raylib (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/games/wave_collector/Makefile b/games/wave_collector/Makefile index 06e74799..703383b8 100644 --- a/games/wave_collector/Makefile +++ b/games/wave_collector/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/projects/VSCode/Makefile b/projects/VSCode/Makefile index 747718fc..3cffaaba 100644 --- a/projects/VSCode/Makefile +++ b/projects/VSCode/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/src/Makefile b/src/Makefile index e2fe6c5d..0217c198 100644 --- a/src/Makefile +++ b/src/Makefile @@ -14,7 +14,7 @@ # Many thanks to Milan Nikolic (@gen2brain) for implementing Android platform pipeline. # Many thanks to Emanuele Petriglia for his contribution on GNU/Linux pipeline. # -# Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. # In no event will the authors be held liable for any damages arising from diff --git a/src/core.c b/src/core.c index b0c0658d..42db214f 100644 --- a/src/core.c +++ b/src/core.c @@ -68,7 +68,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/gestures.h b/src/gestures.h index a4546eb1..36775333 100644 --- a/src/gestures.h +++ b/src/gestures.h @@ -24,7 +24,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/models.c b/src/models.c index 7a9acdf7..07f8203b 100644 --- a/src/models.c +++ b/src/models.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/raylib.h b/src/raylib.h index dc864b8d..dade7aba 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -49,7 +49,7 @@ * raylib is licensed under an unmodified zlib/libpng license, which is an OSI-certified, * BSD-like license that allows static linking with closed source software: * -* Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/rglfw.c b/src/rglfw.c index 853c5200..3463bb96 100644 --- a/src/rglfw.c +++ b/src/rglfw.c @@ -7,7 +7,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2017-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2017-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/rlgl.h b/src/rlgl.h index 81f39d68..3e428241 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -42,7 +42,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/shapes.c b/src/shapes.c index b7f7e3df..fbc70fc4 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -14,7 +14,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/text.c b/src/text.c index d44cdd11..cd7a6802 100644 --- a/src/text.c +++ b/src/text.c @@ -17,7 +17,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/textures.c b/src/textures.c index cd0bd208..5189b635 100644 --- a/src/textures.c +++ b/src/textures.c @@ -38,7 +38,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/utils.c b/src/utils.c index 6b174354..10cce9b9 100644 --- a/src/utils.c +++ b/src/utils.c @@ -11,7 +11,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/src/utils.h b/src/utils.h index 08b33962..d7ab8829 100644 --- a/src/utils.h +++ b/src/utils.h @@ -5,7 +5,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/Makefile b/templates/advance_game/Makefile index 2e5d6e26..e475f72c 100644 --- a/templates/advance_game/Makefile +++ b/templates/advance_game/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/advance_game.c b/templates/advance_game/advance_game.c index 48a34f6d..3fb5d657 100644 --- a/templates/advance_game/advance_game.c +++ b/templates/advance_game/advance_game.c @@ -8,7 +8,7 @@ * This game has been created using raylib (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/templates/advance_game/screens/screen_ending.c b/templates/advance_game/screens/screen_ending.c index 66b5ddf9..62d1267a 100644 --- a/templates/advance_game/screens/screen_ending.c +++ b/templates/advance_game/screens/screen_ending.c @@ -4,7 +4,7 @@ * * Ending Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/screens/screen_gameplay.c b/templates/advance_game/screens/screen_gameplay.c index 8943adb5..8ea61491 100644 --- a/templates/advance_game/screens/screen_gameplay.c +++ b/templates/advance_game/screens/screen_gameplay.c @@ -4,7 +4,7 @@ * * Gameplay Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/screens/screen_logo.c b/templates/advance_game/screens/screen_logo.c index 6282e83e..8badbf52 100644 --- a/templates/advance_game/screens/screen_logo.c +++ b/templates/advance_game/screens/screen_logo.c @@ -4,7 +4,7 @@ * * Logo Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/screens/screen_options.c b/templates/advance_game/screens/screen_options.c index dc8d74fa..4b58da13 100644 --- a/templates/advance_game/screens/screen_options.c +++ b/templates/advance_game/screens/screen_options.c @@ -4,7 +4,7 @@ * * Options Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/screens/screen_title.c b/templates/advance_game/screens/screen_title.c index 5727546a..8e74a027 100644 --- a/templates/advance_game/screens/screen_title.c +++ b/templates/advance_game/screens/screen_title.c @@ -4,7 +4,7 @@ * * Title Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/advance_game/screens/screens.h b/templates/advance_game/screens/screens.h index 4d7f9b53..7c2dfb48 100644 --- a/templates/advance_game/screens/screens.h +++ b/templates/advance_game/screens/screens.h @@ -4,7 +4,7 @@ * * Screens Functions Declarations (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/simple_game/Makefile b/templates/simple_game/Makefile index 86e0dbde..9f27a429 100644 --- a/templates/simple_game/Makefile +++ b/templates/simple_game/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/simple_game/simple_game.c b/templates/simple_game/simple_game.c index 028b1da8..8f2dc36a 100644 --- a/templates/simple_game/simple_game.c +++ b/templates/simple_game/simple_game.c @@ -8,7 +8,7 @@ * This game has been created using raylib (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/templates/standard_game/Makefile b/templates/standard_game/Makefile index b9c6c188..4333c8b8 100644 --- a/templates/standard_game/Makefile +++ b/templates/standard_game/Makefile @@ -2,7 +2,7 @@ # # raylib makefile for Desktop platforms, Raspberry Pi, Android and HTML5 # -# Copyright (c) 2013-2018 Ramon Santamaria (@raysan5) +# Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) # # This software is provided "as-is", without any express or implied warranty. In no event # will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screen_ending.c b/templates/standard_game/screens/screen_ending.c index 87196977..1bd5ce98 100644 --- a/templates/standard_game/screens/screen_ending.c +++ b/templates/standard_game/screens/screen_ending.c @@ -4,7 +4,7 @@ * * Ending Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screen_gameplay.c b/templates/standard_game/screens/screen_gameplay.c index 7f108265..427e5ba7 100644 --- a/templates/standard_game/screens/screen_gameplay.c +++ b/templates/standard_game/screens/screen_gameplay.c @@ -4,7 +4,7 @@ * * Gameplay Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screen_logo.c b/templates/standard_game/screens/screen_logo.c index c0b60571..435ea241 100644 --- a/templates/standard_game/screens/screen_logo.c +++ b/templates/standard_game/screens/screen_logo.c @@ -4,7 +4,7 @@ * * Logo Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screen_options.c b/templates/standard_game/screens/screen_options.c index 9f6690d1..df68dd26 100644 --- a/templates/standard_game/screens/screen_options.c +++ b/templates/standard_game/screens/screen_options.c @@ -4,7 +4,7 @@ * * Options Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screen_title.c b/templates/standard_game/screens/screen_title.c index 328448ba..5bd33825 100644 --- a/templates/standard_game/screens/screen_title.c +++ b/templates/standard_game/screens/screen_title.c @@ -4,7 +4,7 @@ * * Title Screen Functions Definitions (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/screens/screens.h b/templates/standard_game/screens/screens.h index e961b533..9450c29f 100644 --- a/templates/standard_game/screens/screens.h +++ b/templates/standard_game/screens/screens.h @@ -4,7 +4,7 @@ * * Screens Functions Declarations (Init, Update, Draw, Unload) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * * This software is provided "as-is", without any express or implied warranty. In no event * will the authors be held liable for any damages arising from the use of this software. diff --git a/templates/standard_game/standard_game.c b/templates/standard_game/standard_game.c index 8871484e..7918562c 100644 --- a/templates/standard_game/standard_game.c +++ b/templates/standard_game/standard_game.c @@ -8,7 +8,7 @@ * This game has been created using raylib (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2018 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ -- cgit v1.2.3 From 600cdb61a306cd1d5dd78679c0acceb91287b193 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 23 Apr 2019 23:28:11 +0200 Subject: new example: models_first_person_maze -WIP- --- examples/models/models_first_person_maze.c | 84 +++++++++++++++++++++++++++ examples/models/models_first_person_maze.png | Bin 0 -> 327996 bytes 2 files changed, 84 insertions(+) create mode 100644 examples/models/models_first_person_maze.c create mode 100644 examples/models/models_first_person_maze.png (limited to 'examples/models') diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c new file mode 100644 index 00000000..4342b178 --- /dev/null +++ b/examples/models/models_first_person_maze.c @@ -0,0 +1,84 @@ +/******************************************************************************************* +* +* raylib [models] example - first person maze +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2019 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze"); + + // Define the camera to look into our 3d world + Camera camera = {{ 0.2f, 0.4f, 0.2f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + + Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) + Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM) + Mesh mesh = GenMeshCubicmap(image, (Vector3){ 1.0f, 1.0f, 1.0f }); + Model model = LoadModelFromMesh(mesh); + UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM + + // NOTE: By default each cube is mapped to one part of texture atlas + Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture + model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture + + Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position + Vector3 playerPosition = camera.position; // Set player position + + SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set camera mode + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + UpdateCamera(&camera); // Update camera + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawModel(model, mapPosition, 1.0f, WHITE); // Draw maze map + //DrawCubeV(playerPosition, (Vector3){ 0.2f, 0.4f, 0.2f }, RED); // Draw player + + EndMode3D(); + + DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); + DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); + + DrawFPS(10, 10); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadTexture(cubicmap); // Unload cubicmap texture + UnloadTexture(texture); // Unload map texture + UnloadModel(model); // Unload map model + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/models/models_first_person_maze.png b/examples/models/models_first_person_maze.png new file mode 100644 index 00000000..ed6047e1 Binary files /dev/null and b/examples/models/models_first_person_maze.png differ -- cgit v1.2.3 From d46160fb6e85403f67975457631ba4f19824fc6f Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 2 May 2019 12:22:15 +0200 Subject: example review: models_first_person_maze Added walls collision check --- examples/models/models_first_person_maze.c | 48 +++++++++++++++++++++++++++--- 1 file changed, 44 insertions(+), 4 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index 4342b178..be101758 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -23,16 +23,19 @@ int main() // Define the camera to look into our 3d world Camera camera = {{ 0.2f, 0.4f, 0.2f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; - Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) - Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM) - Mesh mesh = GenMeshCubicmap(image, (Vector3){ 1.0f, 1.0f, 1.0f }); + Image imMap = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) + Texture2D cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM) + Mesh mesh = GenMeshCubicmap(imMap, (Vector3){ 1.0f, 1.0f, 1.0f }); Model model = LoadModelFromMesh(mesh); - UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM // NOTE: By default each cube is mapped to one part of texture atlas Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture + // Get map image data to be used for collision detection + Color *mapPixels = GetImageData(imMap); + UnloadImage(imMap); // Unload image from RAM + Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position Vector3 playerPosition = camera.position; // Set player position @@ -46,7 +49,39 @@ int main() { // Update //---------------------------------------------------------------------------------- + Vector3 oldCamPos = camera.position; // Store old camera position + UpdateCamera(&camera); // Update camera + + // Check player collision (we simplify to 2D collision detection) + Vector2 playerPos = { camera.position.x, camera.position.z }; + float playerRadius = 0.1f; // Collision radius (player is modelled as a cilinder for collision) + + int playerCellX = (int)(playerPos.x - mapPosition.x + 0.5f); + int playerCellY = (int)(playerPos.y - mapPosition.z + 0.5f); + + // Out-of-limits security check + if (playerCellX < 0) playerCellX = 0; + else if (playerCellX >= cubicmap.width) playerCellX = cubicmap.width - 1; + + if (playerCellY < 0) playerCellY = 0; + else if (playerCellY >= cubicmap.height) playerCellY = cubicmap.height - 1; + + // Check map collisions using image data and player position + // TODO: Improvement: Just check player surrounding cells for collision + for (int y = 0; y < cubicmap.height; y++) + { + for (int x = 0; x < cubicmap.width; x++) + { + if ((mapPixels[y*cubicmap.width + x].r == 255) && // Collision: white pixel, only check R channel + (CheckCollisionCircleRec(playerPos, playerRadius, + (Rectangle){ mapPosition.x - 0.5f + x*1.0f, mapPosition.z - 0.5f + y*1.0f, 1.0f, 1.0f }))) + { + // Collision detected, reset camera position + camera.position = oldCamPos; + } + } + } //---------------------------------------------------------------------------------- // Draw @@ -64,6 +99,9 @@ int main() DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); + + // Draw player position radar + DrawRectangle(GetScreenWidth() - cubicmap.width*4 - 20 + playerCellX*4, 20 + playerCellY*4, 4, 4, RED); DrawFPS(10, 10); @@ -73,6 +111,8 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- + free(mapPixels); // Unload color array + UnloadTexture(cubicmap); // Unload cubicmap texture UnloadTexture(texture); // Unload map texture UnloadModel(model); // Unload map model -- cgit v1.2.3 From beda4180cd03166d06f37ba50eb050283c4907e1 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 2 May 2019 13:15:05 +0200 Subject: Added missing include --- examples/models/models_first_person_maze.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'examples/models') diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index be101758..6e6b3214 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -11,6 +11,8 @@ #include "raylib.h" +#include "" // Required for: free() + int main() { // Initialization -- cgit v1.2.3 From 0b2bad4205d0322455ef4535342264dd675c1942 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 2 May 2019 13:24:02 +0200 Subject: Update models_first_person_maze.c --- examples/models/models_first_person_maze.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'examples/models') diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index 6e6b3214..093334ba 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -11,7 +11,7 @@ #include "raylib.h" -#include "" // Required for: free() +#include // Required for: free() int main() { -- cgit v1.2.3 From 424d3ca8d9c5d612606444b2a2099cfad37f1888 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 14 May 2019 15:34:23 +0200 Subject: examples review Redesigns, deletes and renames Also noted authors propertly on contributed examples --- examples/core/core_3d_camera_mode.c | 73 ++++++++ examples/core/core_3d_camera_mode.png | Bin 0 -> 8492 bytes examples/core/core_3d_mode.c | 73 -------- examples/core/core_3d_mode.png | Bin 8492 -> 0 bytes examples/core/core_color_select.c | 94 ---------- examples/core/core_color_select.png | Bin 14328 -> 0 bytes examples/core/core_custom_logging.c | 4 +- examples/core/core_gestures_detection.c | 115 ------------ examples/core/core_gestures_detection.png | Bin 19480 -> 0 bytes examples/core/core_input_gestures.c | 115 ++++++++++++ examples/core/core_input_gestures.png | Bin 0 -> 19480 bytes examples/core/core_input_mouse_wheel.c | 58 ++++++ examples/core/core_input_mouse_wheel.png | Bin 0 -> 15375 bytes examples/core/core_input_multitouch.c | 4 +- examples/core/core_loading_thread.c | 88 +++++---- examples/core/core_mouse_wheel.c | 58 ------ examples/core/core_mouse_wheel.png | Bin 15375 -> 0 bytes examples/core/core_window_letterbox.c | 90 +++++++++ examples/core/core_window_letterbox.png | Bin 0 -> 17967 bytes examples/core/core_window_scale_letterbox.c | 88 --------- examples/core/core_window_scale_letterbox.png | Bin 17967 -> 0 bytes examples/models/models_orthographic_projection.c | 6 +- examples/models/models_yaw_pitch_roll.c | 4 +- examples/shaders/shaders_julia_set.c | 208 +++++++++------------ examples/shaders/shaders_palette_switch.c | 4 +- examples/shaders/shaders_texture_drawing.c | 2 + examples/shaders/shaders_texture_waves.c | 4 +- examples/shapes/shapes_colors_palette.c | 114 +++++------ examples/shapes/shapes_colors_palette.png | Bin 6591 -> 18089 bytes examples/shapes/shapes_draw_circle_sector.c | 4 +- examples/shapes/shapes_draw_rectangle_rounded.c | 4 +- examples/shapes/shapes_draw_ring.c | 4 +- examples/shapes/shapes_rectangle_scaling.c | 94 ++++++++++ examples/shapes/shapes_rectangle_scaling.png | Bin 0 -> 15191 bytes examples/shapes/shapes_rectangle_scaling_mouse.c | 92 --------- examples/shapes/shapes_rectangle_scaling_mouse.png | Bin 15191 -> 0 bytes examples/text/text_bmfont_ttf.c | 40 ++-- examples/text/text_bmfont_ttf.png | Bin 19542 -> 20086 bytes examples/text/text_bmfont_unordered.c | 65 ------- examples/text/text_bmfont_unordered.png | Bin 18713 -> 0 bytes examples/text/text_draw_inside_rectangle.c | 120 ------------ examples/text/text_draw_inside_rectangle.png | Bin 17844 -> 0 bytes examples/text/text_rectangle_bounds.c | 120 ++++++++++++ examples/text/text_rectangle_bounds.png | Bin 0 -> 17844 bytes examples/text/text_unicode.c | 2 + examples/textures/textures_image_npatch.c | 108 ----------- examples/textures/textures_image_npatch.png | Bin 18306 -> 0 bytes examples/textures/textures_npatch_drawing.c | 109 +++++++++++ examples/textures/textures_npatch_drawing.png | Bin 0 -> 26858 bytes 49 files changed, 911 insertions(+), 1053 deletions(-) create mode 100644 examples/core/core_3d_camera_mode.c create mode 100644 examples/core/core_3d_camera_mode.png delete mode 100644 examples/core/core_3d_mode.c delete mode 100644 examples/core/core_3d_mode.png delete mode 100644 examples/core/core_color_select.c delete mode 100644 examples/core/core_color_select.png delete mode 100644 examples/core/core_gestures_detection.c delete mode 100644 examples/core/core_gestures_detection.png create mode 100644 examples/core/core_input_gestures.c create mode 100644 examples/core/core_input_gestures.png create mode 100644 examples/core/core_input_mouse_wheel.c create mode 100644 examples/core/core_input_mouse_wheel.png delete mode 100644 examples/core/core_mouse_wheel.c delete mode 100644 examples/core/core_mouse_wheel.png create mode 100644 examples/core/core_window_letterbox.c create mode 100644 examples/core/core_window_letterbox.png delete mode 100644 examples/core/core_window_scale_letterbox.c delete mode 100644 examples/core/core_window_scale_letterbox.png create mode 100644 examples/shapes/shapes_rectangle_scaling.c create mode 100644 examples/shapes/shapes_rectangle_scaling.png delete mode 100644 examples/shapes/shapes_rectangle_scaling_mouse.c delete mode 100644 examples/shapes/shapes_rectangle_scaling_mouse.png delete mode 100644 examples/text/text_bmfont_unordered.c delete mode 100644 examples/text/text_bmfont_unordered.png delete mode 100644 examples/text/text_draw_inside_rectangle.c delete mode 100644 examples/text/text_draw_inside_rectangle.png create mode 100644 examples/text/text_rectangle_bounds.c create mode 100644 examples/text/text_rectangle_bounds.png delete mode 100644 examples/textures/textures_image_npatch.c delete mode 100644 examples/textures/textures_image_npatch.png create mode 100644 examples/textures/textures_npatch_drawing.c create mode 100644 examples/textures/textures_npatch_drawing.png (limited to 'examples/models') diff --git a/examples/core/core_3d_camera_mode.c b/examples/core/core_3d_camera_mode.c new file mode 100644 index 00000000..a4962200 --- /dev/null +++ b/examples/core/core_3d_camera_mode.c @@ -0,0 +1,73 @@ +/******************************************************************************************* +* +* raylib [core] example - Initialize 3d camera mode +* +* This example has been created using raylib 1.0 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2014 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera mode"); + + // Define the camera to look into our 3d world + Camera3D camera = { 0 }; + camera.position = (Vector3){ 0.0f, 10.0f, 10.0f }; // Camera position + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) + camera.fovy = 45.0f; // Camera field-of-view Y + camera.type = CAMERA_PERSPECTIVE; // Camera mode type + + Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + // TODO: Update your variables here + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED); + DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, MAROON); + + DrawGrid(10, 1.0f); + + EndMode3D(); + + DrawText("Welcome to the third dimension!", 10, 40, 20, DARKGRAY); + + DrawFPS(10, 10); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/examples/core/core_3d_camera_mode.png b/examples/core/core_3d_camera_mode.png new file mode 100644 index 00000000..de65daeb Binary files /dev/null and b/examples/core/core_3d_camera_mode.png differ diff --git a/examples/core/core_3d_mode.c b/examples/core/core_3d_mode.c deleted file mode 100644 index 39c0752a..00000000 --- a/examples/core/core_3d_mode.c +++ /dev/null @@ -1,73 +0,0 @@ -/******************************************************************************************* -* -* raylib [core] example - Initialize 3d mode -* -* This example has been created using raylib 1.0 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2014 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d mode"); - - // Define the camera to look into our 3d world - Camera3D camera; - camera.position = (Vector3){ 0.0f, 10.0f, 10.0f }; // Camera position - camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point - camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) - camera.fovy = 45.0f; // Camera field-of-view Y - camera.type = CAMERA_PERSPECTIVE; // Camera mode type - - Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - - SetTargetFPS(60); // Set our game to run at 60 frames-per-second - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - // TODO: Update your variables here - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - BeginMode3D(camera); - - DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED); - DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, MAROON); - - DrawGrid(10, 1.0f); - - EndMode3D(); - - DrawText("Welcome to the third dimension!", 10, 40, 20, DARKGRAY); - - DrawFPS(10, 10); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/core/core_3d_mode.png b/examples/core/core_3d_mode.png deleted file mode 100644 index de65daeb..00000000 Binary files a/examples/core/core_3d_mode.png and /dev/null differ diff --git a/examples/core/core_color_select.c b/examples/core/core_color_select.c deleted file mode 100644 index 002a6931..00000000 --- a/examples/core/core_color_select.c +++ /dev/null @@ -1,94 +0,0 @@ -/******************************************************************************************* -* -* raylib [core] example - Color selection by mouse (collision detection) -* -* This example has been created using raylib 1.0 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2014 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [core] example - color selection (collision detection)"); - - Color colors[21] = { DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN, - GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW, - GREEN, SKYBLUE, PURPLE, BEIGE }; - - Rectangle colorsRecs[21]; // Rectangles array - - // Fills colorsRecs data (for every rectangle) - for (int i = 0; i < 21; i++) - { - colorsRecs[i].x = 20 + 100*(i%7) + 10*(i%7); - colorsRecs[i].y = 60 + 100*(i/7) + 10*(i/7); - colorsRecs[i].width = 100; - colorsRecs[i].height = 100; - } - - bool selected[21] = { false }; // Selected rectangles indicator - - Vector2 mousePoint; - - SetTargetFPS(60); // Set our game to run at 60 frames-per-second - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - mousePoint = GetMousePosition(); - - for (int i = 0; i < 21; i++) // Iterate along all the rectangles - { - if (CheckCollisionPointRec(mousePoint, colorsRecs[i])) - { - colors[i].a = 120; - - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) selected[i] = !selected[i]; - } - else colors[i].a = 255; - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - for (int i = 0; i < 21; i++) // Draw all rectangles - { - DrawRectangleRec(colorsRecs[i], colors[i]); - - // Draw four rectangles around selected rectangle - if (selected[i]) - { - DrawRectangle(colorsRecs[i].x, colorsRecs[i].y, 100, 10, RAYWHITE); // Square top rectangle - DrawRectangle(colorsRecs[i].x, colorsRecs[i].y, 10, 100, RAYWHITE); // Square left rectangle - DrawRectangle(colorsRecs[i].x + 90, colorsRecs[i].y, 10, 100, RAYWHITE); // Square right rectangle - DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + 90, 100, 10, RAYWHITE); // Square bottom rectangle - } - } - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/core/core_color_select.png b/examples/core/core_color_select.png deleted file mode 100644 index 93ab83ae..00000000 Binary files a/examples/core/core_color_select.png and /dev/null differ diff --git a/examples/core/core_custom_logging.c b/examples/core/core_custom_logging.c index 4c4caf5d..cf1a601f 100644 --- a/examples/core/core_custom_logging.c +++ b/examples/core/core_custom_logging.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.1 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2018 Ramon Santamaria (@raysan5) and Pablo Marcos Oltra (@pamarcos) +* Example contributed by Pablo Marcos Oltra (@pamarcos) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Pablo Marcos Oltra (@pamarcos) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/core/core_gestures_detection.c b/examples/core/core_gestures_detection.c deleted file mode 100644 index 63a1e6bd..00000000 --- a/examples/core/core_gestures_detection.c +++ /dev/null @@ -1,115 +0,0 @@ -/******************************************************************************************* -* -* raylib [core] example - Gestures Detection -* -* This example has been created using raylib 1.4 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2016 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" -#include - -#define MAX_GESTURE_STRINGS 20 - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [core] example - gestures detection"); - - Vector2 touchPosition = { 0, 0 }; - Rectangle touchArea = { 220, 10, screenWidth - 230, screenHeight - 20 }; - - int gesturesCount = 0; - char gestureStrings[MAX_GESTURE_STRINGS][32]; - - int currentGesture = GESTURE_NONE; - int lastGesture = GESTURE_NONE; - - //SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - lastGesture = currentGesture; - currentGesture = GetGestureDetected(); - touchPosition = GetTouchPosition(0); - - if (CheckCollisionPointRec(touchPosition, touchArea) && (currentGesture != GESTURE_NONE)) - { - if (currentGesture != lastGesture) - { - // Store gesture string - switch (currentGesture) - { - case GESTURE_TAP: strcpy(gestureStrings[gesturesCount], "GESTURE TAP"); break; - case GESTURE_DOUBLETAP: strcpy(gestureStrings[gesturesCount], "GESTURE DOUBLETAP"); break; - case GESTURE_HOLD: strcpy(gestureStrings[gesturesCount], "GESTURE HOLD"); break; - case GESTURE_DRAG: strcpy(gestureStrings[gesturesCount], "GESTURE DRAG"); break; - case GESTURE_SWIPE_RIGHT: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE RIGHT"); break; - case GESTURE_SWIPE_LEFT: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE LEFT"); break; - case GESTURE_SWIPE_UP: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE UP"); break; - case GESTURE_SWIPE_DOWN: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE DOWN"); break; - case GESTURE_PINCH_IN: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH IN"); break; - case GESTURE_PINCH_OUT: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH OUT"); break; - default: break; - } - - gesturesCount++; - - // Reset gestures strings - if (gesturesCount >= MAX_GESTURE_STRINGS) - { - for (int i = 0; i < MAX_GESTURE_STRINGS; i++) strcpy(gestureStrings[i], "\0"); - - gesturesCount = 0; - } - } - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - DrawRectangleRec(touchArea, GRAY); - DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, RAYWHITE); - - DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(GRAY, 0.5f)); - - for (int i = 0; i < gesturesCount; i++) - { - if (i%2 == 0) DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.5f)); - else DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.3f)); - - if (i < gesturesCount - 1) DrawText(gestureStrings[i], 35, 36 + 20*i, 10, DARKGRAY); - else DrawText(gestureStrings[i], 35, 36 + 20*i, 10, MAROON); - } - - DrawRectangleLines(10, 29, 200, screenHeight - 50, GRAY); - DrawText("DETECTED GESTURES", 50, 15, 10, GRAY); - - if (currentGesture != GESTURE_NONE) DrawCircleV(touchPosition, 30, MAROON); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- -} \ No newline at end of file diff --git a/examples/core/core_gestures_detection.png b/examples/core/core_gestures_detection.png deleted file mode 100644 index d2bbb5d7..00000000 Binary files a/examples/core/core_gestures_detection.png and /dev/null differ diff --git a/examples/core/core_input_gestures.c b/examples/core/core_input_gestures.c new file mode 100644 index 00000000..ce2ed86c --- /dev/null +++ b/examples/core/core_input_gestures.c @@ -0,0 +1,115 @@ +/******************************************************************************************* +* +* raylib [core] example - Input Gestures Detection +* +* This example has been created using raylib 1.4 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2016 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" +#include + +#define MAX_GESTURE_STRINGS 20 + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures"); + + Vector2 touchPosition = { 0, 0 }; + Rectangle touchArea = { 220, 10, screenWidth - 230, screenHeight - 20 }; + + int gesturesCount = 0; + char gestureStrings[MAX_GESTURE_STRINGS][32]; + + int currentGesture = GESTURE_NONE; + int lastGesture = GESTURE_NONE; + + //SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + lastGesture = currentGesture; + currentGesture = GetGestureDetected(); + touchPosition = GetTouchPosition(0); + + if (CheckCollisionPointRec(touchPosition, touchArea) && (currentGesture != GESTURE_NONE)) + { + if (currentGesture != lastGesture) + { + // Store gesture string + switch (currentGesture) + { + case GESTURE_TAP: strcpy(gestureStrings[gesturesCount], "GESTURE TAP"); break; + case GESTURE_DOUBLETAP: strcpy(gestureStrings[gesturesCount], "GESTURE DOUBLETAP"); break; + case GESTURE_HOLD: strcpy(gestureStrings[gesturesCount], "GESTURE HOLD"); break; + case GESTURE_DRAG: strcpy(gestureStrings[gesturesCount], "GESTURE DRAG"); break; + case GESTURE_SWIPE_RIGHT: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE RIGHT"); break; + case GESTURE_SWIPE_LEFT: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE LEFT"); break; + case GESTURE_SWIPE_UP: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE UP"); break; + case GESTURE_SWIPE_DOWN: strcpy(gestureStrings[gesturesCount], "GESTURE SWIPE DOWN"); break; + case GESTURE_PINCH_IN: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH IN"); break; + case GESTURE_PINCH_OUT: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH OUT"); break; + default: break; + } + + gesturesCount++; + + // Reset gestures strings + if (gesturesCount >= MAX_GESTURE_STRINGS) + { + for (int i = 0; i < MAX_GESTURE_STRINGS; i++) strcpy(gestureStrings[i], "\0"); + + gesturesCount = 0; + } + } + } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + DrawRectangleRec(touchArea, GRAY); + DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, RAYWHITE); + + DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(GRAY, 0.5f)); + + for (int i = 0; i < gesturesCount; i++) + { + if (i%2 == 0) DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.5f)); + else DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.3f)); + + if (i < gesturesCount - 1) DrawText(gestureStrings[i], 35, 36 + 20*i, 10, DARKGRAY); + else DrawText(gestureStrings[i], 35, 36 + 20*i, 10, MAROON); + } + + DrawRectangleLines(10, 29, 200, screenHeight - 50, GRAY); + DrawText("DETECTED GESTURES", 50, 15, 10, GRAY); + + if (currentGesture != GESTURE_NONE) DrawCircleV(touchPosition, 30, MAROON); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- +} \ No newline at end of file diff --git a/examples/core/core_input_gestures.png b/examples/core/core_input_gestures.png new file mode 100644 index 00000000..d2bbb5d7 Binary files /dev/null and b/examples/core/core_input_gestures.png differ diff --git a/examples/core/core_input_mouse_wheel.c b/examples/core/core_input_mouse_wheel.c new file mode 100644 index 00000000..48cf7042 --- /dev/null +++ b/examples/core/core_input_mouse_wheel.c @@ -0,0 +1,58 @@ +/******************************************************************************************* +* +* raylib [core] examples - Mouse wheel input +* +* This test has been created using raylib 1.1 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2014 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel"); + + int boxPositionY = screenHeight/2 - 40; + int scrollSpeed = 4; // Scrolling speed in pixels + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + boxPositionY -= (GetMouseWheelMove()*scrollSpeed); + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + DrawRectangle(screenWidth/2 - 40, boxPositionY, 80, 80, MAROON); + + DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, GRAY); + DrawText(FormatText("Box position Y: %03i", boxPositionY), 10, 40, 20, LIGHTGRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/examples/core/core_input_mouse_wheel.png b/examples/core/core_input_mouse_wheel.png new file mode 100644 index 00000000..26a1f243 Binary files /dev/null and b/examples/core/core_input_mouse_wheel.png differ diff --git a/examples/core/core_input_multitouch.c b/examples/core/core_input_multitouch.c index ef8fa7ae..5baab271 100644 --- a/examples/core/core_input_multitouch.c +++ b/examples/core/core_input_multitouch.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.1 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014-2019 Berni and Ramon Santamaria (@raysan5) +* Example contributed by Berni (@Berni8k) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Berni (@Berni8k) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/core/core_loading_thread.c b/examples/core/core_loading_thread.c index 4ffc9d0b..1dacd69f 100644 --- a/examples/core/core_loading_thread.c +++ b/examples/core/core_loading_thread.c @@ -15,10 +15,13 @@ #include "raylib.h" #include "pthread.h" // POSIX style threads management -#include -#include // Required for clock() function +#include // C11 atomic data types +#include // Required for: clock() + +// Using C11 atomics for synchronization +// NOTE: A plain bool (or any plain data type for that matter) can't be used for inter-thread synchronization static atomic_bool dataLoaded = ATOMIC_VAR_INIT(false); // Data Loaded completion indicator static void *LoadDataThread(void *arg); // Loading data thread function declaration @@ -48,33 +51,37 @@ int main() //---------------------------------------------------------------------------------- switch (state) { - case STATE_WAITING: - if (IsKeyPressed(KEY_ENTER)) + case STATE_WAITING: { - int error = pthread_create(&threadId, NULL, &LoadDataThread, NULL); - if (error != 0) TraceLog(LOG_ERROR, "Error creating loading thread"); - else TraceLog(LOG_INFO, "Loading thread initialized successfully"); - - state = STATE_LOADING; - } - break; - case STATE_LOADING: - framesCounter++; - if (atomic_load(&dataLoaded)) + if (IsKeyPressed(KEY_ENTER)) + { + int error = pthread_create(&threadId, NULL, &LoadDataThread, NULL); + if (error != 0) TraceLog(LOG_ERROR, "Error creating loading thread"); + else TraceLog(LOG_INFO, "Loading thread initialized successfully"); + + state = STATE_LOADING; + } + } break; + case STATE_LOADING: { - framesCounter = 0; - state = STATE_FINISHED; - } - break; - case STATE_FINISHED: - if (IsKeyPressed(KEY_ENTER)) + framesCounter++; + if (atomic_load(&dataLoaded)) + { + framesCounter = 0; + state = STATE_FINISHED; + } + } break; + case STATE_FINISHED: { - // Reset everything to launch again - atomic_store(&dataLoaded, false); - dataProgress = 0; - state = STATE_WAITING; - } - break; + if (IsKeyPressed(KEY_ENTER)) + { + // Reset everything to launch again + atomic_store(&dataLoaded, false); + dataProgress = 0; + state = STATE_WAITING; + } + } break; + default: break; } //---------------------------------------------------------------------------------- @@ -84,19 +91,22 @@ int main() ClearBackground(RAYWHITE); - switch(state) { - case STATE_WAITING: - DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY); - break; - case STATE_LOADING: - DrawRectangle(150, 200, dataProgress, 60, SKYBLUE); - if ((framesCounter/15)%2) - DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE); - break; - case STATE_FINISHED: - DrawRectangle(150, 200, 500, 60, LIME); - DrawText("DATA LOADED!", 250, 210, 40, GREEN); - break; + switch (state) + { + case STATE_WAITING: DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY); break; + case STATE_LOADING: + { + DrawRectangle(150, 200, dataProgress, 60, SKYBLUE); + if ((framesCounter/15)%2) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE); + + } break; + case STATE_FINISHED: + { + DrawRectangle(150, 200, 500, 60, LIME); + DrawText("DATA LOADED!", 250, 210, 40, GREEN); + + } break; + default: break; } DrawRectangleLines(150, 200, 500, 60, DARKGRAY); diff --git a/examples/core/core_mouse_wheel.c b/examples/core/core_mouse_wheel.c deleted file mode 100644 index 6a5252ee..00000000 --- a/examples/core/core_mouse_wheel.c +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************************* -* -* raylib [core] examples - Mouse wheel -* -* This test has been created using raylib 1.1 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2014 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse wheel"); - - int boxPositionY = screenHeight/2 - 40; - int scrollSpeed = 4; // Scrolling speed in pixels - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - boxPositionY -= (GetMouseWheelMove()*scrollSpeed); - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - DrawRectangle(screenWidth/2 - 40, boxPositionY, 80, 80, MAROON); - - DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, GRAY); - DrawText(FormatText("Box position Y: %03i", boxPositionY), 10, 40, 20, LIGHTGRAY); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/core/core_mouse_wheel.png b/examples/core/core_mouse_wheel.png deleted file mode 100644 index 26a1f243..00000000 Binary files a/examples/core/core_mouse_wheel.png and /dev/null differ diff --git a/examples/core/core_window_letterbox.c b/examples/core/core_window_letterbox.c new file mode 100644 index 00000000..8c0843d2 --- /dev/null +++ b/examples/core/core_window_letterbox.c @@ -0,0 +1,90 @@ +/******************************************************************************************* +* +* raylib [core] example - window scale letterbox +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +#define max(a, b) ((a)>(b)? (a) : (b)) +#define min(a, b) ((a)<(b)? (a) : (b)) + +int main() +{ + const int windowWidth = 800; + const int windowHeight = 450; + + // Enable config flags for resizable window and vertical synchro + SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT); + InitWindow(windowWidth, windowHeight, "raylib [core] example - window scale letterbox"); + SetWindowMinSize(320, 240); + + int gameScreenWidth = 640; + int gameScreenHeight = 480; + + // Render texture initialization + RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight); + SetTextureFilter(target.texture, FILTER_BILINEAR); // Texture scale filter to use + + Color colors[10] = { 0 }; + for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while( !WindowShouldClose() ) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + // Compute required framebuffer scaling + float scale = min((float)GetScreenWidth()/gameScreenWidth, (float)GetScreenHeight()/gameScreenHeight); + + if (IsKeyPressed(KEY_SPACE)) + { + // Recalculate random colors for the bars + for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; + } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + ClearBackground(BLACK); + + // Draw everything in the render texture + BeginTextureMode(target); + + ClearBackground(RAYWHITE); // Clear render texture background color + + for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]); + + DrawText("You can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE); + + EndTextureMode(); + + // Draw RenderTexture2D to window, properly scaled + DrawTexturePro(target.texture, (Rectangle){ 0.0f, 0.0f, (float)target.texture.width, (float)-target.texture.height }, + (Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5, + (float)gameScreenWidth*scale, (float)gameScreenHeight*scale }, (Vector2){ 0, 0 }, 0.0f, WHITE); + + EndDrawing(); + //-------------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadRenderTexture(target); // Unload render texture + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/core/core_window_letterbox.png b/examples/core/core_window_letterbox.png new file mode 100644 index 00000000..5acf2d7c Binary files /dev/null and b/examples/core/core_window_letterbox.png differ diff --git a/examples/core/core_window_scale_letterbox.c b/examples/core/core_window_scale_letterbox.c deleted file mode 100644 index ea4a375a..00000000 --- a/examples/core/core_window_scale_letterbox.c +++ /dev/null @@ -1,88 +0,0 @@ -/******************************************************************************************* -* -* raylib [core] example - window scale letterbox -* -* This example has been created using raylib 2.5 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2019 Anata and Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -#define max(a, b) ((a)>(b)? (a) : (b)) -#define min(a, b) ((a)<(b)? (a) : (b)) - -int main() -{ - const int windowWidth = 800; - const int windowHeight = 450; - - // Enable config flags for resizable window and vertical synchro - SetConfigFlags(FLAG_WINDOW_RESIZABLE | FLAG_VSYNC_HINT); - InitWindow(windowWidth, windowHeight, "raylib [core] example - window scale letterbox"); - SetWindowMinSize(320, 240); - - int gameScreenWidth = 640; - int gameScreenHeight = 480; - - // Render texture initialization - RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight); - SetTextureFilter(target.texture, FILTER_BILINEAR); // Texture scale filter to use - - Color colors[10] = { 0 }; - for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while( !WindowShouldClose() ) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - // Compute required framebuffer scaling - float scale = min((float)GetScreenWidth()/gameScreenWidth, (float)GetScreenHeight()/gameScreenHeight); - - if (IsKeyPressed(KEY_SPACE)) - { - // Recalculate random colors for the bars - for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - ClearBackground(BLACK); - - // Draw everything in the render texture - BeginTextureMode(target); - - ClearBackground(RAYWHITE); // Clear render texture background color - - for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]); - - DrawText("You can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE); - - EndTextureMode(); - - // Draw RenderTexture2D to window, properly scaled - DrawTexturePro(target.texture, (Rectangle){ 0.0f, 0.0f, (float)target.texture.width, (float)-target.texture.height }, - (Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5, - (float)gameScreenWidth*scale, (float)gameScreenHeight*scale }, (Vector2){ 0, 0 }, 0.0f, WHITE); - - EndDrawing(); - //-------------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - UnloadRenderTexture(target); // Unload render texture - - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} diff --git a/examples/core/core_window_scale_letterbox.png b/examples/core/core_window_scale_letterbox.png deleted file mode 100644 index 5acf2d7c..00000000 Binary files a/examples/core/core_window_scale_letterbox.png and /dev/null differ diff --git a/examples/models/models_orthographic_projection.c b/examples/models/models_orthographic_projection.c index f9b54b6d..3ad32b60 100644 --- a/examples/models/models_orthographic_projection.c +++ b/examples/models/models_orthographic_projection.c @@ -4,10 +4,12 @@ * * This program is heavily based on the geometric objects example * -* This example has been created using raylib 1.9.7 (www.raylib.com) +* This example has been created using raylib 2.0 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2018 Max Danielsson & Ramon Santamaria (@raysan5) +* Example contributed by Max Danielsson (@autious) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Max Danielsson (@autious) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/models/models_yaw_pitch_roll.c b/examples/models/models_yaw_pitch_roll.c index 7eaaf0be..658be084 100644 --- a/examples/models/models_yaw_pitch_roll.c +++ b/examples/models/models_yaw_pitch_roll.c @@ -5,9 +5,9 @@ * This example has been created using raylib 1.8 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Example based on Berni work on Raspberry Pi. +* Example contributed by Berni (@Berni8k) and reviewed by Ramon Santamaria (@raysan5) * -* Copyright (c) 2017 Ramon Santamaria (@raysan5) +* Copyright (c) 2017 Berni (@Berni8k) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shaders/shaders_julia_set.c b/examples/shaders/shaders_julia_set.c index 381cd33e..c4dac6d2 100644 --- a/examples/shaders/shaders_julia_set.c +++ b/examples/shaders/shaders_julia_set.c @@ -1,6 +1,6 @@ /******************************************************************************************* * -* raylib [shaders] example - Render julia sets using a shader. +* raylib [shaders] example - julia sets * * NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support, * OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version. @@ -10,73 +10,68 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Author: eggmund (https://github.com/eggmund) +* Example contributed by eggmund (@eggmund) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 eggmund (@eggmund) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" -#include // For memcpy -// Speed when using auto -const float AUTO_SPEED = 0.0005; +#include "raymath.h" // A few good julia sets const float POINTS_OF_INTEREST[6][2] = { - {-0.348827, 0.607167}, - {-0.786268, 0.169728}, - {-0.8, 0.156}, - {0.285, 0.0}, - {-0.835, -0.2321}, - {-0.70176, -0.3842}, + { -0.348827, 0.607167 }, + { -0.786268, 0.169728 }, + { -0.8, 0.156 }, + { 0.285, 0.0 }, + { -0.835, -0.2321 }, + { -0.70176, -0.3842 }, }; int main() { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 1280; - int screenHeight = 720; - - InitWindow(screenWidth, screenHeight, "raylib [shaders] example - julia set renderer"); - - // If julia set is rendered for this frame. - bool rendered = false; - - bool showControls = true; - - // Multiplier of speed to change c value. Set to 3 to start off with. - int incrementSpeed = 3; - - // Offset and zoom to draw the julia set at. (centered on screen and 1.6 times smaller) - float offset[2] = { -(float)screenWidth/2, -(float)screenHeight/2 }; - float zoom = 1.6; + const int screenWidth = 800; + const int screenHeight = 450; - // c constant to use in z^2 + c - float c[2]; - // Copy a point of interest into the c variable. 4 bytes per float (32 bits). - memcpy(c, &POINTS_OF_INTEREST[0], 8); + InitWindow(screenWidth, screenHeight, "raylib [shaders] example - julia sets"); // Load julia set shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, "resources/shaders/glsl330/julia_shader.fs"); - // Get variable (uniform) location on the shader to connect with the program + // c constant to use in z^2 + c + float c[2] = { POINTS_OF_INTEREST[0][0], POINTS_OF_INTEREST[0][1] }; + + // Offset and zoom to draw the julia set at. (centered on screen and 1.6 times smaller) + float offset[2] = { -(float)screenWidth/2, -(float)screenHeight/2 }; + float zoom = 1.6f; + + // Get variable (uniform) locations on the shader to connect with the program // NOTE: If uniform variable could not be found in the shader, function returns -1 - // The location of c will be stored since we will need to change this whenever c changes int cLoc = GetShaderLocation(shader, "c"); + int zoomLoc = GetShaderLocation(shader, "zoom"); + int offsetLoc = GetShaderLocation(shader, "offset"); // Tell the shader what the screen dimensions, zoom, offset and c are float screenDims[2] = { (float)screenWidth, (float)screenHeight }; SetShaderValue(shader, GetShaderLocation(shader, "screenDims"), screenDims, UNIFORM_VEC2); - SetShaderValue(shader, GetShaderLocation(shader, "zoom"), &zoom, UNIFORM_FLOAT); - SetShaderValue(shader, GetShaderLocation(shader, "offset"), offset, UNIFORM_VEC2); - - SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); + SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); + SetShaderValue(shader, zoomLoc, &zoom, UNIFORM_FLOAT); + SetShaderValue(shader, offsetLoc, offset, UNIFORM_VEC2); + // Create a RenderTexture2D to be used for render to texture RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); + int incrementSpeed = 3; // Multiplier of speed to change c value + bool showControls = true; // Show controls + bool pause = false; // Pause animation + SetTargetFPS(60); // Set the window to run at 60 frames-per-second //-------------------------------------------------------------------------------------- @@ -86,115 +81,86 @@ int main() // Update //---------------------------------------------------------------------------------- - // Get input - //---------------------------------------------------------------------------------- - - // Press 1 - 6 to reset c to a point of interest. - if (IsKeyPressed(KEY_ONE) || IsKeyPressed(KEY_TWO) || IsKeyPressed(KEY_THREE) || IsKeyPressed(KEY_FOUR) || IsKeyPressed(KEY_FIVE) || IsKeyPressed(KEY_SIX)) + // Press [1 - 6] to reset c to a point of interest + if (IsKeyPressed(KEY_ONE) || + IsKeyPressed(KEY_TWO) || + IsKeyPressed(KEY_THREE) || + IsKeyPressed(KEY_FOUR) || + IsKeyPressed(KEY_FIVE) || + IsKeyPressed(KEY_SIX)) { - if (IsKeyPressed(KEY_ONE)) - { - memcpy(c, &POINTS_OF_INTEREST[0], 8); - } - else if (IsKeyPressed(KEY_TWO)) - { - memcpy(c, &POINTS_OF_INTEREST[1], 8); - } - else if (IsKeyPressed(KEY_THREE)) - { - memcpy(c, &POINTS_OF_INTEREST[2], 8); - } - else if (IsKeyPressed(KEY_FOUR)) - { - memcpy(c, &POINTS_OF_INTEREST[3], 8); - } - else if (IsKeyPressed(KEY_FIVE)) - { - memcpy(c, &POINTS_OF_INTEREST[4], 8); - } - else if (IsKeyPressed(KEY_SIX)) - { - memcpy(c, &POINTS_OF_INTEREST[5], 8); - } - SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); - rendered = false; // c value has changed, so render the set again. - } + if (IsKeyPressed(KEY_ONE)) c[0] = POINTS_OF_INTEREST[0][0], c[1] = POINTS_OF_INTEREST[0][1]; + else if (IsKeyPressed(KEY_TWO)) c[0] = POINTS_OF_INTEREST[1][0], c[1] = POINTS_OF_INTEREST[1][1]; + else if (IsKeyPressed(KEY_THREE)) c[0] = POINTS_OF_INTEREST[2][0], c[1] = POINTS_OF_INTEREST[2][1]; + else if (IsKeyPressed(KEY_FOUR)) c[0] = POINTS_OF_INTEREST[3][0], c[1] = POINTS_OF_INTEREST[3][1]; + else if (IsKeyPressed(KEY_FIVE)) c[0] = POINTS_OF_INTEREST[4][0], c[1] = POINTS_OF_INTEREST[4][1]; + else if (IsKeyPressed(KEY_SIX)) c[0] = POINTS_OF_INTEREST[5][0], c[1] = POINTS_OF_INTEREST[5][1]; - // Press "r" to stop changing c - if (IsKeyPressed(KEY_R)) - { - incrementSpeed = 0; + SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); } - // Toggle whether or not to show controls - if (IsKeyPressed(KEY_H)) + if (IsKeyPressed(KEY_P)) pause = !pause; // Pause animation (c change) + if (IsKeyPressed(KEY_F1)) showControls = !showControls; // Toggle whether or not to show controls + + if (!pause) { - showControls = !showControls; - } + if (IsKeyDown(KEY_RIGHT)) incrementSpeed++; + else if (IsKeyDown(KEY_LEFT)) incrementSpeed--; - // Scroll to change c increment speed. - int mouseMv = GetMouseWheelMove(); // Get the amount the mouse has moved this frame - if (mouseMv != 0) - { - if (IsKeyDown(KEY_LEFT_SHIFT)) - { - incrementSpeed += mouseMv * 10; - } - else + // Use mouse wheel to change zoom + zoom -= (float)GetMouseWheelMove()/10.f; + SetShaderValue(shader, zoomLoc, &zoom, UNIFORM_FLOAT); + + // Use mouse button to change offset + if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) { - incrementSpeed += mouseMv; + // TODO: Logic is not correct, the idea is getting zoom focus to pointed area + Vector2 mousePos = GetMousePosition(); + + offset[0] = mousePos.x -(float)screenWidth; + offset[1] = mousePos.y -(float)screenHeight; + + SetShaderValue(shader, offsetLoc, offset, UNIFORM_VEC2); } - rendered = false; - } - if (incrementSpeed != 0) - { - float amount = GetFrameTime() * incrementSpeed * AUTO_SPEED; + // Increment c value with time + float amount = GetFrameTime()*incrementSpeed*0.0005f; c[0] += amount; c[1] += amount; - // Update the c value in the shader. SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); - rendered = false; } - //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - ClearBackground(BLACK); // Clear the screen of the previous frame. + ClearBackground(BLACK); // Clear the screen of the previous frame. - // If the c value has changed, redraw the julia set using the shader, onto the render texture. - if (!rendered) - { - BeginTextureMode(target); // Enable drawing to texture - - ClearBackground(BLACK); // Clear the last frame drawn on the texture. - - // Draw a rectangle in shader mode. This acts as a canvas for the shader to draw on. - BeginShaderMode(shader); - DrawRectangle(0, 0, screenWidth, screenHeight, BLACK); - EndShaderMode(); - - EndTextureMode(); - - rendered = true; // The set is now rendered, so do not compute it again until it next changes. - } - - // Draw the saved texture (rendered julia set). - DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, target.texture.height }, (Vector2){ 0, 0 }, WHITE); + // Using a render texture to draw Julia set + BeginTextureMode(target); // Enable drawing to texture + ClearBackground(BLACK); // Clear the render texture + + // Draw a rectangle in shader mode + // NOTE: This acts as a canvas for the shader to draw on + BeginShaderMode(shader); + DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), BLACK); + EndShaderMode(); + EndTextureMode(); + + // Draw the saved texture (rendered julia set) + DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, Vector2Zero(), WHITE); - // Print information. - DrawText( FormatText("cx: %f\ncy: %f\nspeed: %d", c[0], c[1], incrementSpeed), 10, 10, 20, RAYWHITE ); + // Draw information + //DrawText( FormatText("cx: %f\ncy: %f\nspeed: %d", c[0], c[1], incrementSpeed), 10, 10, 10, RAYWHITE); if (showControls) { - DrawText("Press keys 1 - 6 to change point of interest.", 10, screenHeight - 88, 20, RAYWHITE); - DrawText("Use the scroll wheel to auto increment the c value. Hold shift while scrolling to increase speed by 10.", 10, screenHeight - 66, 20, RAYWHITE); - DrawText("Press 'r' to reset speed.", 10, screenHeight - 44, 20, RAYWHITE); - DrawText("Press 'h' to hide these controls.", 10, screenHeight - 22, 20, RAYWHITE); + DrawText("Press keys [1 - 6] to change point of interest", 10, GetScreenHeight() - 60, 10, RAYWHITE); + DrawText("Press KEY_LEFT | KEY_RIGHT to change speed", 10, GetScreenHeight() - 45, 10, RAYWHITE); + DrawText("Press KEY_P to pause movement animation", 10, GetScreenHeight() - 30, 10, RAYWHITE); + DrawText("Press KEY_F1 to toggle these controls", 10, GetScreenHeight() - 15, 10, RAYWHITE); } EndDrawing(); diff --git a/examples/shaders/shaders_palette_switch.c b/examples/shaders/shaders_palette_switch.c index a2fa0b27..fa0bafaf 100644 --- a/examples/shaders/shaders_palette_switch.c +++ b/examples/shaders/shaders_palette_switch.c @@ -12,7 +12,9 @@ * This example has been created using raylib 2.3 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Ramon Santamaria (@raysan5) +* Example contributed by Marco Lizza (@MarcoLizza) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Marco Lizza (@MarcoLizza) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shaders/shaders_texture_drawing.c b/examples/shaders/shaders_texture_drawing.c index f5758273..3a540098 100644 --- a/examples/shaders/shaders_texture_drawing.c +++ b/examples/shaders/shaders_texture_drawing.c @@ -7,6 +7,8 @@ * This example has been created using raylib 2.0 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * +* Example contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5) +* * Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shaders/shaders_texture_waves.c b/examples/shaders/shaders_texture_waves.c index 03c62deb..bc677c78 100644 --- a/examples/shaders/shaders_texture_waves.c +++ b/examples/shaders/shaders_texture_waves.c @@ -12,7 +12,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Anata (creator) and Ramon Santamaria (review) (@raysan5) +* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shapes/shapes_colors_palette.c b/examples/shapes/shapes_colors_palette.c index dcab862e..d6ac30a9 100644 --- a/examples/shapes/shapes_colors_palette.c +++ b/examples/shapes/shapes_colors_palette.c @@ -1,26 +1,53 @@ /******************************************************************************************* * -* raylib [shapes] example - Draw raylib custom color palette +* raylib [shapes] example - Colors palette * -* This example has been created using raylib 1.0 (www.raylib.com) +* This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2014 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" +#define MAX_COLORS_COUNT 21 // Number of colors available + int main() { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette"); + + Color colors[MAX_COLORS_COUNT] = { + DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN, + GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW, + GREEN, SKYBLUE, PURPLE, BEIGE }; + + const char *colorNames[MAX_COLORS_COUNT] = { + "DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE", + "DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN", + "LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" }; + + Rectangle colorsRecs[MAX_COLORS_COUNT] = { 0 }; // Rectangles array + + // Fills colorsRecs data (for every rectangle) + for (int i = 0; i < MAX_COLORS_COUNT; i++) + { + colorsRecs[i].x = 20 + 100*(i%7) + 10*(i%7); + colorsRecs[i].y = 80 + 100*(i/7) + 10*(i/7); + colorsRecs[i].width = 100; + colorsRecs[i].height = 100; + } + + int colorState[MAX_COLORS_COUNT] = { 0 }; // Color state: 0-DEFAULT, 1-MOUSE_HOVER - InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib color palette"); - - SetTargetFPS(60); + Vector2 mousePoint; + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -28,7 +55,13 @@ int main() { // Update //---------------------------------------------------------------------------------- - // TODO: Update your variables here + mousePoint = GetMousePosition(); + + for (int i = 0; i < MAX_COLORS_COUNT; i++) + { + if (CheckCollisionPointRec(mousePoint, colorsRecs[i])) colorState[i] = 1; + else colorState[i] = 0; + } //---------------------------------------------------------------------------------- // Draw @@ -36,53 +69,22 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); + + DrawText("raylib colors palette", 28, 42, 20, BLACK); + DrawText("press SPACE to see all colors", GetScreenWidth() - 180, GetScreenHeight() - 40, 10, GRAY); - DrawText("raylib color palette", 28, 42, 20, BLACK); - - DrawRectangle(26, 80, 100, 100, DARKGRAY); - DrawRectangle(26, 188, 100, 100, GRAY); - DrawRectangle(26, 296, 100, 100, LIGHTGRAY); - DrawRectangle(134, 80, 100, 100, MAROON); - DrawRectangle(134, 188, 100, 100, RED); - DrawRectangle(134, 296, 100, 100, PINK); - DrawRectangle(242, 80, 100, 100, ORANGE); - DrawRectangle(242, 188, 100, 100, GOLD); - DrawRectangle(242, 296, 100, 100, YELLOW); - DrawRectangle(350, 80, 100, 100, DARKGREEN); - DrawRectangle(350, 188, 100, 100, LIME); - DrawRectangle(350, 296, 100, 100, GREEN); - DrawRectangle(458, 80, 100, 100, DARKBLUE); - DrawRectangle(458, 188, 100, 100, BLUE); - DrawRectangle(458, 296, 100, 100, SKYBLUE); - DrawRectangle(566, 80, 100, 100, DARKPURPLE); - DrawRectangle(566, 188, 100, 100, VIOLET); - DrawRectangle(566, 296, 100, 100, PURPLE); - DrawRectangle(674, 80, 100, 100, DARKBROWN); - DrawRectangle(674, 188, 100, 100, BROWN); - DrawRectangle(674, 296, 100, 100, BEIGE); - - - DrawText("DARKGRAY", 65, 166, 10, BLACK); - DrawText("GRAY", 93, 274, 10, BLACK); - DrawText("LIGHTGRAY", 61, 382, 10, BLACK); - DrawText("MAROON", 186, 166, 10, BLACK); - DrawText("RED", 208, 274, 10, BLACK); - DrawText("PINK", 204, 382, 10, BLACK); - DrawText("ORANGE", 295, 166, 10, BLACK); - DrawText("GOLD", 310, 274, 10, BLACK); - DrawText("YELLOW", 300, 382, 10, BLACK); - DrawText("DARKGREEN", 382, 166, 10, BLACK); - DrawText("LIME", 420, 274, 10, BLACK); - DrawText("GREEN", 410, 382, 10, BLACK); - DrawText("DARKBLUE", 498, 166, 10, BLACK); - DrawText("BLUE", 526, 274, 10, BLACK); - DrawText("SKYBLUE", 505, 382, 10, BLACK); - DrawText("DARKPURPLE", 592, 166, 10, BLACK); - DrawText("VIOLET", 621, 274, 10, BLACK); - DrawText("PURPLE", 620, 382, 10, BLACK); - DrawText("DARKBROWN", 705, 166, 10, BLACK); - DrawText("BROWN", 733, 274, 10, BLACK); - DrawText("BEIGE", 737, 382, 10, BLACK); + for (int i = 0; i < MAX_COLORS_COUNT; i++) // Draw all rectangles + { + DrawRectangleRec(colorsRecs[i], Fade(colors[i], colorState[i]? 0.6f : 1.0f)); + + if (IsKeyDown(KEY_SPACE) || colorState[i]) + { + DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + colorsRecs[i].height - 26, colorsRecs[i].width, 20, BLACK); + DrawRectangleLinesEx(colorsRecs[i], 6, Fade(BLACK, 0.3f)); + DrawText(colorNames[i], colorsRecs[i].x + colorsRecs[i].width - MeasureText(colorNames[i], 10) - 12, + colorsRecs[i].y + colorsRecs[i].height - 20, 10, colors[i]); + } + } EndDrawing(); //---------------------------------------------------------------------------------- @@ -90,7 +92,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; diff --git a/examples/shapes/shapes_colors_palette.png b/examples/shapes/shapes_colors_palette.png index 4073b670..b68e497e 100644 Binary files a/examples/shapes/shapes_colors_palette.png and b/examples/shapes/shapes_colors_palette.png differ diff --git a/examples/shapes/shapes_draw_circle_sector.c b/examples/shapes/shapes_draw_circle_sector.c index a88a59d5..597b85a7 100644 --- a/examples/shapes/shapes_draw_circle_sector.c +++ b/examples/shapes/shapes_draw_circle_sector.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Vlad Adrian (@Demizdor) and Ramon Santamaria (@raysan5) +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shapes/shapes_draw_rectangle_rounded.c b/examples/shapes/shapes_draw_rectangle_rounded.c index 35fe63fb..e36e2731 100644 --- a/examples/shapes/shapes_draw_rectangle_rounded.c +++ b/examples/shapes/shapes_draw_rectangle_rounded.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Vlad Adrian (@Demizdor) and Ramon Santamaria (@raysan5) +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shapes/shapes_draw_ring.c b/examples/shapes/shapes_draw_ring.c index d56b9c2e..44a3ec5f 100644 --- a/examples/shapes/shapes_draw_ring.c +++ b/examples/shapes/shapes_draw_ring.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Vlad Adrian (@Demizdor) and Ramon Santamaria (@raysan5) +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/shapes/shapes_rectangle_scaling.c b/examples/shapes/shapes_rectangle_scaling.c new file mode 100644 index 00000000..036a1dd4 --- /dev/null +++ b/examples/shapes/shapes_rectangle_scaling.c @@ -0,0 +1,94 @@ +/******************************************************************************************* +* +* raylib [shapes] example - rectangle scaling by mouse +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +#define MOUSE_SCALE_MARK_SIZE 12 + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse"); + + Rectangle rec = { 100, 100, 200, 80 }; + + Vector2 mousePosition = { 0 }; + + bool mouseScaleReady = false; + bool mouseScaleMode = false; + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + mousePosition = GetMousePosition(); + + if (CheckCollisionPointRec(mousePosition, rec) && + CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE })) + { + mouseScaleReady = true; + if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true; + } + else mouseScaleReady = false; + + if (mouseScaleMode) + { + mouseScaleReady = true; + + rec.width = (mousePosition.x - rec.x); + rec.height = (mousePosition.y - rec.y); + + if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE; + if (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE; + + if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false; + } + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, GRAY); + + DrawRectangleRec(rec, Fade(GREEN, 0.5f)); + + if (mouseScaleReady) + { + DrawRectangleLinesEx(rec, 1, RED); + DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height }, + (Vector2){ rec.x + rec.width, rec.y + rec.height }, + (Vector2){ rec.x + rec.width, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE }, RED); + } + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/examples/shapes/shapes_rectangle_scaling.png b/examples/shapes/shapes_rectangle_scaling.png new file mode 100644 index 00000000..83d67de9 Binary files /dev/null and b/examples/shapes/shapes_rectangle_scaling.png differ diff --git a/examples/shapes/shapes_rectangle_scaling_mouse.c b/examples/shapes/shapes_rectangle_scaling_mouse.c deleted file mode 100644 index d8c521ca..00000000 --- a/examples/shapes/shapes_rectangle_scaling_mouse.c +++ /dev/null @@ -1,92 +0,0 @@ -/******************************************************************************************* -* -* raylib [shapes] example - rectangle scaling by mouse -* -* This example has been created using raylib 2.5 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2019 Demioz and Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -#define MOUSE_SCALE_MARK_SIZE 12 - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse"); - - Rectangle rec = { 100, 100, 200, 80 }; - - Vector2 mousePosition = { 0 }; - - bool mouseScaleReady = false; - bool mouseScaleMode = false; - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - mousePosition = GetMousePosition(); - - if (CheckCollisionPointRec(mousePosition, rec) && - CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE })) - { - mouseScaleReady = true; - if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true; - } - else mouseScaleReady = false; - - if (mouseScaleMode) - { - mouseScaleReady = true; - - rec.width = (mousePosition.x - rec.x); - rec.height = (mousePosition.y - rec.y); - - if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE; - if (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE; - - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false; - } - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, GRAY); - - DrawRectangleRec(rec, Fade(GREEN, 0.5f)); - - if (mouseScaleReady) - { - DrawRectangleLinesEx(rec, 1, RED); - DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height }, - (Vector2){ rec.x + rec.width, rec.y + rec.height }, - (Vector2){ rec.x + rec.width, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE }, RED); - } - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/shapes/shapes_rectangle_scaling_mouse.png b/examples/shapes/shapes_rectangle_scaling_mouse.png deleted file mode 100644 index 83d67de9..00000000 Binary files a/examples/shapes/shapes_rectangle_scaling_mouse.png and /dev/null differ diff --git a/examples/text/text_bmfont_ttf.c b/examples/text/text_bmfont_ttf.c index f71f5ddb..ca26b2cf 100644 --- a/examples/text/text_bmfont_ttf.c +++ b/examples/text/text_bmfont_ttf.c @@ -20,17 +20,20 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [text] example - bmfont and ttf sprite fonts loading"); - const char msgBm[64] = "THIS IS AN AngelCode SPRITE FONT"; - const char msgTtf[64] = "THIS SPRITE FONT has been GENERATED from a TTF"; + // Define characters to draw + // NOTE: raylib supports UTF-8 encoding, following list is actually codified as UTF8 internally + const char msg[256] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ"; // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) - Font fontBm = LoadFont("resources/bmfont.fnt"); // BMFont (AngelCode) - Font fontTtf = LoadFont("resources/pixantiqua.ttf"); // TTF font - - Vector2 fontPosition; - - fontPosition.x = screenWidth/2 - MeasureTextEx(fontBm, msgBm, fontBm.baseSize, 0).x/2; - fontPosition.y = screenHeight/2 - fontBm.baseSize/2 - 80; + + // BMFont (AngelCode) : Font data and image atlas have been generated using external program + Font fontBm = LoadFont("resources/pixantiqua.fnt"); + + // TTF font : Font data and atlas are generated directly from TTF + // NOTE: We define a font base size of 32 pixels tall and up-to 250 characters + Font fontTtf = LoadFontEx("resources/pixantiqua.ttf", 32, 0, 250); + + bool useTtf = false; SetTargetFPS(60); //-------------------------------------------------------------------------------------- @@ -40,7 +43,8 @@ int main() { // Update //---------------------------------------------------------------------------------- - // TODO: Update variables here... + if (IsKeyDown(KEY_SPACE)) useTtf = true; + else useTtf = false; //---------------------------------------------------------------------------------- // Draw @@ -48,9 +52,19 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - - DrawTextEx(fontBm, msgBm, fontPosition, fontBm.baseSize, 0, MAROON); - DrawTextEx(fontTtf, msgTtf, (Vector2){ 75.0f, 240.0f }, fontTtf.baseSize*0.8f, 2, LIME); + + DrawText("Press SPACE to use TTF generated font", 20, 20, 20, LIGHTGRAY); + + if (!useTtf) + { + DrawTextEx(fontBm, msg, (Vector2){ 20.0f, 100.0f }, fontBm.baseSize, 2, MAROON); + DrawText("Using BMFont (Angelcode) imported", 20, GetScreenHeight() - 30, 20, GRAY); + } + else + { + DrawTextEx(fontTtf, msg, (Vector2){ 20.0f, 100.0f }, fontTtf.baseSize, 2, LIME); + DrawText("Using TTF font generated", 20, GetScreenHeight() - 30, 20, GRAY); + } EndDrawing(); //---------------------------------------------------------------------------------- diff --git a/examples/text/text_bmfont_ttf.png b/examples/text/text_bmfont_ttf.png index 8305d36b..a99027ad 100644 Binary files a/examples/text/text_bmfont_ttf.png and b/examples/text/text_bmfont_ttf.png differ diff --git a/examples/text/text_bmfont_unordered.c b/examples/text/text_bmfont_unordered.c deleted file mode 100644 index a5147619..00000000 --- a/examples/text/text_bmfont_unordered.c +++ /dev/null @@ -1,65 +0,0 @@ -/******************************************************************************************* -* -* raylib [text] example - BMFont unordered chars loading and drawing -* -* This example has been created using raylib 1.4 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2016 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [text] example - bmfont unordered loading and drawing"); - - // NOTE: Using chars outside the [32..127] limits! - // NOTE: If a character is not found in the font, it just renders a space - const char msg[256] = "ASCII extended characters:\n¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆ\nÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæ\nçèéêëìíîïðñòóôõö÷øùúûüýþÿ"; - - // NOTE: Loaded font has an unordered list of characters (chars in the range 32..255) - Font font = LoadFont("resources/pixantiqua.fnt"); // BMFont (AngelCode) - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - // TODO: Update variables here... - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - DrawText("Font name: PixAntiqua", 40, 50, 20, GRAY); - DrawText(FormatText("Font base size: %i", font.baseSize), 40, 80, 20, GRAY); - DrawText(FormatText("Font chars number: %i", font.charsCount), 40, 110, 20, GRAY); - - DrawTextEx(font, msg, (Vector2){ 40, 180 }, font.baseSize, 0, MAROON); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - UnloadFont(font); // AngelCode Font unloading - - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/text/text_bmfont_unordered.png b/examples/text/text_bmfont_unordered.png deleted file mode 100644 index c6767567..00000000 Binary files a/examples/text/text_bmfont_unordered.png and /dev/null differ diff --git a/examples/text/text_draw_inside_rectangle.c b/examples/text/text_draw_inside_rectangle.c deleted file mode 100644 index e60fa5e5..00000000 --- a/examples/text/text_draw_inside_rectangle.c +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************************* -* -* raylib [text] example - Draw text inside a rectangle -* -* This example has been created using raylib 2.3 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2018 Vlad Adrian (@demizdor) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); - - char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ - a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ - tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; - - bool resizing = false; - bool wordWrap = true; - - Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250}; - Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 }; - - // Minimum width and heigh for the container rectangle - const int minWidth = 60; - const int minHeight = 60; - const int maxWidth = screenWidth - 50; - const int maxHeight = screenHeight - 160; - - Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates - - Color borderColor = MAROON; // Container border color - - Font font = GetFontDefault(); // Get default system font - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap; - - Vector2 mouse = GetMousePosition(); - - // Check if the mouse is inside the container and toggle border color - if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f); - else if (!resizing) borderColor = MAROON; - - // Container resizing logic - if (resizing) - { - if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; - - int width = container.width + (mouse.x - lastMouse.x); - container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth; - - int height = container.height + (mouse.y - lastMouse.y); - container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight; - } - else - { - // Check if we're resizing - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; - } - - // Move resizer rectangle properly - resizer.x = container.x + container.width - 17; - resizer.y = container.y + container.height - 17; - - lastMouse = mouse; // Update mouse - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - DrawRectangleLinesEx(container, 3, borderColor); // Draw container border - - // Draw text in container (add some padding) - DrawTextRec(font, text, - (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, - 20.0f, 2.0f, wordWrap, GRAY); - - DrawRectangleRec(resizer, borderColor); // Draw the resize box - - // Draw info - DrawText("Word Wrap: ", 313, screenHeight-115, 20, BLACK); - if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED); - else DrawText("OFF", 447, screenHeight - 115, 20, BLACK); - DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 91, 20, GRAY); - - DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); - DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); - DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} \ No newline at end of file diff --git a/examples/text/text_draw_inside_rectangle.png b/examples/text/text_draw_inside_rectangle.png deleted file mode 100644 index f46b1096..00000000 Binary files a/examples/text/text_draw_inside_rectangle.png and /dev/null differ diff --git a/examples/text/text_rectangle_bounds.c b/examples/text/text_rectangle_bounds.c new file mode 100644 index 00000000..d4cd240a --- /dev/null +++ b/examples/text/text_rectangle_bounds.c @@ -0,0 +1,120 @@ +/******************************************************************************************* +* +* raylib [text] example - Draw text inside a rectangle +* +* This example has been created using raylib 2.3 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); + + char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ + a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ + tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; + + bool resizing = false; + bool wordWrap = true; + + Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250}; + Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 }; + + // Minimum width and heigh for the container rectangle + const int minWidth = 60; + const int minHeight = 60; + const int maxWidth = screenWidth - 50; + const int maxHeight = screenHeight - 160; + + Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates + Color borderColor = MAROON; // Container border color + Font font = GetFontDefault(); // Get default system font + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap; + + Vector2 mouse = GetMousePosition(); + + // Check if the mouse is inside the container and toggle border color + if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f); + else if (!resizing) borderColor = MAROON; + + // Container resizing logic + if (resizing) + { + if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; + + int width = container.width + (mouse.x - lastMouse.x); + container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth; + + int height = container.height + (mouse.y - lastMouse.y); + container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight; + } + else + { + // Check if we're resizing + if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; + } + + // Move resizer rectangle properly + resizer.x = container.x + container.width - 17; + resizer.y = container.y + container.height - 17; + + lastMouse = mouse; // Update mouse + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + DrawRectangleLinesEx(container, 3, borderColor); // Draw container border + + // Draw text in container (add some padding) + DrawTextRec(font, text, + (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, + 20.0f, 2.0f, wordWrap, GRAY); + + DrawRectangleRec(resizer, borderColor); // Draw the resize box + + // Draw info + DrawText("Word Wrap: ", 313, screenHeight-115, 20, BLACK); + if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED); + else DrawText("OFF", 447, screenHeight - 115, 20, BLACK); + DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 91, 20, GRAY); + + DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); + DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); + DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} \ No newline at end of file diff --git a/examples/text/text_rectangle_bounds.png b/examples/text/text_rectangle_bounds.png new file mode 100644 index 00000000..f46b1096 Binary files /dev/null and b/examples/text/text_rectangle_bounds.png differ diff --git a/examples/text/text_unicode.c b/examples/text/text_unicode.c index b6c6db30..6b456a75 100644 --- a/examples/text/text_unicode.c +++ b/examples/text/text_unicode.c @@ -5,6 +5,8 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * +* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) +* * Copyright (c) 2019 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ diff --git a/examples/textures/textures_image_npatch.c b/examples/textures/textures_image_npatch.c deleted file mode 100644 index 357b8a98..00000000 --- a/examples/textures/textures_image_npatch.c +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************************* -* -* raylib [textures] example - N-patch drawing -* -* NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM) -* -* This example has been created using raylib 2.0 (www.raylib.com) -* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -* -* Copyright (c) 2016 Ramon Santamaria (@raysan5) -* -********************************************************************************************/ - -#include "raylib.h" - -int main() -{ - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - - InitWindow(screenWidth, screenHeight, "raylib [textures] example - N-patch drawing"); - - // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) - Texture2D nPatchTexture = LoadTexture("resources/ninepatch_button.png"); - Vector2 mousePosition; - Vector2 origin = {0.0f, 0.0f}; - - // The location and size of the n-patches. - Rectangle dstRec1 = {480.0f, 160.0f, 32.0f, 32.0f}; - Rectangle dstRec2 = {160.0f, 160.0f, 32.0f, 32.0f}; - Rectangle dstRecH = {160.0f, 93.0f, 32.0f, 32.0f}; // this rec's height is ignored - Rectangle dstRecV = {92.0f, 160.0f, 32.0f, 32.0f}; // this rec's width is ignored - - // A 9-patch (NPT_9PATCH) changes its sizes in both axis - NPatchInfo ninePatchInfo1 = {(Rectangle){0.0f, 0.0f, 64.0f, 64.0f}, 12, 40, 12, 12, NPT_9PATCH }; - NPatchInfo ninePatchInfo2 = {(Rectangle){0.0f, 128.0f, 64.0f, 64.0f}, 16, 16, 16, 16, NPT_9PATCH }; - // A horizontal 3-patch (NPT_3PATCH_HORIZONTAL) changes its sizes along the x axis only - NPatchInfo h3PatchInfo = {(Rectangle){0.0f, 64.0f, 64.0f, 64.0f}, 8, 8, 8, 8, NPT_3PATCH_HORIZONTAL }; - // A vertical 3-patch (NPT_3PATCH_VERTICAL) changes its sizes along the y axis only - NPatchInfo v3PatchInfo = {(Rectangle){0.0f, 192.0f, 64.0f, 64.0f}, 6, 6, 6, 6, NPT_3PATCH_VERTICAL }; - - SetTargetFPS(60); - //--------------------------------------------------------------------------------------- - - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - mousePosition = GetMousePosition(); - // resize the n-patches based on mouse position. - dstRec1.width = mousePosition.x - dstRec1.x; - dstRec1.height = mousePosition.y - dstRec1.y; - dstRec2.width = mousePosition.x - dstRec2.x; - dstRec2.height = mousePosition.y - dstRec2.y; - dstRecH.width = mousePosition.x - dstRecH.x; - dstRecV.height = mousePosition.y - dstRecV.y; - - // set a minimum width and/or height - if (dstRec1.width < 1.0f) dstRec1.width = 1.0f; - if (dstRec1.width > 300.0f) dstRec1.width = 300.0f; - if (dstRec1.height < 1.0f) dstRec1.height = 1.0f; - if (dstRec2.width < 1.0f) dstRec2.width = 1.0f; - if (dstRec2.width > 300.0f) dstRec2.width = 300.0f; - if (dstRec2.height < 1.0f) dstRec2.height = 1.0f; - if (dstRecH.width < 1.0f) dstRecH.width = 1.0f; - if (dstRecV.height < 1.0f) dstRecV.height = 1.0f; - //---------------------------------------------------------------------------------- - - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); - - ClearBackground(RAYWHITE); - - // Draw the n-patches - DrawTextureNPatch(nPatchTexture, ninePatchInfo2, dstRec2, origin, 0.0f, WHITE); - DrawTextureNPatch(nPatchTexture, ninePatchInfo1, dstRec1, origin, 0.0f, WHITE); - DrawTextureNPatch(nPatchTexture, h3PatchInfo, dstRecH, origin, 0.0f, WHITE); - DrawTextureNPatch(nPatchTexture, v3PatchInfo, dstRecV, origin, 0.0f, WHITE); - - // Draw the source texture - DrawRectangleLines( 5, 88, 74, 266, BLUE); - DrawTexture(nPatchTexture, 10, 93, WHITE); - DrawText("TEXTURE", 15, 360, 10, DARKGRAY); - - DrawRectangle( 10, 10, 250, 73, Fade(SKYBLUE, 0.5)); - DrawRectangleLines( 10, 10, 250, 73, BLUE); - - DrawText("9-Patch and 3-Patch example", 20, 20, 10, BLACK); - DrawText(" Move the mouse to stretch or", 40, 40, 10, DARKGRAY); - DrawText(" shrink the n-patches.", 40, 60, 10, DARKGRAY); - - EndDrawing(); - //---------------------------------------------------------------------------------- - } - - // De-Initialization - //-------------------------------------------------------------------------------------- - UnloadTexture(nPatchTexture); // Texture unloading - - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - - return 0; -} diff --git a/examples/textures/textures_image_npatch.png b/examples/textures/textures_image_npatch.png deleted file mode 100644 index 5258811b..00000000 Binary files a/examples/textures/textures_image_npatch.png and /dev/null differ diff --git a/examples/textures/textures_npatch_drawing.c b/examples/textures/textures_npatch_drawing.c new file mode 100644 index 00000000..0514efe7 --- /dev/null +++ b/examples/textures/textures_npatch_drawing.c @@ -0,0 +1,109 @@ +/******************************************************************************************* +* +* raylib [textures] example - N-patch drawing +* +* NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM) +* +* This example has been created using raylib 2.0 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Example contributed by Jorge A. Gomes (@overdev) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2018 Jorge A. Gomes (@overdev) and Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + int screenWidth = 800; + int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [textures] example - N-patch drawing"); + + // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) + Texture2D nPatchTexture = LoadTexture("resources/ninepatch_button.png"); + + Vector2 mousePosition = { 0 }; + Vector2 origin = { 0.0f, 0.0f }; + + // Position and size of the n-patches + Rectangle dstRec1 = { 480.0f, 160.0f, 32.0f, 32.0f }; + Rectangle dstRec2 = { 160.0f, 160.0f, 32.0f, 32.0f }; + Rectangle dstRecH = { 160.0f, 93.0f, 32.0f, 32.0f }; + Rectangle dstRecV = { 92.0f, 160.0f, 32.0f, 32.0f }; + + // A 9-patch (NPT_9PATCH) changes its sizes in both axis + NPatchInfo ninePatchInfo1 = { (Rectangle){ 0.0f, 0.0f, 64.0f, 64.0f }, 12, 40, 12, 12, NPT_9PATCH }; + NPatchInfo ninePatchInfo2 = { (Rectangle){ 0.0f, 128.0f, 64.0f, 64.0f }, 16, 16, 16, 16, NPT_9PATCH }; + + // A horizontal 3-patch (NPT_3PATCH_HORIZONTAL) changes its sizes along the x axis only + NPatchInfo h3PatchInfo = { (Rectangle){ 0.0f, 64.0f, 64.0f, 64.0f }, 8, 8, 8, 8, NPT_3PATCH_HORIZONTAL }; + + // A vertical 3-patch (NPT_3PATCH_VERTICAL) changes its sizes along the y axis only + NPatchInfo v3PatchInfo = { (Rectangle){ 0.0f, 192.0f, 64.0f, 64.0f }, 6, 6, 6, 6, NPT_3PATCH_VERTICAL }; + + SetTargetFPS(60); + //--------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + mousePosition = GetMousePosition(); + + // Resize the n-patches based on mouse position + dstRec1.width = mousePosition.x - dstRec1.x; + dstRec1.height = mousePosition.y - dstRec1.y; + dstRec2.width = mousePosition.x - dstRec2.x; + dstRec2.height = mousePosition.y - dstRec2.y; + dstRecH.width = mousePosition.x - dstRecH.x; + dstRecV.height = mousePosition.y - dstRecV.y; + + // Set a minimum width and/or height + if (dstRec1.width < 1.0f) dstRec1.width = 1.0f; + if (dstRec1.width > 300.0f) dstRec1.width = 300.0f; + if (dstRec1.height < 1.0f) dstRec1.height = 1.0f; + if (dstRec2.width < 1.0f) dstRec2.width = 1.0f; + if (dstRec2.width > 300.0f) dstRec2.width = 300.0f; + if (dstRec2.height < 1.0f) dstRec2.height = 1.0f; + if (dstRecH.width < 1.0f) dstRecH.width = 1.0f; + if (dstRecV.height < 1.0f) dstRecV.height = 1.0f; + //---------------------------------------------------------------------------------- + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + // Draw the n-patches + DrawTextureNPatch(nPatchTexture, ninePatchInfo2, dstRec2, origin, 0.0f, WHITE); + DrawTextureNPatch(nPatchTexture, ninePatchInfo1, dstRec1, origin, 0.0f, WHITE); + DrawTextureNPatch(nPatchTexture, h3PatchInfo, dstRecH, origin, 0.0f, WHITE); + DrawTextureNPatch(nPatchTexture, v3PatchInfo, dstRecV, origin, 0.0f, WHITE); + + // Draw the source texture + DrawRectangleLines(5, 88, 74, 266, BLUE); + DrawTexture(nPatchTexture, 10, 93, WHITE); + DrawText("TEXTURE", 15, 360, 10, DARKGRAY); + + DrawText("Move the mouse to stretch or shrink the n-patches", 10, 20, 20, DARKGRAY); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + UnloadTexture(nPatchTexture); // Texture unloading + + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/textures/textures_npatch_drawing.png b/examples/textures/textures_npatch_drawing.png new file mode 100644 index 00000000..21df9caa Binary files /dev/null and b/examples/textures/textures_npatch_drawing.png differ -- cgit v1.2.3 From 245cf2400e3f215b998d4e1f2ae1f9afefa0eb08 Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 17 May 2019 20:03:04 +0200 Subject: Review shader examples --- examples/models/models_material_pbr.c | 44 +-- examples/models/models_skybox.c | 10 +- examples/models/resources/shaders/brdf.fs | 133 --------- examples/models/resources/shaders/brdf.vs | 25 -- examples/models/resources/shaders/cubemap.fs | 38 --- examples/models/resources/shaders/cubemap.vs | 28 -- examples/models/resources/shaders/glsl100/brdf.fs | 133 +++++++++ examples/models/resources/shaders/glsl100/brdf.vs | 25 ++ .../models/resources/shaders/glsl100/cubemap.fs | 38 +++ .../models/resources/shaders/glsl100/cubemap.vs | 28 ++ .../models/resources/shaders/glsl100/irradiance.fs | 58 ++++ examples/models/resources/shaders/glsl100/pbr.fs | 298 +++++++++++++++++++++ examples/models/resources/shaders/glsl100/pbr.vs | 49 ++++ .../models/resources/shaders/glsl100/prefilter.fs | 120 +++++++++ .../models/resources/shaders/glsl100/skybox.fs | 31 +++ .../models/resources/shaders/glsl100/skybox.vs | 32 +++ examples/models/resources/shaders/glsl330/brdf.fs | 133 +++++++++ examples/models/resources/shaders/glsl330/brdf.vs | 25 ++ .../models/resources/shaders/glsl330/cubemap.fs | 38 +++ .../models/resources/shaders/glsl330/cubemap.vs | 28 ++ .../models/resources/shaders/glsl330/irradiance.fs | 58 ++++ examples/models/resources/shaders/glsl330/pbr.fs | 298 +++++++++++++++++++++ examples/models/resources/shaders/glsl330/pbr.vs | 49 ++++ .../models/resources/shaders/glsl330/prefilter.fs | 120 +++++++++ .../models/resources/shaders/glsl330/skybox.fs | 31 +++ .../models/resources/shaders/glsl330/skybox.vs | 32 +++ examples/models/resources/shaders/irradiance.fs | 58 ---- examples/models/resources/shaders/pbr.fs | 298 --------------------- examples/models/resources/shaders/pbr.vs | 49 ---- examples/models/resources/shaders/prefilter.fs | 120 --------- examples/models/resources/shaders/skybox.fs | 31 --- examples/models/resources/shaders/skybox.vs | 32 --- 32 files changed, 1656 insertions(+), 834 deletions(-) delete mode 100644 examples/models/resources/shaders/brdf.fs delete mode 100644 examples/models/resources/shaders/brdf.vs delete mode 100644 examples/models/resources/shaders/cubemap.fs delete mode 100644 examples/models/resources/shaders/cubemap.vs create mode 100644 examples/models/resources/shaders/glsl100/brdf.fs create mode 100644 examples/models/resources/shaders/glsl100/brdf.vs create mode 100644 examples/models/resources/shaders/glsl100/cubemap.fs create mode 100644 examples/models/resources/shaders/glsl100/cubemap.vs create mode 100644 examples/models/resources/shaders/glsl100/irradiance.fs create mode 100644 examples/models/resources/shaders/glsl100/pbr.fs create mode 100644 examples/models/resources/shaders/glsl100/pbr.vs create mode 100644 examples/models/resources/shaders/glsl100/prefilter.fs create mode 100644 examples/models/resources/shaders/glsl100/skybox.fs create mode 100644 examples/models/resources/shaders/glsl100/skybox.vs create mode 100644 examples/models/resources/shaders/glsl330/brdf.fs create mode 100644 examples/models/resources/shaders/glsl330/brdf.vs create mode 100644 examples/models/resources/shaders/glsl330/cubemap.fs create mode 100644 examples/models/resources/shaders/glsl330/cubemap.vs create mode 100644 examples/models/resources/shaders/glsl330/irradiance.fs create mode 100644 examples/models/resources/shaders/glsl330/pbr.fs create mode 100644 examples/models/resources/shaders/glsl330/pbr.vs create mode 100644 examples/models/resources/shaders/glsl330/prefilter.fs create mode 100644 examples/models/resources/shaders/glsl330/skybox.fs create mode 100644 examples/models/resources/shaders/glsl330/skybox.vs delete mode 100644 examples/models/resources/shaders/irradiance.fs delete mode 100644 examples/models/resources/shaders/pbr.fs delete mode 100644 examples/models/resources/shaders/pbr.vs delete mode 100644 examples/models/resources/shaders/prefilter.fs delete mode 100644 examples/models/resources/shaders/skybox.fs delete mode 100644 examples/models/resources/shaders/skybox.vs (limited to 'examples/models') diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index 5c308cfc..b8d320c7 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -17,6 +17,12 @@ #define RLIGHTS_IMPLEMENTATION #include "rlights.h" +#if defined(PLATFORM_DESKTOP) + #define GLSL_VERSION 330 +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + #define GLSL_VERSION 100 +#endif + #define CUBEMAP_SIZE 512 // Cubemap texture size #define IRRADIANCE_SIZE 32 // Irradiance texture size #define PREFILTERED_SIZE 256 // Prefiltered HDR environment texture size @@ -114,10 +120,8 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) { Material mat = { 0 }; // NOTE: All maps textures are set to { 0 } - #define PATH_PBR_VS "resources/shaders/pbr.vs" // Path to physically based rendering vertex shader - #define PATH_PBR_FS "resources/shaders/pbr.fs" // Path to physically based rendering fragment shader - - mat.shader = LoadShader(PATH_PBR_VS, PATH_PBR_FS); + mat.shader = LoadShader(FormatText("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION)); // Get required locations points for PBR material // NOTE: Those location names must be available and used in the shader code @@ -144,23 +148,21 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) mat.maps[MAP_ROUGHNESS].texture = LoadTexture("resources/pbr/trooper_roughness.png"); mat.maps[MAP_OCCLUSION].texture = LoadTexture("resources/pbr/trooper_ao.png"); - // Set environment maps - #define PATH_CUBEMAP_VS "resources/shaders/cubemap.vs" // Path to equirectangular to cubemap vertex shader - #define PATH_CUBEMAP_FS "resources/shaders/cubemap.fs" // Path to equirectangular to cubemap fragment shader - #define PATH_SKYBOX_VS "resources/shaders/skybox.vs" // Path to skybox vertex shader - #define PATH_IRRADIANCE_FS "resources/shaders/irradiance.fs" // Path to irradiance (GI) calculation fragment shader - #define PATH_PREFILTER_FS "resources/shaders/prefilter.fs" // Path to reflection prefilter calculation fragment shader - #define PATH_BRDF_VS "resources/shaders/brdf.vs" // Path to bidirectional reflectance distribution function vertex shader - #define PATH_BRDF_FS "resources/shaders/brdf.fs" // Path to bidirectional reflectance distribution function fragment shader - - Shader shdrCubemap = LoadShader(PATH_CUBEMAP_VS, PATH_CUBEMAP_FS); - printf("Loaded shader: cubemap\n"); - Shader shdrIrradiance = LoadShader(PATH_SKYBOX_VS, PATH_IRRADIANCE_FS); - printf("Loaded shader: irradiance\n"); - Shader shdrPrefilter = LoadShader(PATH_SKYBOX_VS, PATH_PREFILTER_FS); - printf("Loaded shader: prefilter\n"); - Shader shdrBRDF = LoadShader(PATH_BRDF_VS, PATH_BRDF_FS); - printf("Loaded shader: brdf\n"); + // Load equirectangular to cubemap shader + Shader shdrCubemap = LoadShader(FormatText("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION)); + + // Load irradiance (GI) calculation shader + Shader shdrIrradiance = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/irradiance.fs", GLSL_VERSION)); + + // Load reflection prefilter calculation shader + Shader shdrPrefilter = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/prefilter.fs", GLSL_VERSION)); + + // Load bidirectional reflectance distribution function shader + Shader shdrBRDF = LoadShader(FormatText("resources/shaders/glsl%i/brdf.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/brdf.fs", GLSL_VERSION)); // Setup required shader locations SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); diff --git a/examples/models/models_skybox.c b/examples/models/models_skybox.c index 759c79c6..2d4d5710 100644 --- a/examples/models/models_skybox.c +++ b/examples/models/models_skybox.c @@ -11,6 +11,12 @@ #include "raylib.h" +#if defined(PLATFORM_DESKTOP) + #define GLSL_VERSION 330 +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + #define GLSL_VERSION 100 +#endif + int main() { // Initialization @@ -29,7 +35,9 @@ int main() // Load skybox shader and set required locations // NOTE: Some locations are automatically set at shader loading - skybox.materials[0].shader = LoadShader("resources/shaders/skybox.vs", "resources/shaders/skybox.fs"); + skybox.materials[0].shader = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), + FormatText("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION)); + SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MAP_CUBEMAP }, UNIFORM_INT); // Load cubemap shader and setup required shader locations diff --git a/examples/models/resources/shaders/brdf.fs b/examples/models/resources/shaders/brdf.fs deleted file mode 100644 index d04bc661..00000000 --- a/examples/models/resources/shaders/brdf.fs +++ /dev/null @@ -1,133 +0,0 @@ -/******************************************************************************************* -* -* BRDF LUT Generation - Bidirectional reflectance distribution function fragment shader -* -* REF: https://github.com/HectorMF/BRDFGenerator -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - - -// Input vertex attributes (from vertex shader) -in vec2 fragTexCoord; - -// Constant values -const float PI = 3.14159265359; -const uint MAX_SAMPLES = 1024u; - -// Output fragment color -out vec4 finalColor; - -vec2 Hammersley(uint i, uint N); -float RadicalInverseVdC(uint bits); -float GeometrySchlickGGX(float NdotV, float roughness); -float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); -vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); -vec2 IntegrateBRDF(float NdotV, float roughness); - -float RadicalInverseVdC(uint bits) -{ - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 -} - -// Compute Hammersley coordinates -vec2 Hammersley(uint i, uint N) -{ - return vec2(float(i)/float(N), RadicalInverseVdC(i)); -} - -// Integrate number of importance samples for (roughness and NoV) -vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) -{ - float a = roughness*roughness; - float phi = 2.0 * PI * Xi.x; - float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta*cosTheta); - - // Transform from spherical coordinates to cartesian coordinates (halfway vector) - vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); - - // Transform from tangent space H vector to world space sample vector - vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; - - return normalize(sampleVec); -} - -float GeometrySchlickGGX(float NdotV, float roughness) -{ - // For IBL k is calculated different - float k = (roughness*roughness)/2.0; - - float nom = NdotV; - float denom = NdotV*(1.0 - k) + k; - - return nom/denom; -} - -// Compute the geometry term for the BRDF given roughness squared, NoV, NoL -float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) -{ - float NdotV = max(dot(N, V), 0.0); - float NdotL = max(dot(N, L), 0.0); - float ggx2 = GeometrySchlickGGX(NdotV, roughness); - float ggx1 = GeometrySchlickGGX(NdotL, roughness); - - return ggx1*ggx2; -} - -vec2 IntegrateBRDF(float NdotV, float roughness) -{ - float A = 0.0; - float B = 0.0; - vec3 V = vec3(sqrt(1.0 - NdotV*NdotV), 0.0, NdotV); - vec3 N = vec3(0.0, 0.0, 1.0); - - for (uint i = 0u; i < MAX_SAMPLES; i++) - { - // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) - - vec2 Xi = Hammersley(i, MAX_SAMPLES); // Compute a Hammersely coordinate - vec3 H = ImportanceSampleGGX(Xi, N, roughness); // Integrate number of importance samples for (roughness and NoV) - vec3 L = normalize(2.0*dot(V, H)*H - V); // Compute reflection vector L - - float NdotL = max(L.z, 0.0); // Compute normal dot light - float NdotH = max(H.z, 0.0); // Compute normal dot half - float VdotH = max(dot(V, H), 0.0); // Compute view dot half - - if (NdotL > 0.0) - { - float G = GeometrySmith(N, V, L, roughness); // Compute the geometry term for the BRDF given roughness squared, NoV, NoL - float GVis = (G*VdotH)/(NdotH*NdotV); // Compute the visibility term given G, VoH, NoH, NoV, NoL - float Fc = pow(1.0 - VdotH, 5.0); // Compute the fresnel term given VoH - - A += (1.0 - Fc)*GVis; // Sum the result given fresnel, geometry, visibility - B += Fc*GVis; - } - } - - // Calculate brdf average sample - A /= float(MAX_SAMPLES); - B /= float(MAX_SAMPLES); - - return vec2(A, B); -} - -void main() -{ - // Calculate brdf based on texture coordinates - vec2 brdf = IntegrateBRDF(fragTexCoord.x, fragTexCoord.y); - - // Calculate final fragment color - finalColor = vec4(brdf.r, brdf.g, 0.0, 1.0); -} diff --git a/examples/models/resources/shaders/brdf.vs b/examples/models/resources/shaders/brdf.vs deleted file mode 100644 index 06384673..00000000 --- a/examples/models/resources/shaders/brdf.vs +++ /dev/null @@ -1,25 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Bidirectional reflectance distribution function vertex shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes -in vec3 vertexPosition; -in vec2 vertexTexCoord; - -// Output vertex attributes (to fragment shader) -out vec2 fragTexCoord; - -void main() -{ - // Calculate fragment position based on model transformations - fragTexCoord = vertexTexCoord; - - // Calculate final vertex position - gl_Position = vec4(vertexPosition, 1.0); -} \ No newline at end of file diff --git a/examples/models/resources/shaders/cubemap.fs b/examples/models/resources/shaders/cubemap.fs deleted file mode 100644 index e8e28536..00000000 --- a/examples/models/resources/shaders/cubemap.fs +++ /dev/null @@ -1,38 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Equirectangular to cubemap fragment shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes (from vertex shader) -in vec3 fragPosition; - -// Input uniform values -uniform sampler2D equirectangularMap; - -// Output fragment color -out vec4 finalColor; - -vec2 SampleSphericalMap(vec3 v) -{ - vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); - uv *= vec2(0.1591, 0.3183); - uv += 0.5; - return uv; -} - -void main() -{ - // Normalize local position - vec2 uv = SampleSphericalMap(normalize(fragPosition)); - - // Fetch color from texture map - vec3 color = texture(equirectangularMap, uv).rgb; - - // Calculate final fragment color - finalColor = vec4(color, 1.0); -} diff --git a/examples/models/resources/shaders/cubemap.vs b/examples/models/resources/shaders/cubemap.vs deleted file mode 100644 index 5721eaa2..00000000 --- a/examples/models/resources/shaders/cubemap.vs +++ /dev/null @@ -1,28 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Equirectangular to cubemap vertex shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes -in vec3 vertexPosition; - -// Input uniform values -uniform mat4 projection; -uniform mat4 view; - -// Output vertex attributes (to fragment shader) -out vec3 fragPosition; - -void main() -{ - // Calculate fragment position based on model transformations - fragPosition = vertexPosition; - - // Calculate final vertex position - gl_Position = projection*view*vec4(vertexPosition, 1.0); -} diff --git a/examples/models/resources/shaders/glsl100/brdf.fs b/examples/models/resources/shaders/glsl100/brdf.fs new file mode 100644 index 00000000..d04bc661 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/brdf.fs @@ -0,0 +1,133 @@ +/******************************************************************************************* +* +* BRDF LUT Generation - Bidirectional reflectance distribution function fragment shader +* +* REF: https://github.com/HectorMF/BRDFGenerator +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + + +// Input vertex attributes (from vertex shader) +in vec2 fragTexCoord; + +// Constant values +const float PI = 3.14159265359; +const uint MAX_SAMPLES = 1024u; + +// Output fragment color +out vec4 finalColor; + +vec2 Hammersley(uint i, uint N); +float RadicalInverseVdC(uint bits); +float GeometrySchlickGGX(float NdotV, float roughness); +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); +vec2 IntegrateBRDF(float NdotV, float roughness); + +float RadicalInverseVdC(uint bits) +{ + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +// Compute Hammersley coordinates +vec2 Hammersley(uint i, uint N) +{ + return vec2(float(i)/float(N), RadicalInverseVdC(i)); +} + +// Integrate number of importance samples for (roughness and NoV) +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) +{ + float a = roughness*roughness; + float phi = 2.0 * PI * Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + + return normalize(sampleVec); +} + +float GeometrySchlickGGX(float NdotV, float roughness) +{ + // For IBL k is calculated different + float k = (roughness*roughness)/2.0; + + float nom = NdotV; + float denom = NdotV*(1.0 - k) + k; + + return nom/denom; +} + +// Compute the geometry term for the BRDF given roughness squared, NoV, NoL +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) +{ + float NdotV = max(dot(N, V), 0.0); + float NdotL = max(dot(N, L), 0.0); + float ggx2 = GeometrySchlickGGX(NdotV, roughness); + float ggx1 = GeometrySchlickGGX(NdotL, roughness); + + return ggx1*ggx2; +} + +vec2 IntegrateBRDF(float NdotV, float roughness) +{ + float A = 0.0; + float B = 0.0; + vec3 V = vec3(sqrt(1.0 - NdotV*NdotV), 0.0, NdotV); + vec3 N = vec3(0.0, 0.0, 1.0); + + for (uint i = 0u; i < MAX_SAMPLES; i++) + { + // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) + + vec2 Xi = Hammersley(i, MAX_SAMPLES); // Compute a Hammersely coordinate + vec3 H = ImportanceSampleGGX(Xi, N, roughness); // Integrate number of importance samples for (roughness and NoV) + vec3 L = normalize(2.0*dot(V, H)*H - V); // Compute reflection vector L + + float NdotL = max(L.z, 0.0); // Compute normal dot light + float NdotH = max(H.z, 0.0); // Compute normal dot half + float VdotH = max(dot(V, H), 0.0); // Compute view dot half + + if (NdotL > 0.0) + { + float G = GeometrySmith(N, V, L, roughness); // Compute the geometry term for the BRDF given roughness squared, NoV, NoL + float GVis = (G*VdotH)/(NdotH*NdotV); // Compute the visibility term given G, VoH, NoH, NoV, NoL + float Fc = pow(1.0 - VdotH, 5.0); // Compute the fresnel term given VoH + + A += (1.0 - Fc)*GVis; // Sum the result given fresnel, geometry, visibility + B += Fc*GVis; + } + } + + // Calculate brdf average sample + A /= float(MAX_SAMPLES); + B /= float(MAX_SAMPLES); + + return vec2(A, B); +} + +void main() +{ + // Calculate brdf based on texture coordinates + vec2 brdf = IntegrateBRDF(fragTexCoord.x, fragTexCoord.y); + + // Calculate final fragment color + finalColor = vec4(brdf.r, brdf.g, 0.0, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/brdf.vs b/examples/models/resources/shaders/glsl100/brdf.vs new file mode 100644 index 00000000..06384673 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/brdf.vs @@ -0,0 +1,25 @@ +/******************************************************************************************* +* +* rPBR [shader] - Bidirectional reflectance distribution function vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; + +// Output vertex attributes (to fragment shader) +out vec2 fragTexCoord; + +void main() +{ + // Calculate fragment position based on model transformations + fragTexCoord = vertexTexCoord; + + // Calculate final vertex position + gl_Position = vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/examples/models/resources/shaders/glsl100/cubemap.fs b/examples/models/resources/shaders/glsl100/cubemap.fs new file mode 100644 index 00000000..e8e28536 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/cubemap.fs @@ -0,0 +1,38 @@ +/******************************************************************************************* +* +* rPBR [shader] - Equirectangular to cubemap fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform sampler2D equirectangularMap; + +// Output fragment color +out vec4 finalColor; + +vec2 SampleSphericalMap(vec3 v) +{ + vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); + uv *= vec2(0.1591, 0.3183); + uv += 0.5; + return uv; +} + +void main() +{ + // Normalize local position + vec2 uv = SampleSphericalMap(normalize(fragPosition)); + + // Fetch color from texture map + vec3 color = texture(equirectangularMap, uv).rgb; + + // Calculate final fragment color + finalColor = vec4(color, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/cubemap.vs b/examples/models/resources/shaders/glsl100/cubemap.vs new file mode 100644 index 00000000..5721eaa2 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/cubemap.vs @@ -0,0 +1,28 @@ +/******************************************************************************************* +* +* rPBR [shader] - Equirectangular to cubemap vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; + +// Input uniform values +uniform mat4 projection; +uniform mat4 view; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; + +void main() +{ + // Calculate fragment position based on model transformations + fragPosition = vertexPosition; + + // Calculate final vertex position + gl_Position = projection*view*vec4(vertexPosition, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/irradiance.fs b/examples/models/resources/shaders/glsl100/irradiance.fs new file mode 100644 index 00000000..b42d2143 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/irradiance.fs @@ -0,0 +1,58 @@ +/******************************************************************************************* +* +* rPBR [shader] - Irradiance cubemap fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; + +// Constant values +const float PI = 3.14159265359f; + +// Output fragment color +out vec4 finalColor; + +void main() +{ + // The sample direction equals the hemisphere's orientation + vec3 normal = normalize(fragPosition); + + vec3 irradiance = vec3(0.0); + + vec3 up = vec3(0.0, 1.0, 0.0); + vec3 right = cross(up, normal); + up = cross(normal, right); + + float sampleDelta = 0.025f; + float nrSamples = 0.0f; + + for (float phi = 0.0; phi < 2.0*PI; phi += sampleDelta) + { + for (float theta = 0.0; theta < 0.5*PI; theta += sampleDelta) + { + // Spherical to cartesian (in tangent space) + vec3 tangentSample = vec3(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)); + + // tangent space to world + vec3 sampleVec = tangentSample.x*right + tangentSample.y*up + tangentSample.z*normal; + + // Fetch color from environment cubemap + irradiance += texture(environmentMap, sampleVec).rgb*cos(theta)*sin(theta); + nrSamples++; + } + } + + // Calculate irradiance average value from samples + irradiance = PI*irradiance*(1.0/float(nrSamples)); + + // Calculate final fragment color + finalColor = vec4(irradiance, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/pbr.fs b/examples/models/resources/shaders/glsl100/pbr.fs new file mode 100644 index 00000000..38d56c5d --- /dev/null +++ b/examples/models/resources/shaders/glsl100/pbr.fs @@ -0,0 +1,298 @@ +/******************************************************************************************* +* +* rPBR [shader] - Physically based rendering fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +#define MAX_REFLECTION_LOD 4.0 +#define MAX_DEPTH_LAYER 20 +#define MIN_DEPTH_LAYER 10 + +#define MAX_LIGHTS 4 +#define LIGHT_DIRECTIONAL 0 +#define LIGHT_POINT 1 + +struct MaterialProperty { + vec3 color; + int useSampler; + sampler2D sampler; +}; + +struct Light { + int enabled; + int type; + vec3 position; + vec3 target; + vec4 color; +}; + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; +in vec2 fragTexCoord; +in vec3 fragNormal; +in vec3 fragTangent; +in vec3 fragBinormal; + +// Input material values +uniform MaterialProperty albedo; +uniform MaterialProperty normals; +uniform MaterialProperty metalness; +uniform MaterialProperty roughness; +uniform MaterialProperty occlusion; +uniform MaterialProperty emission; +uniform MaterialProperty height; + +// Input uniform values +uniform samplerCube irradianceMap; +uniform samplerCube prefilterMap; +uniform sampler2D brdfLUT; + +// Input lighting values +uniform Light lights[MAX_LIGHTS]; + +// Other uniform values +uniform int renderMode; +uniform vec3 viewPos; +vec2 texCoord; + +// Constant values +const float PI = 3.14159265359; + +// Output fragment color +out vec4 finalColor; + +vec3 ComputeMaterialProperty(MaterialProperty property); +float DistributionGGX(vec3 N, vec3 H, float roughness); +float GeometrySchlickGGX(float NdotV, float roughness); +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); +vec3 fresnelSchlick(float cosTheta, vec3 F0); +vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness); +vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir); + +vec3 ComputeMaterialProperty(MaterialProperty property) +{ + vec3 result = vec3(0.0, 0.0, 0.0); + + if (property.useSampler == 1) result = texture(property.sampler, texCoord).rgb; + else result = property.color; + + return result; +} + +float DistributionGGX(vec3 N, vec3 H, float roughness) +{ + float a = roughness*roughness; + float a2 = a*a; + float NdotH = max(dot(N, H), 0.0); + float NdotH2 = NdotH*NdotH; + + float nom = a2; + float denom = (NdotH2*(a2 - 1.0) + 1.0); + denom = PI*denom*denom; + + return nom/denom; +} + +float GeometrySchlickGGX(float NdotV, float roughness) +{ + float r = (roughness + 1.0); + float k = r*r/8.0; + + float nom = NdotV; + float denom = NdotV*(1.0 - k) + k; + + return nom/denom; +} +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) +{ + float NdotV = max(dot(N, V), 0.0); + float NdotL = max(dot(N, L), 0.0); + float ggx2 = GeometrySchlickGGX(NdotV, roughness); + float ggx1 = GeometrySchlickGGX(NdotL, roughness); + + return ggx1*ggx2; +} + +vec3 fresnelSchlick(float cosTheta, vec3 F0) +{ + return F0 + (1.0 - F0)*pow(1.0 - cosTheta, 5.0); +} + +vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) +{ + return F0 + (max(vec3(1.0 - roughness), F0) - F0)*pow(1.0 - cosTheta, 5.0); +} + +vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) +{ + // Calculate the number of depth layers and calculate the size of each layer + float numLayers = mix(MAX_DEPTH_LAYER, MIN_DEPTH_LAYER, abs(dot(vec3(0.0, 0.0, 1.0), viewDir))); + float layerDepth = 1.0/numLayers; + + // Calculate depth of current layer + float currentLayerDepth = 0.0; + + // Calculate the amount to shift the texture coordinates per layer (from vector P) + // Note: height amount is stored in height material attribute color R channel (sampler use is independent) + vec2 P = viewDir.xy*height.color.r; + vec2 deltaTexCoords = P/numLayers; + + // Store initial texture coordinates and depth values + vec2 currentTexCoords = texCoords; + float currentDepthMapValue = texture(height.sampler, currentTexCoords).r; + + while (currentLayerDepth < currentDepthMapValue) + { + // Shift texture coordinates along direction of P + currentTexCoords -= deltaTexCoords; + + // Get depth map value at current texture coordinates + currentDepthMapValue = texture(height.sampler, currentTexCoords).r; + + // Get depth of next layer + currentLayerDepth += layerDepth; + } + + // Get texture coordinates before collision (reverse operations) + vec2 prevTexCoords = currentTexCoords + deltaTexCoords; + + // Get depth after and before collision for linear interpolation + float afterDepth = currentDepthMapValue - currentLayerDepth; + float beforeDepth = texture(height.sampler, prevTexCoords).r - currentLayerDepth + layerDepth; + + // Interpolation of texture coordinates + float weight = afterDepth/(afterDepth - beforeDepth); + vec2 finalTexCoords = prevTexCoords*weight + currentTexCoords*(1.0 - weight); + + return finalTexCoords; +} + +void main() +{ + // Calculate TBN and RM matrices + mat3 TBN = transpose(mat3(fragTangent, fragBinormal, fragNormal)); + + // Calculate lighting required attributes + vec3 normal = normalize(fragNormal); + vec3 view = normalize(viewPos - fragPosition); + vec3 refl = reflect(-view, normal); + + // Check if parallax mapping is enabled and calculate texture coordinates to use based on height map + // NOTE: remember that 'texCoord' variable must be assigned before calling any ComputeMaterialProperty() function + if (height.useSampler == 1) texCoord = ParallaxMapping(fragTexCoord, view); + else texCoord = fragTexCoord; // Use default texture coordinates + + // Fetch material values from texture sampler or color attributes + vec3 color = ComputeMaterialProperty(albedo); + vec3 metal = ComputeMaterialProperty(metalness); + vec3 rough = ComputeMaterialProperty(roughness); + vec3 emiss = ComputeMaterialProperty(emission); + vec3 ao = ComputeMaterialProperty(occlusion); + + // Check if normal mapping is enabled + if (normals.useSampler == 1) + { + // Fetch normal map color and transform lighting values to tangent space + normal = ComputeMaterialProperty(normals); + normal = normalize(normal*2.0 - 1.0); + normal = normalize(normal*TBN); + + // Convert tangent space normal to world space due to cubemap reflection calculations + refl = normalize(reflect(-view, normal)); + } + + // Calculate reflectance at normal incidence + vec3 F0 = vec3(0.04); + F0 = mix(F0, color, metal.r); + + // Calculate lighting for all lights + vec3 Lo = vec3(0.0); + vec3 lightDot = vec3(0.0); + + for (int i = 0; i < MAX_LIGHTS; i++) + { + if (lights[i].enabled == 1) + { + // Calculate per-light radiance + vec3 light = vec3(0.0); + vec3 radiance = lights[i].color.rgb; + if (lights[i].type == LIGHT_DIRECTIONAL) light = -normalize(lights[i].target - lights[i].position); + else if (lights[i].type == LIGHT_POINT) + { + light = normalize(lights[i].position - fragPosition); + float distance = length(lights[i].position - fragPosition); + float attenuation = 1.0/(distance*distance); + radiance *= attenuation; + } + + // Cook-torrance BRDF + vec3 high = normalize(view + light); + float NDF = DistributionGGX(normal, high, rough.r); + float G = GeometrySmith(normal, view, light, rough.r); + vec3 F = fresnelSchlick(max(dot(high, view), 0.0), F0); + vec3 nominator = NDF*G*F; + float denominator = 4*max(dot(normal, view), 0.0)*max(dot(normal, light), 0.0) + 0.001; + vec3 brdf = nominator/denominator; + + // Store to kS the fresnel value and calculate energy conservation + vec3 kS = F; + vec3 kD = vec3(1.0) - kS; + + // Multiply kD by the inverse metalness such that only non-metals have diffuse lighting + kD *= 1.0 - metal.r; + + // Scale light by dot product between normal and light direction + float NdotL = max(dot(normal, light), 0.0); + + // Add to outgoing radiance Lo + // Note: BRDF is already multiplied by the Fresnel so it doesn't need to be multiplied again + Lo += (kD*color/PI + brdf)*radiance*NdotL*lights[i].color.a; + lightDot += radiance*NdotL + brdf*lights[i].color.a; + } + } + + // Calculate ambient lighting using IBL + vec3 F = fresnelSchlickRoughness(max(dot(normal, view), 0.0), F0, rough.r); + vec3 kS = F; + vec3 kD = 1.0 - kS; + kD *= 1.0 - metal.r; + + // Calculate indirect diffuse + vec3 irradiance = texture(irradianceMap, fragNormal).rgb; + vec3 diffuse = color*irradiance; + + // Sample both the prefilter map and the BRDF lut and combine them together as per the Split-Sum approximation + vec3 prefilterColor = textureLod(prefilterMap, refl, rough.r*MAX_REFLECTION_LOD).rgb; + vec2 brdf = texture(brdfLUT, vec2(max(dot(normal, view), 0.0), rough.r)).rg; + vec3 reflection = prefilterColor*(F*brdf.x + brdf.y); + + // Calculate final lighting + vec3 ambient = (kD*diffuse + reflection)*ao; + + // Calculate fragment color based on render mode + vec3 fragmentColor = ambient + Lo + emiss; // Physically Based Rendering + + if (renderMode == 1) fragmentColor = color; // Albedo + else if (renderMode == 2) fragmentColor = normal; // Normals + else if (renderMode == 3) fragmentColor = metal; // Metalness + else if (renderMode == 4) fragmentColor = rough; // Roughness + else if (renderMode == 5) fragmentColor = ao; // Ambient Occlusion + else if (renderMode == 6) fragmentColor = emiss; // Emission + else if (renderMode == 7) fragmentColor = lightDot; // Lighting + else if (renderMode == 8) fragmentColor = kS; // Fresnel + else if (renderMode == 9) fragmentColor = irradiance; // Irradiance + else if (renderMode == 10) fragmentColor = reflection; // Reflection + + // Apply HDR tonemapping + fragmentColor = fragmentColor/(fragmentColor + vec3(1.0)); + + // Apply gamma correction + fragmentColor = pow(fragmentColor, vec3(1.0/2.2)); + + // Calculate final fragment color + finalColor = vec4(fragmentColor, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/pbr.vs b/examples/models/resources/shaders/glsl100/pbr.vs new file mode 100644 index 00000000..8bd3faa1 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/pbr.vs @@ -0,0 +1,49 @@ +/******************************************************************************************* +* +* rPBR [shader] - Physically based rendering vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexTangent; + +// Input uniform values +uniform mat4 mvp; +uniform mat4 matModel; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; +out vec2 fragTexCoord; +out vec3 fragNormal; +out vec3 fragTangent; +out vec3 fragBinormal; + +void main() +{ + // Calculate binormal from vertex normal and tangent + vec3 vertexBinormal = cross(vertexNormal, vec3(vertexTangent)); + + // Calculate fragment normal based on normal transformations + mat3 normalMatrix = transpose(inverse(mat3(matModel))); + + // Calculate fragment position based on model transformations + fragPosition = vec3(matModel*vec4(vertexPosition, 1.0f)); + + // Send vertex attributes to fragment shader + fragTexCoord = vertexTexCoord; + fragNormal = normalize(normalMatrix*vertexNormal); + fragTangent = normalize(normalMatrix*vec3(vertexTangent)); + fragTangent = normalize(fragTangent - dot(fragTangent, fragNormal)*fragNormal); + fragBinormal = normalize(normalMatrix*vertexBinormal); + fragBinormal = cross(fragNormal, fragTangent); + + // Calculate final vertex position + gl_Position = mvp*vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/examples/models/resources/shaders/glsl100/prefilter.fs b/examples/models/resources/shaders/glsl100/prefilter.fs new file mode 100644 index 00000000..9439810d --- /dev/null +++ b/examples/models/resources/shaders/glsl100/prefilter.fs @@ -0,0 +1,120 @@ +/******************************************************************************************* +* +* rPBR [shader] - Prefiltered environment for reflections fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 +#define MAX_SAMPLES 1024u +#define CUBEMAP_RESOLUTION 1024.0 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; +uniform float roughness; + +// Constant values +const float PI = 3.14159265359f; + +// Output fragment color +out vec4 finalColor; + +float DistributionGGX(vec3 N, vec3 H, float roughness); +float RadicalInverse_VdC(uint bits); +vec2 Hammersley(uint i, uint N); +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); + +float DistributionGGX(vec3 N, vec3 H, float roughness) +{ + float a = roughness*roughness; + float a2 = a*a; + float NdotH = max(dot(N, H), 0.0); + float NdotH2 = NdotH*NdotH; + + float nom = a2; + float denom = (NdotH2*(a2 - 1.0) + 1.0); + denom = PI*denom*denom; + + return nom/denom; +} + +float RadicalInverse_VdC(uint bits) +{ + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +vec2 Hammersley(uint i, uint N) +{ + return vec2(float(i)/float(N), RadicalInverse_VdC(i)); +} + +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) +{ + float a = roughness*roughness; + float phi = 2.0 * PI * Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + + return normalize(sampleVec); +} + +void main() +{ + // Make the simplyfying assumption that V equals R equals the normal + vec3 N = normalize(fragPosition); + vec3 R = N; + vec3 V = R; + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + for (uint i = 0u; i < MAX_SAMPLES; i++) + { + // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) + vec2 Xi = Hammersley(i, MAX_SAMPLES); + vec3 H = ImportanceSampleGGX(Xi, N, roughness); + vec3 L = normalize(2.0*dot(V, H)*H - V); + + float NdotL = max(dot(N, L), 0.0); + if(NdotL > 0.0) + { + // Sample from the environment's mip level based on roughness/pdf + float D = DistributionGGX(N, H, roughness); + float NdotH = max(dot(N, H), 0.0); + float HdotV = max(dot(H, V), 0.0); + float pdf = D*NdotH/(4.0*HdotV) + 0.0001; + + float resolution = CUBEMAP_RESOLUTION; + float saTexel = 4.0*PI/(6.0*resolution*resolution); + float saSample = 1.0/(float(MAX_SAMPLES)*pdf + 0.0001); + float mipLevel = ((roughness == 0.0) ? 0.0 : 0.5*log2(saSample/saTexel)); + + prefilteredColor += textureLod(environmentMap, L, mipLevel).rgb*NdotL; + totalWeight += NdotL; + } + } + + // Calculate prefilter average color + prefilteredColor = prefilteredColor/totalWeight; + + // Calculate final fragment color + finalColor = vec4(prefilteredColor, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/skybox.fs b/examples/models/resources/shaders/glsl100/skybox.fs new file mode 100644 index 00000000..053a2517 --- /dev/null +++ b/examples/models/resources/shaders/glsl100/skybox.fs @@ -0,0 +1,31 @@ +/******************************************************************************************* +* +* rPBR [shader] - Background skybox fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; + +// Output fragment color +out vec4 finalColor; + +void main() +{ + // Fetch color from texture map + vec3 color = texture(environmentMap, fragPosition).rgb; + + // Apply gamma correction + color = color/(color + vec3(1.0)); + color = pow(color, vec3(1.0/2.2)); + + // Calculate final fragment color + finalColor = vec4(color, 1.0); +} diff --git a/examples/models/resources/shaders/glsl100/skybox.vs b/examples/models/resources/shaders/glsl100/skybox.vs new file mode 100644 index 00000000..dcbe6c3d --- /dev/null +++ b/examples/models/resources/shaders/glsl100/skybox.vs @@ -0,0 +1,32 @@ +/******************************************************************************************* +* +* rPBR [shader] - Background skybox vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; + +// Input uniform values +uniform mat4 projection; +uniform mat4 view; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; + +void main() +{ + // Calculate fragment position based on model transformations + fragPosition = vertexPosition; + + // Remove translation from the view matrix + mat4 rotView = mat4(mat3(view)); + vec4 clipPos = projection*rotView*vec4(vertexPosition, 1.0); + + // Calculate final vertex position + gl_Position = clipPos.xyww; +} diff --git a/examples/models/resources/shaders/glsl330/brdf.fs b/examples/models/resources/shaders/glsl330/brdf.fs new file mode 100644 index 00000000..d04bc661 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/brdf.fs @@ -0,0 +1,133 @@ +/******************************************************************************************* +* +* BRDF LUT Generation - Bidirectional reflectance distribution function fragment shader +* +* REF: https://github.com/HectorMF/BRDFGenerator +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + + +// Input vertex attributes (from vertex shader) +in vec2 fragTexCoord; + +// Constant values +const float PI = 3.14159265359; +const uint MAX_SAMPLES = 1024u; + +// Output fragment color +out vec4 finalColor; + +vec2 Hammersley(uint i, uint N); +float RadicalInverseVdC(uint bits); +float GeometrySchlickGGX(float NdotV, float roughness); +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); +vec2 IntegrateBRDF(float NdotV, float roughness); + +float RadicalInverseVdC(uint bits) +{ + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +// Compute Hammersley coordinates +vec2 Hammersley(uint i, uint N) +{ + return vec2(float(i)/float(N), RadicalInverseVdC(i)); +} + +// Integrate number of importance samples for (roughness and NoV) +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) +{ + float a = roughness*roughness; + float phi = 2.0 * PI * Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + + return normalize(sampleVec); +} + +float GeometrySchlickGGX(float NdotV, float roughness) +{ + // For IBL k is calculated different + float k = (roughness*roughness)/2.0; + + float nom = NdotV; + float denom = NdotV*(1.0 - k) + k; + + return nom/denom; +} + +// Compute the geometry term for the BRDF given roughness squared, NoV, NoL +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) +{ + float NdotV = max(dot(N, V), 0.0); + float NdotL = max(dot(N, L), 0.0); + float ggx2 = GeometrySchlickGGX(NdotV, roughness); + float ggx1 = GeometrySchlickGGX(NdotL, roughness); + + return ggx1*ggx2; +} + +vec2 IntegrateBRDF(float NdotV, float roughness) +{ + float A = 0.0; + float B = 0.0; + vec3 V = vec3(sqrt(1.0 - NdotV*NdotV), 0.0, NdotV); + vec3 N = vec3(0.0, 0.0, 1.0); + + for (uint i = 0u; i < MAX_SAMPLES; i++) + { + // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) + + vec2 Xi = Hammersley(i, MAX_SAMPLES); // Compute a Hammersely coordinate + vec3 H = ImportanceSampleGGX(Xi, N, roughness); // Integrate number of importance samples for (roughness and NoV) + vec3 L = normalize(2.0*dot(V, H)*H - V); // Compute reflection vector L + + float NdotL = max(L.z, 0.0); // Compute normal dot light + float NdotH = max(H.z, 0.0); // Compute normal dot half + float VdotH = max(dot(V, H), 0.0); // Compute view dot half + + if (NdotL > 0.0) + { + float G = GeometrySmith(N, V, L, roughness); // Compute the geometry term for the BRDF given roughness squared, NoV, NoL + float GVis = (G*VdotH)/(NdotH*NdotV); // Compute the visibility term given G, VoH, NoH, NoV, NoL + float Fc = pow(1.0 - VdotH, 5.0); // Compute the fresnel term given VoH + + A += (1.0 - Fc)*GVis; // Sum the result given fresnel, geometry, visibility + B += Fc*GVis; + } + } + + // Calculate brdf average sample + A /= float(MAX_SAMPLES); + B /= float(MAX_SAMPLES); + + return vec2(A, B); +} + +void main() +{ + // Calculate brdf based on texture coordinates + vec2 brdf = IntegrateBRDF(fragTexCoord.x, fragTexCoord.y); + + // Calculate final fragment color + finalColor = vec4(brdf.r, brdf.g, 0.0, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/brdf.vs b/examples/models/resources/shaders/glsl330/brdf.vs new file mode 100644 index 00000000..06384673 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/brdf.vs @@ -0,0 +1,25 @@ +/******************************************************************************************* +* +* rPBR [shader] - Bidirectional reflectance distribution function vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; + +// Output vertex attributes (to fragment shader) +out vec2 fragTexCoord; + +void main() +{ + // Calculate fragment position based on model transformations + fragTexCoord = vertexTexCoord; + + // Calculate final vertex position + gl_Position = vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/examples/models/resources/shaders/glsl330/cubemap.fs b/examples/models/resources/shaders/glsl330/cubemap.fs new file mode 100644 index 00000000..e8e28536 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/cubemap.fs @@ -0,0 +1,38 @@ +/******************************************************************************************* +* +* rPBR [shader] - Equirectangular to cubemap fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform sampler2D equirectangularMap; + +// Output fragment color +out vec4 finalColor; + +vec2 SampleSphericalMap(vec3 v) +{ + vec2 uv = vec2(atan(v.z, v.x), asin(v.y)); + uv *= vec2(0.1591, 0.3183); + uv += 0.5; + return uv; +} + +void main() +{ + // Normalize local position + vec2 uv = SampleSphericalMap(normalize(fragPosition)); + + // Fetch color from texture map + vec3 color = texture(equirectangularMap, uv).rgb; + + // Calculate final fragment color + finalColor = vec4(color, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/cubemap.vs b/examples/models/resources/shaders/glsl330/cubemap.vs new file mode 100644 index 00000000..5721eaa2 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/cubemap.vs @@ -0,0 +1,28 @@ +/******************************************************************************************* +* +* rPBR [shader] - Equirectangular to cubemap vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; + +// Input uniform values +uniform mat4 projection; +uniform mat4 view; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; + +void main() +{ + // Calculate fragment position based on model transformations + fragPosition = vertexPosition; + + // Calculate final vertex position + gl_Position = projection*view*vec4(vertexPosition, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/irradiance.fs b/examples/models/resources/shaders/glsl330/irradiance.fs new file mode 100644 index 00000000..b42d2143 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/irradiance.fs @@ -0,0 +1,58 @@ +/******************************************************************************************* +* +* rPBR [shader] - Irradiance cubemap fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; + +// Constant values +const float PI = 3.14159265359f; + +// Output fragment color +out vec4 finalColor; + +void main() +{ + // The sample direction equals the hemisphere's orientation + vec3 normal = normalize(fragPosition); + + vec3 irradiance = vec3(0.0); + + vec3 up = vec3(0.0, 1.0, 0.0); + vec3 right = cross(up, normal); + up = cross(normal, right); + + float sampleDelta = 0.025f; + float nrSamples = 0.0f; + + for (float phi = 0.0; phi < 2.0*PI; phi += sampleDelta) + { + for (float theta = 0.0; theta < 0.5*PI; theta += sampleDelta) + { + // Spherical to cartesian (in tangent space) + vec3 tangentSample = vec3(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)); + + // tangent space to world + vec3 sampleVec = tangentSample.x*right + tangentSample.y*up + tangentSample.z*normal; + + // Fetch color from environment cubemap + irradiance += texture(environmentMap, sampleVec).rgb*cos(theta)*sin(theta); + nrSamples++; + } + } + + // Calculate irradiance average value from samples + irradiance = PI*irradiance*(1.0/float(nrSamples)); + + // Calculate final fragment color + finalColor = vec4(irradiance, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/pbr.fs b/examples/models/resources/shaders/glsl330/pbr.fs new file mode 100644 index 00000000..38d56c5d --- /dev/null +++ b/examples/models/resources/shaders/glsl330/pbr.fs @@ -0,0 +1,298 @@ +/******************************************************************************************* +* +* rPBR [shader] - Physically based rendering fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +#define MAX_REFLECTION_LOD 4.0 +#define MAX_DEPTH_LAYER 20 +#define MIN_DEPTH_LAYER 10 + +#define MAX_LIGHTS 4 +#define LIGHT_DIRECTIONAL 0 +#define LIGHT_POINT 1 + +struct MaterialProperty { + vec3 color; + int useSampler; + sampler2D sampler; +}; + +struct Light { + int enabled; + int type; + vec3 position; + vec3 target; + vec4 color; +}; + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; +in vec2 fragTexCoord; +in vec3 fragNormal; +in vec3 fragTangent; +in vec3 fragBinormal; + +// Input material values +uniform MaterialProperty albedo; +uniform MaterialProperty normals; +uniform MaterialProperty metalness; +uniform MaterialProperty roughness; +uniform MaterialProperty occlusion; +uniform MaterialProperty emission; +uniform MaterialProperty height; + +// Input uniform values +uniform samplerCube irradianceMap; +uniform samplerCube prefilterMap; +uniform sampler2D brdfLUT; + +// Input lighting values +uniform Light lights[MAX_LIGHTS]; + +// Other uniform values +uniform int renderMode; +uniform vec3 viewPos; +vec2 texCoord; + +// Constant values +const float PI = 3.14159265359; + +// Output fragment color +out vec4 finalColor; + +vec3 ComputeMaterialProperty(MaterialProperty property); +float DistributionGGX(vec3 N, vec3 H, float roughness); +float GeometrySchlickGGX(float NdotV, float roughness); +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); +vec3 fresnelSchlick(float cosTheta, vec3 F0); +vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness); +vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir); + +vec3 ComputeMaterialProperty(MaterialProperty property) +{ + vec3 result = vec3(0.0, 0.0, 0.0); + + if (property.useSampler == 1) result = texture(property.sampler, texCoord).rgb; + else result = property.color; + + return result; +} + +float DistributionGGX(vec3 N, vec3 H, float roughness) +{ + float a = roughness*roughness; + float a2 = a*a; + float NdotH = max(dot(N, H), 0.0); + float NdotH2 = NdotH*NdotH; + + float nom = a2; + float denom = (NdotH2*(a2 - 1.0) + 1.0); + denom = PI*denom*denom; + + return nom/denom; +} + +float GeometrySchlickGGX(float NdotV, float roughness) +{ + float r = (roughness + 1.0); + float k = r*r/8.0; + + float nom = NdotV; + float denom = NdotV*(1.0 - k) + k; + + return nom/denom; +} +float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) +{ + float NdotV = max(dot(N, V), 0.0); + float NdotL = max(dot(N, L), 0.0); + float ggx2 = GeometrySchlickGGX(NdotV, roughness); + float ggx1 = GeometrySchlickGGX(NdotL, roughness); + + return ggx1*ggx2; +} + +vec3 fresnelSchlick(float cosTheta, vec3 F0) +{ + return F0 + (1.0 - F0)*pow(1.0 - cosTheta, 5.0); +} + +vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) +{ + return F0 + (max(vec3(1.0 - roughness), F0) - F0)*pow(1.0 - cosTheta, 5.0); +} + +vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) +{ + // Calculate the number of depth layers and calculate the size of each layer + float numLayers = mix(MAX_DEPTH_LAYER, MIN_DEPTH_LAYER, abs(dot(vec3(0.0, 0.0, 1.0), viewDir))); + float layerDepth = 1.0/numLayers; + + // Calculate depth of current layer + float currentLayerDepth = 0.0; + + // Calculate the amount to shift the texture coordinates per layer (from vector P) + // Note: height amount is stored in height material attribute color R channel (sampler use is independent) + vec2 P = viewDir.xy*height.color.r; + vec2 deltaTexCoords = P/numLayers; + + // Store initial texture coordinates and depth values + vec2 currentTexCoords = texCoords; + float currentDepthMapValue = texture(height.sampler, currentTexCoords).r; + + while (currentLayerDepth < currentDepthMapValue) + { + // Shift texture coordinates along direction of P + currentTexCoords -= deltaTexCoords; + + // Get depth map value at current texture coordinates + currentDepthMapValue = texture(height.sampler, currentTexCoords).r; + + // Get depth of next layer + currentLayerDepth += layerDepth; + } + + // Get texture coordinates before collision (reverse operations) + vec2 prevTexCoords = currentTexCoords + deltaTexCoords; + + // Get depth after and before collision for linear interpolation + float afterDepth = currentDepthMapValue - currentLayerDepth; + float beforeDepth = texture(height.sampler, prevTexCoords).r - currentLayerDepth + layerDepth; + + // Interpolation of texture coordinates + float weight = afterDepth/(afterDepth - beforeDepth); + vec2 finalTexCoords = prevTexCoords*weight + currentTexCoords*(1.0 - weight); + + return finalTexCoords; +} + +void main() +{ + // Calculate TBN and RM matrices + mat3 TBN = transpose(mat3(fragTangent, fragBinormal, fragNormal)); + + // Calculate lighting required attributes + vec3 normal = normalize(fragNormal); + vec3 view = normalize(viewPos - fragPosition); + vec3 refl = reflect(-view, normal); + + // Check if parallax mapping is enabled and calculate texture coordinates to use based on height map + // NOTE: remember that 'texCoord' variable must be assigned before calling any ComputeMaterialProperty() function + if (height.useSampler == 1) texCoord = ParallaxMapping(fragTexCoord, view); + else texCoord = fragTexCoord; // Use default texture coordinates + + // Fetch material values from texture sampler or color attributes + vec3 color = ComputeMaterialProperty(albedo); + vec3 metal = ComputeMaterialProperty(metalness); + vec3 rough = ComputeMaterialProperty(roughness); + vec3 emiss = ComputeMaterialProperty(emission); + vec3 ao = ComputeMaterialProperty(occlusion); + + // Check if normal mapping is enabled + if (normals.useSampler == 1) + { + // Fetch normal map color and transform lighting values to tangent space + normal = ComputeMaterialProperty(normals); + normal = normalize(normal*2.0 - 1.0); + normal = normalize(normal*TBN); + + // Convert tangent space normal to world space due to cubemap reflection calculations + refl = normalize(reflect(-view, normal)); + } + + // Calculate reflectance at normal incidence + vec3 F0 = vec3(0.04); + F0 = mix(F0, color, metal.r); + + // Calculate lighting for all lights + vec3 Lo = vec3(0.0); + vec3 lightDot = vec3(0.0); + + for (int i = 0; i < MAX_LIGHTS; i++) + { + if (lights[i].enabled == 1) + { + // Calculate per-light radiance + vec3 light = vec3(0.0); + vec3 radiance = lights[i].color.rgb; + if (lights[i].type == LIGHT_DIRECTIONAL) light = -normalize(lights[i].target - lights[i].position); + else if (lights[i].type == LIGHT_POINT) + { + light = normalize(lights[i].position - fragPosition); + float distance = length(lights[i].position - fragPosition); + float attenuation = 1.0/(distance*distance); + radiance *= attenuation; + } + + // Cook-torrance BRDF + vec3 high = normalize(view + light); + float NDF = DistributionGGX(normal, high, rough.r); + float G = GeometrySmith(normal, view, light, rough.r); + vec3 F = fresnelSchlick(max(dot(high, view), 0.0), F0); + vec3 nominator = NDF*G*F; + float denominator = 4*max(dot(normal, view), 0.0)*max(dot(normal, light), 0.0) + 0.001; + vec3 brdf = nominator/denominator; + + // Store to kS the fresnel value and calculate energy conservation + vec3 kS = F; + vec3 kD = vec3(1.0) - kS; + + // Multiply kD by the inverse metalness such that only non-metals have diffuse lighting + kD *= 1.0 - metal.r; + + // Scale light by dot product between normal and light direction + float NdotL = max(dot(normal, light), 0.0); + + // Add to outgoing radiance Lo + // Note: BRDF is already multiplied by the Fresnel so it doesn't need to be multiplied again + Lo += (kD*color/PI + brdf)*radiance*NdotL*lights[i].color.a; + lightDot += radiance*NdotL + brdf*lights[i].color.a; + } + } + + // Calculate ambient lighting using IBL + vec3 F = fresnelSchlickRoughness(max(dot(normal, view), 0.0), F0, rough.r); + vec3 kS = F; + vec3 kD = 1.0 - kS; + kD *= 1.0 - metal.r; + + // Calculate indirect diffuse + vec3 irradiance = texture(irradianceMap, fragNormal).rgb; + vec3 diffuse = color*irradiance; + + // Sample both the prefilter map and the BRDF lut and combine them together as per the Split-Sum approximation + vec3 prefilterColor = textureLod(prefilterMap, refl, rough.r*MAX_REFLECTION_LOD).rgb; + vec2 brdf = texture(brdfLUT, vec2(max(dot(normal, view), 0.0), rough.r)).rg; + vec3 reflection = prefilterColor*(F*brdf.x + brdf.y); + + // Calculate final lighting + vec3 ambient = (kD*diffuse + reflection)*ao; + + // Calculate fragment color based on render mode + vec3 fragmentColor = ambient + Lo + emiss; // Physically Based Rendering + + if (renderMode == 1) fragmentColor = color; // Albedo + else if (renderMode == 2) fragmentColor = normal; // Normals + else if (renderMode == 3) fragmentColor = metal; // Metalness + else if (renderMode == 4) fragmentColor = rough; // Roughness + else if (renderMode == 5) fragmentColor = ao; // Ambient Occlusion + else if (renderMode == 6) fragmentColor = emiss; // Emission + else if (renderMode == 7) fragmentColor = lightDot; // Lighting + else if (renderMode == 8) fragmentColor = kS; // Fresnel + else if (renderMode == 9) fragmentColor = irradiance; // Irradiance + else if (renderMode == 10) fragmentColor = reflection; // Reflection + + // Apply HDR tonemapping + fragmentColor = fragmentColor/(fragmentColor + vec3(1.0)); + + // Apply gamma correction + fragmentColor = pow(fragmentColor, vec3(1.0/2.2)); + + // Calculate final fragment color + finalColor = vec4(fragmentColor, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/pbr.vs b/examples/models/resources/shaders/glsl330/pbr.vs new file mode 100644 index 00000000..8bd3faa1 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/pbr.vs @@ -0,0 +1,49 @@ +/******************************************************************************************* +* +* rPBR [shader] - Physically based rendering vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; +in vec2 vertexTexCoord; +in vec3 vertexNormal; +in vec4 vertexTangent; + +// Input uniform values +uniform mat4 mvp; +uniform mat4 matModel; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; +out vec2 fragTexCoord; +out vec3 fragNormal; +out vec3 fragTangent; +out vec3 fragBinormal; + +void main() +{ + // Calculate binormal from vertex normal and tangent + vec3 vertexBinormal = cross(vertexNormal, vec3(vertexTangent)); + + // Calculate fragment normal based on normal transformations + mat3 normalMatrix = transpose(inverse(mat3(matModel))); + + // Calculate fragment position based on model transformations + fragPosition = vec3(matModel*vec4(vertexPosition, 1.0f)); + + // Send vertex attributes to fragment shader + fragTexCoord = vertexTexCoord; + fragNormal = normalize(normalMatrix*vertexNormal); + fragTangent = normalize(normalMatrix*vec3(vertexTangent)); + fragTangent = normalize(fragTangent - dot(fragTangent, fragNormal)*fragNormal); + fragBinormal = normalize(normalMatrix*vertexBinormal); + fragBinormal = cross(fragNormal, fragTangent); + + // Calculate final vertex position + gl_Position = mvp*vec4(vertexPosition, 1.0); +} \ No newline at end of file diff --git a/examples/models/resources/shaders/glsl330/prefilter.fs b/examples/models/resources/shaders/glsl330/prefilter.fs new file mode 100644 index 00000000..9439810d --- /dev/null +++ b/examples/models/resources/shaders/glsl330/prefilter.fs @@ -0,0 +1,120 @@ +/******************************************************************************************* +* +* rPBR [shader] - Prefiltered environment for reflections fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 +#define MAX_SAMPLES 1024u +#define CUBEMAP_RESOLUTION 1024.0 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; +uniform float roughness; + +// Constant values +const float PI = 3.14159265359f; + +// Output fragment color +out vec4 finalColor; + +float DistributionGGX(vec3 N, vec3 H, float roughness); +float RadicalInverse_VdC(uint bits); +vec2 Hammersley(uint i, uint N); +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); + +float DistributionGGX(vec3 N, vec3 H, float roughness) +{ + float a = roughness*roughness; + float a2 = a*a; + float NdotH = max(dot(N, H), 0.0); + float NdotH2 = NdotH*NdotH; + + float nom = a2; + float denom = (NdotH2*(a2 - 1.0) + 1.0); + denom = PI*denom*denom; + + return nom/denom; +} + +float RadicalInverse_VdC(uint bits) +{ + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 +} + +vec2 Hammersley(uint i, uint N) +{ + return vec2(float(i)/float(N), RadicalInverse_VdC(i)); +} + +vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) +{ + float a = roughness*roughness; + float phi = 2.0 * PI * Xi.x; + float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); + float sinTheta = sqrt(1.0 - cosTheta*cosTheta); + + // Transform from spherical coordinates to cartesian coordinates (halfway vector) + vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); + + // Transform from tangent space H vector to world space sample vector + vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; + + return normalize(sampleVec); +} + +void main() +{ + // Make the simplyfying assumption that V equals R equals the normal + vec3 N = normalize(fragPosition); + vec3 R = N; + vec3 V = R; + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + for (uint i = 0u; i < MAX_SAMPLES; i++) + { + // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) + vec2 Xi = Hammersley(i, MAX_SAMPLES); + vec3 H = ImportanceSampleGGX(Xi, N, roughness); + vec3 L = normalize(2.0*dot(V, H)*H - V); + + float NdotL = max(dot(N, L), 0.0); + if(NdotL > 0.0) + { + // Sample from the environment's mip level based on roughness/pdf + float D = DistributionGGX(N, H, roughness); + float NdotH = max(dot(N, H), 0.0); + float HdotV = max(dot(H, V), 0.0); + float pdf = D*NdotH/(4.0*HdotV) + 0.0001; + + float resolution = CUBEMAP_RESOLUTION; + float saTexel = 4.0*PI/(6.0*resolution*resolution); + float saSample = 1.0/(float(MAX_SAMPLES)*pdf + 0.0001); + float mipLevel = ((roughness == 0.0) ? 0.0 : 0.5*log2(saSample/saTexel)); + + prefilteredColor += textureLod(environmentMap, L, mipLevel).rgb*NdotL; + totalWeight += NdotL; + } + } + + // Calculate prefilter average color + prefilteredColor = prefilteredColor/totalWeight; + + // Calculate final fragment color + finalColor = vec4(prefilteredColor, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/skybox.fs b/examples/models/resources/shaders/glsl330/skybox.fs new file mode 100644 index 00000000..053a2517 --- /dev/null +++ b/examples/models/resources/shaders/glsl330/skybox.fs @@ -0,0 +1,31 @@ +/******************************************************************************************* +* +* rPBR [shader] - Background skybox fragment shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes (from vertex shader) +in vec3 fragPosition; + +// Input uniform values +uniform samplerCube environmentMap; + +// Output fragment color +out vec4 finalColor; + +void main() +{ + // Fetch color from texture map + vec3 color = texture(environmentMap, fragPosition).rgb; + + // Apply gamma correction + color = color/(color + vec3(1.0)); + color = pow(color, vec3(1.0/2.2)); + + // Calculate final fragment color + finalColor = vec4(color, 1.0); +} diff --git a/examples/models/resources/shaders/glsl330/skybox.vs b/examples/models/resources/shaders/glsl330/skybox.vs new file mode 100644 index 00000000..dcbe6c3d --- /dev/null +++ b/examples/models/resources/shaders/glsl330/skybox.vs @@ -0,0 +1,32 @@ +/******************************************************************************************* +* +* rPBR [shader] - Background skybox vertex shader +* +* Copyright (c) 2017 Victor Fisac +* +**********************************************************************************************/ + +#version 330 + +// Input vertex attributes +in vec3 vertexPosition; + +// Input uniform values +uniform mat4 projection; +uniform mat4 view; + +// Output vertex attributes (to fragment shader) +out vec3 fragPosition; + +void main() +{ + // Calculate fragment position based on model transformations + fragPosition = vertexPosition; + + // Remove translation from the view matrix + mat4 rotView = mat4(mat3(view)); + vec4 clipPos = projection*rotView*vec4(vertexPosition, 1.0); + + // Calculate final vertex position + gl_Position = clipPos.xyww; +} diff --git a/examples/models/resources/shaders/irradiance.fs b/examples/models/resources/shaders/irradiance.fs deleted file mode 100644 index b42d2143..00000000 --- a/examples/models/resources/shaders/irradiance.fs +++ /dev/null @@ -1,58 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Irradiance cubemap fragment shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes (from vertex shader) -in vec3 fragPosition; - -// Input uniform values -uniform samplerCube environmentMap; - -// Constant values -const float PI = 3.14159265359f; - -// Output fragment color -out vec4 finalColor; - -void main() -{ - // The sample direction equals the hemisphere's orientation - vec3 normal = normalize(fragPosition); - - vec3 irradiance = vec3(0.0); - - vec3 up = vec3(0.0, 1.0, 0.0); - vec3 right = cross(up, normal); - up = cross(normal, right); - - float sampleDelta = 0.025f; - float nrSamples = 0.0f; - - for (float phi = 0.0; phi < 2.0*PI; phi += sampleDelta) - { - for (float theta = 0.0; theta < 0.5*PI; theta += sampleDelta) - { - // Spherical to cartesian (in tangent space) - vec3 tangentSample = vec3(sin(theta)*cos(phi), sin(theta)*sin(phi), cos(theta)); - - // tangent space to world - vec3 sampleVec = tangentSample.x*right + tangentSample.y*up + tangentSample.z*normal; - - // Fetch color from environment cubemap - irradiance += texture(environmentMap, sampleVec).rgb*cos(theta)*sin(theta); - nrSamples++; - } - } - - // Calculate irradiance average value from samples - irradiance = PI*irradiance*(1.0/float(nrSamples)); - - // Calculate final fragment color - finalColor = vec4(irradiance, 1.0); -} diff --git a/examples/models/resources/shaders/pbr.fs b/examples/models/resources/shaders/pbr.fs deleted file mode 100644 index 38d56c5d..00000000 --- a/examples/models/resources/shaders/pbr.fs +++ /dev/null @@ -1,298 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Physically based rendering fragment shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -#define MAX_REFLECTION_LOD 4.0 -#define MAX_DEPTH_LAYER 20 -#define MIN_DEPTH_LAYER 10 - -#define MAX_LIGHTS 4 -#define LIGHT_DIRECTIONAL 0 -#define LIGHT_POINT 1 - -struct MaterialProperty { - vec3 color; - int useSampler; - sampler2D sampler; -}; - -struct Light { - int enabled; - int type; - vec3 position; - vec3 target; - vec4 color; -}; - -// Input vertex attributes (from vertex shader) -in vec3 fragPosition; -in vec2 fragTexCoord; -in vec3 fragNormal; -in vec3 fragTangent; -in vec3 fragBinormal; - -// Input material values -uniform MaterialProperty albedo; -uniform MaterialProperty normals; -uniform MaterialProperty metalness; -uniform MaterialProperty roughness; -uniform MaterialProperty occlusion; -uniform MaterialProperty emission; -uniform MaterialProperty height; - -// Input uniform values -uniform samplerCube irradianceMap; -uniform samplerCube prefilterMap; -uniform sampler2D brdfLUT; - -// Input lighting values -uniform Light lights[MAX_LIGHTS]; - -// Other uniform values -uniform int renderMode; -uniform vec3 viewPos; -vec2 texCoord; - -// Constant values -const float PI = 3.14159265359; - -// Output fragment color -out vec4 finalColor; - -vec3 ComputeMaterialProperty(MaterialProperty property); -float DistributionGGX(vec3 N, vec3 H, float roughness); -float GeometrySchlickGGX(float NdotV, float roughness); -float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness); -vec3 fresnelSchlick(float cosTheta, vec3 F0); -vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness); -vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir); - -vec3 ComputeMaterialProperty(MaterialProperty property) -{ - vec3 result = vec3(0.0, 0.0, 0.0); - - if (property.useSampler == 1) result = texture(property.sampler, texCoord).rgb; - else result = property.color; - - return result; -} - -float DistributionGGX(vec3 N, vec3 H, float roughness) -{ - float a = roughness*roughness; - float a2 = a*a; - float NdotH = max(dot(N, H), 0.0); - float NdotH2 = NdotH*NdotH; - - float nom = a2; - float denom = (NdotH2*(a2 - 1.0) + 1.0); - denom = PI*denom*denom; - - return nom/denom; -} - -float GeometrySchlickGGX(float NdotV, float roughness) -{ - float r = (roughness + 1.0); - float k = r*r/8.0; - - float nom = NdotV; - float denom = NdotV*(1.0 - k) + k; - - return nom/denom; -} -float GeometrySmith(vec3 N, vec3 V, vec3 L, float roughness) -{ - float NdotV = max(dot(N, V), 0.0); - float NdotL = max(dot(N, L), 0.0); - float ggx2 = GeometrySchlickGGX(NdotV, roughness); - float ggx1 = GeometrySchlickGGX(NdotL, roughness); - - return ggx1*ggx2; -} - -vec3 fresnelSchlick(float cosTheta, vec3 F0) -{ - return F0 + (1.0 - F0)*pow(1.0 - cosTheta, 5.0); -} - -vec3 fresnelSchlickRoughness(float cosTheta, vec3 F0, float roughness) -{ - return F0 + (max(vec3(1.0 - roughness), F0) - F0)*pow(1.0 - cosTheta, 5.0); -} - -vec2 ParallaxMapping(vec2 texCoords, vec3 viewDir) -{ - // Calculate the number of depth layers and calculate the size of each layer - float numLayers = mix(MAX_DEPTH_LAYER, MIN_DEPTH_LAYER, abs(dot(vec3(0.0, 0.0, 1.0), viewDir))); - float layerDepth = 1.0/numLayers; - - // Calculate depth of current layer - float currentLayerDepth = 0.0; - - // Calculate the amount to shift the texture coordinates per layer (from vector P) - // Note: height amount is stored in height material attribute color R channel (sampler use is independent) - vec2 P = viewDir.xy*height.color.r; - vec2 deltaTexCoords = P/numLayers; - - // Store initial texture coordinates and depth values - vec2 currentTexCoords = texCoords; - float currentDepthMapValue = texture(height.sampler, currentTexCoords).r; - - while (currentLayerDepth < currentDepthMapValue) - { - // Shift texture coordinates along direction of P - currentTexCoords -= deltaTexCoords; - - // Get depth map value at current texture coordinates - currentDepthMapValue = texture(height.sampler, currentTexCoords).r; - - // Get depth of next layer - currentLayerDepth += layerDepth; - } - - // Get texture coordinates before collision (reverse operations) - vec2 prevTexCoords = currentTexCoords + deltaTexCoords; - - // Get depth after and before collision for linear interpolation - float afterDepth = currentDepthMapValue - currentLayerDepth; - float beforeDepth = texture(height.sampler, prevTexCoords).r - currentLayerDepth + layerDepth; - - // Interpolation of texture coordinates - float weight = afterDepth/(afterDepth - beforeDepth); - vec2 finalTexCoords = prevTexCoords*weight + currentTexCoords*(1.0 - weight); - - return finalTexCoords; -} - -void main() -{ - // Calculate TBN and RM matrices - mat3 TBN = transpose(mat3(fragTangent, fragBinormal, fragNormal)); - - // Calculate lighting required attributes - vec3 normal = normalize(fragNormal); - vec3 view = normalize(viewPos - fragPosition); - vec3 refl = reflect(-view, normal); - - // Check if parallax mapping is enabled and calculate texture coordinates to use based on height map - // NOTE: remember that 'texCoord' variable must be assigned before calling any ComputeMaterialProperty() function - if (height.useSampler == 1) texCoord = ParallaxMapping(fragTexCoord, view); - else texCoord = fragTexCoord; // Use default texture coordinates - - // Fetch material values from texture sampler or color attributes - vec3 color = ComputeMaterialProperty(albedo); - vec3 metal = ComputeMaterialProperty(metalness); - vec3 rough = ComputeMaterialProperty(roughness); - vec3 emiss = ComputeMaterialProperty(emission); - vec3 ao = ComputeMaterialProperty(occlusion); - - // Check if normal mapping is enabled - if (normals.useSampler == 1) - { - // Fetch normal map color and transform lighting values to tangent space - normal = ComputeMaterialProperty(normals); - normal = normalize(normal*2.0 - 1.0); - normal = normalize(normal*TBN); - - // Convert tangent space normal to world space due to cubemap reflection calculations - refl = normalize(reflect(-view, normal)); - } - - // Calculate reflectance at normal incidence - vec3 F0 = vec3(0.04); - F0 = mix(F0, color, metal.r); - - // Calculate lighting for all lights - vec3 Lo = vec3(0.0); - vec3 lightDot = vec3(0.0); - - for (int i = 0; i < MAX_LIGHTS; i++) - { - if (lights[i].enabled == 1) - { - // Calculate per-light radiance - vec3 light = vec3(0.0); - vec3 radiance = lights[i].color.rgb; - if (lights[i].type == LIGHT_DIRECTIONAL) light = -normalize(lights[i].target - lights[i].position); - else if (lights[i].type == LIGHT_POINT) - { - light = normalize(lights[i].position - fragPosition); - float distance = length(lights[i].position - fragPosition); - float attenuation = 1.0/(distance*distance); - radiance *= attenuation; - } - - // Cook-torrance BRDF - vec3 high = normalize(view + light); - float NDF = DistributionGGX(normal, high, rough.r); - float G = GeometrySmith(normal, view, light, rough.r); - vec3 F = fresnelSchlick(max(dot(high, view), 0.0), F0); - vec3 nominator = NDF*G*F; - float denominator = 4*max(dot(normal, view), 0.0)*max(dot(normal, light), 0.0) + 0.001; - vec3 brdf = nominator/denominator; - - // Store to kS the fresnel value and calculate energy conservation - vec3 kS = F; - vec3 kD = vec3(1.0) - kS; - - // Multiply kD by the inverse metalness such that only non-metals have diffuse lighting - kD *= 1.0 - metal.r; - - // Scale light by dot product between normal and light direction - float NdotL = max(dot(normal, light), 0.0); - - // Add to outgoing radiance Lo - // Note: BRDF is already multiplied by the Fresnel so it doesn't need to be multiplied again - Lo += (kD*color/PI + brdf)*radiance*NdotL*lights[i].color.a; - lightDot += radiance*NdotL + brdf*lights[i].color.a; - } - } - - // Calculate ambient lighting using IBL - vec3 F = fresnelSchlickRoughness(max(dot(normal, view), 0.0), F0, rough.r); - vec3 kS = F; - vec3 kD = 1.0 - kS; - kD *= 1.0 - metal.r; - - // Calculate indirect diffuse - vec3 irradiance = texture(irradianceMap, fragNormal).rgb; - vec3 diffuse = color*irradiance; - - // Sample both the prefilter map and the BRDF lut and combine them together as per the Split-Sum approximation - vec3 prefilterColor = textureLod(prefilterMap, refl, rough.r*MAX_REFLECTION_LOD).rgb; - vec2 brdf = texture(brdfLUT, vec2(max(dot(normal, view), 0.0), rough.r)).rg; - vec3 reflection = prefilterColor*(F*brdf.x + brdf.y); - - // Calculate final lighting - vec3 ambient = (kD*diffuse + reflection)*ao; - - // Calculate fragment color based on render mode - vec3 fragmentColor = ambient + Lo + emiss; // Physically Based Rendering - - if (renderMode == 1) fragmentColor = color; // Albedo - else if (renderMode == 2) fragmentColor = normal; // Normals - else if (renderMode == 3) fragmentColor = metal; // Metalness - else if (renderMode == 4) fragmentColor = rough; // Roughness - else if (renderMode == 5) fragmentColor = ao; // Ambient Occlusion - else if (renderMode == 6) fragmentColor = emiss; // Emission - else if (renderMode == 7) fragmentColor = lightDot; // Lighting - else if (renderMode == 8) fragmentColor = kS; // Fresnel - else if (renderMode == 9) fragmentColor = irradiance; // Irradiance - else if (renderMode == 10) fragmentColor = reflection; // Reflection - - // Apply HDR tonemapping - fragmentColor = fragmentColor/(fragmentColor + vec3(1.0)); - - // Apply gamma correction - fragmentColor = pow(fragmentColor, vec3(1.0/2.2)); - - // Calculate final fragment color - finalColor = vec4(fragmentColor, 1.0); -} diff --git a/examples/models/resources/shaders/pbr.vs b/examples/models/resources/shaders/pbr.vs deleted file mode 100644 index 8bd3faa1..00000000 --- a/examples/models/resources/shaders/pbr.vs +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Physically based rendering vertex shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes -in vec3 vertexPosition; -in vec2 vertexTexCoord; -in vec3 vertexNormal; -in vec4 vertexTangent; - -// Input uniform values -uniform mat4 mvp; -uniform mat4 matModel; - -// Output vertex attributes (to fragment shader) -out vec3 fragPosition; -out vec2 fragTexCoord; -out vec3 fragNormal; -out vec3 fragTangent; -out vec3 fragBinormal; - -void main() -{ - // Calculate binormal from vertex normal and tangent - vec3 vertexBinormal = cross(vertexNormal, vec3(vertexTangent)); - - // Calculate fragment normal based on normal transformations - mat3 normalMatrix = transpose(inverse(mat3(matModel))); - - // Calculate fragment position based on model transformations - fragPosition = vec3(matModel*vec4(vertexPosition, 1.0f)); - - // Send vertex attributes to fragment shader - fragTexCoord = vertexTexCoord; - fragNormal = normalize(normalMatrix*vertexNormal); - fragTangent = normalize(normalMatrix*vec3(vertexTangent)); - fragTangent = normalize(fragTangent - dot(fragTangent, fragNormal)*fragNormal); - fragBinormal = normalize(normalMatrix*vertexBinormal); - fragBinormal = cross(fragNormal, fragTangent); - - // Calculate final vertex position - gl_Position = mvp*vec4(vertexPosition, 1.0); -} \ No newline at end of file diff --git a/examples/models/resources/shaders/prefilter.fs b/examples/models/resources/shaders/prefilter.fs deleted file mode 100644 index 9439810d..00000000 --- a/examples/models/resources/shaders/prefilter.fs +++ /dev/null @@ -1,120 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Prefiltered environment for reflections fragment shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 -#define MAX_SAMPLES 1024u -#define CUBEMAP_RESOLUTION 1024.0 - -// Input vertex attributes (from vertex shader) -in vec3 fragPosition; - -// Input uniform values -uniform samplerCube environmentMap; -uniform float roughness; - -// Constant values -const float PI = 3.14159265359f; - -// Output fragment color -out vec4 finalColor; - -float DistributionGGX(vec3 N, vec3 H, float roughness); -float RadicalInverse_VdC(uint bits); -vec2 Hammersley(uint i, uint N); -vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness); - -float DistributionGGX(vec3 N, vec3 H, float roughness) -{ - float a = roughness*roughness; - float a2 = a*a; - float NdotH = max(dot(N, H), 0.0); - float NdotH2 = NdotH*NdotH; - - float nom = a2; - float denom = (NdotH2*(a2 - 1.0) + 1.0); - denom = PI*denom*denom; - - return nom/denom; -} - -float RadicalInverse_VdC(uint bits) -{ - bits = (bits << 16u) | (bits >> 16u); - bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); - bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); - bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); - bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); - return float(bits) * 2.3283064365386963e-10; // / 0x100000000 -} - -vec2 Hammersley(uint i, uint N) -{ - return vec2(float(i)/float(N), RadicalInverse_VdC(i)); -} - -vec3 ImportanceSampleGGX(vec2 Xi, vec3 N, float roughness) -{ - float a = roughness*roughness; - float phi = 2.0 * PI * Xi.x; - float cosTheta = sqrt((1.0 - Xi.y)/(1.0 + (a*a - 1.0)*Xi.y)); - float sinTheta = sqrt(1.0 - cosTheta*cosTheta); - - // Transform from spherical coordinates to cartesian coordinates (halfway vector) - vec3 H = vec3(cos(phi)*sinTheta, sin(phi)*sinTheta, cosTheta); - - // Transform from tangent space H vector to world space sample vector - vec3 up = ((abs(N.z) < 0.999) ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0)); - vec3 tangent = normalize(cross(up, N)); - vec3 bitangent = cross(N, tangent); - vec3 sampleVec = tangent*H.x + bitangent*H.y + N*H.z; - - return normalize(sampleVec); -} - -void main() -{ - // Make the simplyfying assumption that V equals R equals the normal - vec3 N = normalize(fragPosition); - vec3 R = N; - vec3 V = R; - - vec3 prefilteredColor = vec3(0.0); - float totalWeight = 0.0; - - for (uint i = 0u; i < MAX_SAMPLES; i++) - { - // Generate a sample vector that's biased towards the preferred alignment direction (importance sampling) - vec2 Xi = Hammersley(i, MAX_SAMPLES); - vec3 H = ImportanceSampleGGX(Xi, N, roughness); - vec3 L = normalize(2.0*dot(V, H)*H - V); - - float NdotL = max(dot(N, L), 0.0); - if(NdotL > 0.0) - { - // Sample from the environment's mip level based on roughness/pdf - float D = DistributionGGX(N, H, roughness); - float NdotH = max(dot(N, H), 0.0); - float HdotV = max(dot(H, V), 0.0); - float pdf = D*NdotH/(4.0*HdotV) + 0.0001; - - float resolution = CUBEMAP_RESOLUTION; - float saTexel = 4.0*PI/(6.0*resolution*resolution); - float saSample = 1.0/(float(MAX_SAMPLES)*pdf + 0.0001); - float mipLevel = ((roughness == 0.0) ? 0.0 : 0.5*log2(saSample/saTexel)); - - prefilteredColor += textureLod(environmentMap, L, mipLevel).rgb*NdotL; - totalWeight += NdotL; - } - } - - // Calculate prefilter average color - prefilteredColor = prefilteredColor/totalWeight; - - // Calculate final fragment color - finalColor = vec4(prefilteredColor, 1.0); -} diff --git a/examples/models/resources/shaders/skybox.fs b/examples/models/resources/shaders/skybox.fs deleted file mode 100644 index 053a2517..00000000 --- a/examples/models/resources/shaders/skybox.fs +++ /dev/null @@ -1,31 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Background skybox fragment shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes (from vertex shader) -in vec3 fragPosition; - -// Input uniform values -uniform samplerCube environmentMap; - -// Output fragment color -out vec4 finalColor; - -void main() -{ - // Fetch color from texture map - vec3 color = texture(environmentMap, fragPosition).rgb; - - // Apply gamma correction - color = color/(color + vec3(1.0)); - color = pow(color, vec3(1.0/2.2)); - - // Calculate final fragment color - finalColor = vec4(color, 1.0); -} diff --git a/examples/models/resources/shaders/skybox.vs b/examples/models/resources/shaders/skybox.vs deleted file mode 100644 index dcbe6c3d..00000000 --- a/examples/models/resources/shaders/skybox.vs +++ /dev/null @@ -1,32 +0,0 @@ -/******************************************************************************************* -* -* rPBR [shader] - Background skybox vertex shader -* -* Copyright (c) 2017 Victor Fisac -* -**********************************************************************************************/ - -#version 330 - -// Input vertex attributes -in vec3 vertexPosition; - -// Input uniform values -uniform mat4 projection; -uniform mat4 view; - -// Output vertex attributes (to fragment shader) -out vec3 fragPosition; - -void main() -{ - // Calculate fragment position based on model transformations - fragPosition = vertexPosition; - - // Remove translation from the view matrix - mat4 rotView = mat4(mat3(view)); - vec4 clipPos = projection*rotView*vec4(vertexPosition, 1.0); - - // Calculate final vertex position - gl_Position = clipPos.xyww; -} -- cgit v1.2.3 From 6332bc039878c870538ce4c1ce47d3caaf3a40c4 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 18 May 2019 01:24:00 +0200 Subject: Corrected issue with shader loading When using FormatText() several times in same function, returned string is static and so, the same is returned, resulting in failures on shader loading. --- examples/models/models_material_pbr.c | 45 +++++++++++++--------- examples/models/models_skybox.c | 20 +++++----- .../models/resources/shaders/glsl330/skybox.vs | 2 +- 3 files changed, 38 insertions(+), 29 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index b8d320c7..af2fc5b9 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -17,12 +17,6 @@ #define RLIGHTS_IMPLEMENTATION #include "rlights.h" -#if defined(PLATFORM_DESKTOP) - #define GLSL_VERSION 330 -#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB - #define GLSL_VERSION 100 -#endif - #define CUBEMAP_SIZE 512 // Cubemap texture size #define IRRADIANCE_SIZE 32 // Irradiance texture size #define PREFILTERED_SIZE 256 // Prefiltered HDR environment texture size @@ -120,9 +114,12 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) { Material mat = { 0 }; // NOTE: All maps textures are set to { 0 } - mat.shader = LoadShader(FormatText("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION)); - +#if defined(PLATFORM_DESKTOP) + mat.shader = LoadShader("resources/shaders/glsl330/pbr.vs", "resources/shaders/glsl330/pbr.fs"); +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + mat.shader = LoadShader("resources/shaders/glsl100/pbr.vs", "resources/shaders/glsl100/pbr.fs"); +#endif + // Get required locations points for PBR material // NOTE: Those location names must be available and used in the shader code mat.shader.locs[LOC_MAP_ALBEDO] = GetShaderLocation(mat.shader, "albedo.sampler"); @@ -149,20 +146,32 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) mat.maps[MAP_OCCLUSION].texture = LoadTexture("resources/pbr/trooper_ao.png"); // Load equirectangular to cubemap shader - Shader shdrCubemap = LoadShader(FormatText("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION)); +#if defined(PLATFORM_DESKTOP) + Shader shdrCubemap = LoadShader("resources/shaders/glsl330/cubemap.vs", "resources/shaders/glsl330/cubemap.fs"); +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + Shader shdrCubemap = LoadShader("resources/shaders/glsl100/cubemap.vs", "resources/shaders/glsl100/cubemap.fs"); +#endif // Load irradiance (GI) calculation shader - Shader shdrIrradiance = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/irradiance.fs", GLSL_VERSION)); +#if defined(PLATFORM_DESKTOP) + Shader shdrIrradiance = LoadShader("resources/shaders/glsl330/skybox.vs", "resources/shaders/glsl330/irradiance.fs"); +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + Shader shdrIrradiance = LoadShader("resources/shaders/glsl100/skybox.vs", "resources/shaders/glsl100/irradiance.fs"); +#endif // Load reflection prefilter calculation shader - Shader shdrPrefilter = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/prefilter.fs", GLSL_VERSION)); +#if defined(PLATFORM_DESKTOP) + Shader shdrPrefilter = LoadShader("resources/shaders/glsl330/skybox.vs", "resources/shaders/glsl330/prefilter.fs"); +#else + Shader shdrPrefilter = LoadShader("resources/shaders/glsl100/skybox.vs", "resources/shaders/glsl100/prefilter.fs"); +#endif - // Load bidirectional reflectance distribution function shader - Shader shdrBRDF = LoadShader(FormatText("resources/shaders/glsl%i/brdf.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/brdf.fs", GLSL_VERSION)); + // Load bidirectional reflectance distribution function shader +#if defined(PLATFORM_DESKTOP) + Shader shdrBRDF = LoadShader("resources/shaders/glsl330/brdf.vs", "resources/shaders/glsl330/brdf.fs"); +#else + Shader shdrBRDF = LoadShader("resources/shaders/glsl100/brdf.vs", "resources/shaders/glsl100/brdf.fs"); +#endif // Setup required shader locations SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); diff --git a/examples/models/models_skybox.c b/examples/models/models_skybox.c index 2d4d5710..d3369b70 100644 --- a/examples/models/models_skybox.c +++ b/examples/models/models_skybox.c @@ -11,12 +11,6 @@ #include "raylib.h" -#if defined(PLATFORM_DESKTOP) - #define GLSL_VERSION 330 -#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB - #define GLSL_VERSION 100 -#endif - int main() { // Initialization @@ -35,13 +29,19 @@ int main() // Load skybox shader and set required locations // NOTE: Some locations are automatically set at shader loading - skybox.materials[0].shader = LoadShader(FormatText("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), - FormatText("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION)); - +#if defined(PLATFORM_DESKTOP) + skybox.materials[0].shader = LoadShader("resources/shaders/glsl330/skybox.vs", "resources/shaders/glsl330/skybox.fs"); +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + skybox.materials[0].shader = LoadShader("resources/shaders/glsl100/skybox.vs", "resources/shaders/glsl100/skybox.fs"); +#endif SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MAP_CUBEMAP }, UNIFORM_INT); // Load cubemap shader and setup required shader locations - Shader shdrCubemap = LoadShader("resources/shaders/cubemap.vs", "resources/shaders/cubemap.fs"); +#if defined(PLATFORM_DESKTOP) + Shader shdrCubemap = LoadShader("resources/shaders/glsl330/cubemap.vs", "resources/shaders/glsl330/cubemap.fs"); +#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB + Shader shdrCubemap = LoadShader("resources/shaders/glsl100/cubemap.vs", "resources/shaders/glsl100/cubemap.fs"); +#endif SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); // Load HDR panorama (sphere) texture diff --git a/examples/models/resources/shaders/glsl330/skybox.vs b/examples/models/resources/shaders/glsl330/skybox.vs index dcbe6c3d..4fe9a2c3 100644 --- a/examples/models/resources/shaders/glsl330/skybox.vs +++ b/examples/models/resources/shaders/glsl330/skybox.vs @@ -28,5 +28,5 @@ void main() vec4 clipPos = projection*rotView*vec4(vertexPosition, 1.0); // Calculate final vertex position - gl_Position = clipPos.xyww; + gl_Position = clipPos.xyzw; } -- cgit v1.2.3 From c1594fa445d038e40bae22eb69dfa04cc406aca4 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 18 May 2019 01:31:48 +0200 Subject: Tweaks --- examples/models/models_animation.png | Bin 0 -> 67020 bytes examples/shaders/shaders_julia_set.c | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 examples/models/models_animation.png (limited to 'examples/models') diff --git a/examples/models/models_animation.png b/examples/models/models_animation.png new file mode 100644 index 00000000..57e39dd3 Binary files /dev/null and b/examples/models/models_animation.png differ diff --git a/examples/shaders/shaders_julia_set.c b/examples/shaders/shaders_julia_set.c index 6c45f843..ecaa5b6e 100644 --- a/examples/shaders/shaders_julia_set.c +++ b/examples/shaders/shaders_julia_set.c @@ -64,7 +64,7 @@ int main() int offsetLoc = GetShaderLocation(shader, "offset"); // Tell the shader what the screen dimensions, zoom, offset and c are - float screenDims[2] = { (float)screenWidth, (float)screenHeight }; + float screenDims[2] = { (float)GetScreenWidth(), (float)GetScreenHeight() }; SetShaderValue(shader, GetShaderLocation(shader, "screenDims"), screenDims, UNIFORM_VEC2); SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); -- cgit v1.2.3 From b525039e0ab8bcaa2fd6bde34c72a6405f88ae49 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 May 2019 16:36:42 +0200 Subject: Review ALL examples --- examples/audio/audio_module_playing.c | 40 +++++----- examples/audio/audio_music_stream.c | 28 +++---- examples/audio/audio_raw_stream.c | 60 +++++++------- examples/audio/audio_sound_loading.c | 14 ++-- examples/core/core_2d_camera.c | 64 +++++++-------- examples/core/core_3d_camera_first_person.c | 18 ++--- examples/core/core_3d_camera_free.c | 16 ++-- examples/core/core_3d_camera_mode.c | 4 +- examples/core/core_3d_picking.c | 6 +- examples/core/core_basic_window.c | 12 +-- examples/core/core_custom_logging.c | 96 +++++++++++------------ examples/core/core_drop_files.c | 20 ++--- examples/core/core_input_gamepad.c | 66 ++++++++-------- examples/core/core_input_gestures.c | 40 +++++----- examples/core/core_input_keys.c | 8 +- examples/core/core_input_mouse.c | 12 +-- examples/core/core_input_mouse_wheel.c | 8 +- examples/core/core_input_multitouch.c | 24 +++--- examples/core/core_loading_thread.c | 26 +++--- examples/core/core_random_values.c | 10 +-- examples/core/core_storage_values.c | 23 +++--- examples/core/core_vr_simulator.c | 30 +++---- examples/core/core_window_letterbox.c | 40 +++++----- examples/core/core_world_screen.c | 14 ++-- examples/models/models_animation.c | 10 +-- examples/models/models_billboard.c | 16 ++-- examples/models/models_box_collisions.c | 58 +++++++------- examples/models/models_cubicmap.c | 18 ++--- examples/models/models_first_person_maze.c | 34 ++++---- examples/models/models_geometric_shapes.c | 8 +- examples/models/models_heightmap.c | 12 +-- examples/models/models_material_pbr.c | 28 +++---- examples/models/models_mesh_generation.c | 36 ++++----- examples/models/models_mesh_picking.c | 79 +++++++++---------- examples/models/models_obj_loading.c | 8 +- examples/models/models_obj_viewer.c | 8 +- examples/models/models_orthographic_projection.c | 18 ++--- examples/models/models_rlgl_solar_system.c | 30 +++---- examples/models/models_skybox.c | 20 ++--- examples/models/models_yaw_pitch_roll.c | 9 +-- examples/physac/physics_demo.c | 20 ++--- examples/physac/physics_friction.c | 16 ++-- examples/physac/physics_movement.c | 18 ++--- examples/physac/physics_restitution.c | 18 ++--- examples/physac/physics_shatter.c | 14 ++-- examples/shaders/shaders_custom_uniform.c | 38 ++++----- examples/shaders/shaders_eratosthenes.c | 8 +- examples/shaders/shaders_julia_set.c | 49 ++++++------ examples/shaders/shaders_model_shader.c | 19 ++--- examples/shaders/shaders_palette_switch.c | 10 +-- examples/shaders/shaders_postprocessing.c | 44 +++++------ examples/shaders/shaders_raymarching.c | 12 +-- examples/shaders/shaders_shapes_textures.c | 36 ++++----- examples/shaders/shaders_texture_drawing.c | 19 ++--- examples/shaders/shaders_texture_waves.c | 25 +++--- examples/shapes/shapes_basic_shapes.c | 10 +-- examples/shapes/shapes_bouncing_ball.c | 34 ++++---- examples/shapes/shapes_collision_area.c | 86 ++++++++++---------- examples/shapes/shapes_colors_palette.c | 20 ++--- examples/shapes/shapes_draw_circle_sector.c | 4 +- examples/shapes/shapes_draw_rectangle_rounded.c | 22 +++--- examples/shapes/shapes_draw_ring.c | 30 +++---- examples/shapes/shapes_easings_ball_anim.c | 28 +++---- examples/shapes/shapes_easings_box_anim.c | 36 ++++----- examples/shapes/shapes_easings_rectangle_array.c | 36 ++++----- examples/shapes/shapes_following_eyes.c | 30 +++---- examples/shapes/shapes_lines_bezier.c | 18 ++--- examples/shapes/shapes_logo_raylib.c | 10 +-- examples/shapes/shapes_logo_raylib_anim.c | 8 +- examples/shapes/shapes_rectangle_scaling.c | 38 ++++----- examples/text/text_bmfont_ttf.c | 16 ++-- examples/text/text_font_sdf.c | 48 ++++++------ examples/text/text_format_text.c | 8 +- examples/text/text_input_box.c | 28 +++---- examples/text/text_raylib_fonts.c | 36 +++++---- examples/text/text_rectangle_bounds.c | 56 ++++++------- examples/text/text_sprite_fonts.c | 7 +- examples/text/text_ttf_loading.c | 63 +++++++-------- examples/text/text_unicode.c | 89 ++++++++++----------- examples/text/text_writing_anim.c | 20 ++--- examples/textures/textures_background_scrolling.c | 22 +++--- examples/textures/textures_bunnymark.c | 25 +++--- examples/textures/textures_image_drawing.c | 20 ++--- examples/textures/textures_image_generation.c | 28 +++---- examples/textures/textures_image_loading.c | 6 +- examples/textures/textures_image_processing.c | 46 +++++------ examples/textures/textures_image_text.c | 28 +++---- examples/textures/textures_logo_raylib.c | 6 +- examples/textures/textures_npatch_drawing.c | 18 ++--- examples/textures/textures_particles_blending.c | 40 +++++----- examples/textures/textures_raw_data.c | 30 +++---- examples/textures/textures_rectangle.c | 28 +++---- examples/textures/textures_sprite_button.c | 36 ++++----- examples/textures/textures_sprite_explosion.c | 56 ++++++------- examples/textures/textures_srcrec_dstrec.c | 21 ++--- examples/textures/textures_to_image.c | 12 +-- 96 files changed, 1302 insertions(+), 1318 deletions(-) (limited to 'examples/models') diff --git a/examples/audio/audio_module_playing.c b/examples/audio/audio_module_playing.c index 54bfa3d2..4aebd1e6 100644 --- a/examples/audio/audio_module_playing.c +++ b/examples/audio/audio_module_playing.c @@ -23,25 +23,25 @@ typedef struct { Color color; } CircleWave; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); // NOTE: Try to enable MSAA 4X - + InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing (streaming)"); InitAudioDevice(); // Initialize audio device - + Color colors[14] = { ORANGE, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW, GREEN, SKYBLUE, PURPLE, BEIGE }; - + // Creates ome circles for visual effect CircleWave circles[MAX_CIRCLES]; - + for (int i = MAX_CIRCLES - 1; i >= 0; i--) { circles[i].alpha = 0.0f; @@ -53,7 +53,7 @@ int main() } Music xm = LoadMusicStream("resources/chiptun1.mod"); - + PlayMusicStream(xm); float timePlayed = 0.0f; @@ -68,34 +68,34 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateMusicStream(xm); // Update music buffer with new stream data - + // Restart music playing (stop and play) - if (IsKeyPressed(KEY_SPACE)) + if (IsKeyPressed(KEY_SPACE)) { StopMusicStream(xm); PlayMusicStream(xm); } - - // Pause/Resume music playing + + // Pause/Resume music playing if (IsKeyPressed(KEY_P)) { pause = !pause; - + if (pause) PauseMusicStream(xm); else ResumeMusicStream(xm); } - + // Get timePlayed scaled to bar dimensions timePlayed = GetMusicTimePlayed(xm)/GetMusicTimeLength(xm)*(screenWidth - 40); - + // Color circles animation for (int i = MAX_CIRCLES - 1; (i >= 0) && !pause; i--) { circles[i].alpha += circles[i].speed; circles[i].radius += circles[i].speed*10.0f; - + if (circles[i].alpha > 1.0f) circles[i].speed *= -1; - + if (circles[i].alpha <= 0.0f) { circles[i].alpha = 0.0f; @@ -113,12 +113,12 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + for (int i = MAX_CIRCLES - 1; i >= 0; i--) { DrawCircleV(circles[i].position, circles[i].radius, Fade(circles[i].color, circles[i].alpha)); } - + // Draw time bar DrawRectangle(20, screenHeight - 20 - 12, screenWidth - 40, 12, LIGHTGRAY); DrawRectangle(20, screenHeight - 20 - 12, (int)timePlayed, 12, MAROON); @@ -131,7 +131,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- UnloadMusicStream(xm); // Unload music stream buffers from RAM - + CloseAudioDevice(); // Close audio device (music streaming is automatically stopped) CloseWindow(); // Close window and OpenGL context diff --git a/examples/audio/audio_music_stream.c b/examples/audio/audio_music_stream.c index 80dc6f5a..76efb7db 100644 --- a/examples/audio/audio_music_stream.c +++ b/examples/audio/audio_music_stream.c @@ -4,7 +4,7 @@ * * NOTE: This example requires OpenAL Soft library installed * -* This example has been created using raylib 1.7 (www.raylib.com) +* This example has been created using raylib 1.3 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * * Copyright (c) 2015 Ramon Santamaria (@raysan5) @@ -13,19 +13,19 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [audio] example - music playing (streaming)"); InitAudioDevice(); // Initialize audio device Music music = LoadMusicStream("resources/guitar_noodling.ogg"); - + PlayMusicStream(music); float timePlayed = 0.0f; @@ -39,27 +39,27 @@ int main() { // Update //---------------------------------------------------------------------------------- - UpdateMusicStream(music); // Update music buffer with new stream data - + UpdateMusicStream(music); // Update music buffer with new stream data + // Restart music playing (stop and play) - if (IsKeyPressed(KEY_SPACE)) + if (IsKeyPressed(KEY_SPACE)) { StopMusicStream(music); PlayMusicStream(music); } - - // Pause/Resume music playing + + // Pause/Resume music playing if (IsKeyPressed(KEY_P)) { pause = !pause; - + if (pause) PauseMusicStream(music); else ResumeMusicStream(music); } - + // Get timePlayed scaled to bar dimensions (400 pixels) timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*400; - + if (timePlayed > 400) StopMusicStream(music); //---------------------------------------------------------------------------------- @@ -74,7 +74,7 @@ int main() DrawRectangle(200, 200, 400, 12, LIGHTGRAY); DrawRectangle(200, 200, (int)timePlayed, 12, MAROON); DrawRectangleLines(200, 200, 400, 12, GRAY); - + DrawText("PRESS SPACE TO RESTART MUSIC", 215, 250, 20, LIGHTGRAY); DrawText("PRESS P TO PAUSE/RESUME MUSIC", 208, 280, 20, LIGHTGRAY); diff --git a/examples/audio/audio_raw_stream.c b/examples/audio/audio_raw_stream.c index d7fa5d79..b114173a 100644 --- a/examples/audio/audio_raw_stream.c +++ b/examples/audio/audio_raw_stream.c @@ -20,12 +20,12 @@ #define MAX_SAMPLES 512 #define MAX_SAMPLES_PER_UPDATE 4096 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [audio] example - raw audio streaming"); @@ -33,30 +33,30 @@ int main() // Init raw audio stream (sample rate: 22050, sample size: 16bit-short, channels: 1-mono) AudioStream stream = InitAudioStream(22050, 16, 1); - + // Buffer for the single cycle waveform we are synthesizing short *data = (short *)malloc(sizeof(short)*MAX_SAMPLES); // Frame buffer, describing the waveform when repeated over the course of a frame short *writeBuf = (short *)malloc(sizeof(short)*MAX_SAMPLES_PER_UPDATE); - + PlayAudioStream(stream); // Start processing stream buffer (no data loaded currently) - + // Position read in to determine next frequency Vector2 mousePosition = { -100.0f, -100.0f }; - + // Cycles per second (hz) float frequency = 440.0f; - + // Previous value, used to test if sine needs to be rewritten, and to smoothly modulate frequency float oldFrequency = 1.0f; - + // Cursor to read and copy the samples of the sine wave buffer int readCursor = 0; - + // Computed size in samples of the sine wave int waveLength = 1; - + Vector2 position = { 0, 0 }; SetTargetFPS(30); // Set our game to run at 30 frames-per-second @@ -67,62 +67,62 @@ int main() { // Update //---------------------------------------------------------------------------------- - + // Sample mouse input. mousePosition = GetMousePosition(); - - if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) + + if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) { float fp = (float)(mousePosition.y); frequency = 40.0f + (float)(fp); } - + // Rewrite the sine wave. // Compute two cycles to allow the buffer padding, simplifying any modulation, resampling, etc. - if (frequency != oldFrequency) + if (frequency != oldFrequency) { // Compute wavelength. Limit size in both directions. int oldWavelength = waveLength; waveLength = (int)(22050/frequency); if (waveLength > MAX_SAMPLES/2) waveLength = MAX_SAMPLES/2; if (waveLength < 1) waveLength = 1; - + // Write sine wave. for (int i = 0; i < waveLength*2; i++) { data[i] = (short)(sinf(((2*PI*(float)i/waveLength)))*32000); } - + // Scale read cursor's position to minimize transition artifacts readCursor = (int)(readCursor * ((float)waveLength / (float)oldWavelength)); oldFrequency = frequency; } - + // Refill audio stream if required - if (IsAudioBufferProcessed(stream)) + if (IsAudioBufferProcessed(stream)) { // Synthesize a buffer that is exactly the requested size int writeCursor = 0; - - while (writeCursor < MAX_SAMPLES_PER_UPDATE) + + while (writeCursor < MAX_SAMPLES_PER_UPDATE) { // Start by trying to write the whole chunk at once int writeLength = MAX_SAMPLES_PER_UPDATE-writeCursor; - + // Limit to the maximum readable size int readLength = waveLength-readCursor; - + if (writeLength > readLength) writeLength = readLength; // Write the slice memcpy(writeBuf + writeCursor, data + readCursor, writeLength*sizeof(short)); - + // Update cursors and loop audio readCursor = (readCursor + writeLength) % waveLength; - + writeCursor += writeLength; } - + // Copy finished frame to audio stream UpdateAudioStream(stream, writeBuf, MAX_SAMPLES_PER_UPDATE); } @@ -136,13 +136,13 @@ int main() DrawText(FormatText("sine frequency: %i",(int)frequency), GetScreenWidth() - 220, 10, 20, RED); DrawText("click mouse button to change frequency", 10, 10, 20, DARKGRAY); - + // Draw the current buffer state proportionate to the screen for (int i = 0; i < screenWidth; i++) { position.x = i; position.y = 250 + 50*data[i*MAX_SAMPLES/screenWidth]/32000; - + DrawPixelV(position, RED); } @@ -154,7 +154,7 @@ int main() //-------------------------------------------------------------------------------------- free(data); // Unload sine wave data free(writeBuf); // Unload write buffer - + CloseAudioStream(stream); // Close raw audio stream and delete buffers from RAM CloseAudioDevice(); // Close audio device (music streaming is automatically stopped) diff --git a/examples/audio/audio_sound_loading.c b/examples/audio/audio_sound_loading.c index f66a3afd..d208dd9a 100644 --- a/examples/audio/audio_sound_loading.c +++ b/examples/audio/audio_sound_loading.c @@ -4,21 +4,21 @@ * * NOTE: This example requires OpenAL Soft library installed * -* This example has been created using raylib 1.3 (www.raylib.com) +* This example has been created using raylib 1.0 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2015 Ramon Santamaria (@raysan5) +* Copyright (c) 2014 Ramon Santamaria (@raysan5) * ********************************************************************************************/ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading and playing"); @@ -26,8 +26,8 @@ int main() Sound fxWav = LoadSound("resources/sound.wav"); // Load WAV audio file Sound fxOgg = LoadSound("resources/tanatana.ogg"); // Load OGG audio file - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/core/core_2d_camera.c b/examples/core/core_2d_camera.c index 6a0b11ad..fe8e584b 100644 --- a/examples/core/core_2d_camera.c +++ b/examples/core/core_2d_camera.c @@ -13,21 +13,21 @@ #define MAX_BUILDINGS 100 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera"); - + Rectangle player = { 400, 280, 40, 40 }; Rectangle buildings[MAX_BUILDINGS]; Color buildColors[MAX_BUILDINGS]; - + int spacing = 0; - + for (int i = 0; i < MAX_BUILDINGS; i++) { buildings[i].width = GetRandomValue(50, 200); @@ -36,22 +36,22 @@ int main() buildings[i].x = -6000 + spacing; spacing += buildings[i].width; - + buildColors[i] = (Color){ GetRandomValue(200, 240), GetRandomValue(200, 240), GetRandomValue(200, 250), 255 }; } - - Camera2D camera; - + + Camera2D camera = { 0 }; + camera.target = (Vector2){ player.x + 20, player.y + 20 }; camera.offset = (Vector2){ 0, 0 }; camera.rotation = 0.0f; camera.zoom = 1.0f; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- @@ -65,26 +65,26 @@ int main() player.x -= 2; // Player movement camera.offset.x += 2; // Camera displacement with player movement } - + // Camera target follows player camera.target = (Vector2){ player.x + 20, player.y + 20 }; - + // Camera rotation controls if (IsKeyDown(KEY_A)) camera.rotation--; else if (IsKeyDown(KEY_S)) camera.rotation++; - + // Limit camera rotation to 80 degrees (-40 to 40) - if (camera.rotation > 40) camera.rotation = 40; + if (camera.rotation > 40) camera.rotation = 40; else if (camera.rotation < -40) camera.rotation = -40; - + // Camera zoom controls camera.zoom += ((float)GetMouseWheelMove()*0.05f); - + if (camera.zoom > 3.0f) camera.zoom = 3.0f; else if (camera.zoom < 0.1f) camera.zoom = 0.1f; - + // Camera reset (zoom and rotation) - if (IsKeyPressed(KEY_R)) + if (IsKeyPressed(KEY_R)) { camera.zoom = 1.0f; camera.rotation = 0.0f; @@ -94,32 +94,32 @@ int main() // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + BeginMode2D(camera); DrawRectangle(-6000, 320, 13000, 8000, DARKGRAY); - + for (int i = 0; i < MAX_BUILDINGS; i++) DrawRectangleRec(buildings[i], buildColors[i]); - + DrawRectangleRec(player, RED); - + DrawLine(camera.target.x, -screenHeight*10, camera.target.x, screenHeight*10, GREEN); DrawLine(-screenWidth*10, camera.target.y, screenWidth*10, camera.target.y, GREEN); - + EndMode2D(); - + DrawText("SCREEN AREA", 640, 10, 20, RED); - + DrawRectangle(0, 0, screenWidth, 5, RED); DrawRectangle(0, 5, 5, screenHeight - 10, RED); DrawRectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED); DrawRectangle(0, screenHeight - 5, screenWidth, 5, RED); - + DrawRectangle( 10, 10, 250, 113, Fade(SKYBLUE, 0.5f)); DrawRectangleLines( 10, 10, 250, 113, BLUE); - + DrawText("Free 2d camera controls:", 20, 20, 10, BLACK); DrawText("- Right/Left to move Offset", 40, 40, 10, DARKGRAY); DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, DARKGRAY); @@ -131,7 +131,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_3d_camera_first_person.c b/examples/core/core_3d_camera_first_person.c index d3a8f2e4..825a9ca8 100644 --- a/examples/core/core_3d_camera_first_person.c +++ b/examples/core/core_3d_camera_first_person.c @@ -13,15 +13,15 @@ #define MAX_COLUMNS 20 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person"); - + // Define the camera to look into our 3d world (position, target, up vector) Camera camera = { 0 }; camera.position = (Vector3){ 4.0f, 2.0f, 4.0f }; @@ -34,14 +34,14 @@ int main() float heights[MAX_COLUMNS]; Vector3 positions[MAX_COLUMNS]; Color colors[MAX_COLUMNS]; - + for (int i = 0; i < MAX_COLUMNS; i++) { heights[i] = (float)GetRandomValue(1, 12); positions[i] = (Vector3){ GetRandomValue(-15, 15), heights[i]/2, GetRandomValue(-15, 15) }; colors[i] = (Color){ GetRandomValue(20, 255), GetRandomValue(10, 55), 30, 255 }; } - + SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -67,7 +67,7 @@ int main() DrawCube((Vector3){ -16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, BLUE); // Draw a blue wall DrawCube((Vector3){ 16.0f, 2.5f, 0.0f }, 1.0f, 5.0f, 32.0f, LIME); // Draw a green wall DrawCube((Vector3){ 0.0f, 2.5f, 16.0f }, 32.0f, 5.0f, 1.0f, GOLD); // Draw a yellow wall - + // Draw some cubes around for (int i = 0; i < MAX_COLUMNS; i++) { @@ -76,7 +76,7 @@ int main() } EndMode3D(); - + DrawRectangle( 10, 10, 220, 70, Fade(SKYBLUE, 0.5f)); DrawRectangleLines( 10, 10, 220, 70, BLUE); @@ -89,7 +89,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_3d_camera_free.c b/examples/core/core_3d_camera_free.c index 9131ddf8..c1445f60 100644 --- a/examples/core/core_3d_camera_free.c +++ b/examples/core/core_3d_camera_free.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free"); @@ -27,9 +27,9 @@ int main() camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.fovy = 45.0f; // Camera field-of-view Y camera.type = CAMERA_PERSPECTIVE; // Camera mode type - + Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - + SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -41,7 +41,7 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update camera - + if (IsKeyDown('Z')) camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; //---------------------------------------------------------------------------------- @@ -59,10 +59,10 @@ int main() DrawGrid(10, 1.0f); EndMode3D(); - + DrawRectangle( 10, 10, 320, 133, Fade(SKYBLUE, 0.5f)); DrawRectangleLines( 10, 10, 320, 133, BLUE); - + DrawText("Free camera default controls:", 20, 20, 10, BLACK); DrawText("- Mouse Wheel to Zoom in-out", 40, 40, 10, DARKGRAY); DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, DARKGRAY); diff --git a/examples/core/core_3d_camera_mode.c b/examples/core/core_3d_camera_mode.c index a4962200..eae6c888 100644 --- a/examples/core/core_3d_camera_mode.c +++ b/examples/core/core_3d_camera_mode.c @@ -11,7 +11,7 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -30,7 +30,7 @@ int main() Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/core/core_3d_picking.c b/examples/core/core_3d_picking.c index 1c63e2a7..1e60c03b 100644 --- a/examples/core/core_3d_picking.c +++ b/examples/core/core_3d_picking.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking"); diff --git a/examples/core/core_basic_window.c b/examples/core/core_basic_window.c index b30f05de..3c103a5f 100644 --- a/examples/core/core_basic_window.c +++ b/examples/core/core_basic_window.c @@ -21,16 +21,16 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -54,7 +54,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_custom_logging.c b/examples/core/core_custom_logging.c index cf1a601f..0ab3fa45 100644 --- a/examples/core/core_custom_logging.c +++ b/examples/core/core_custom_logging.c @@ -19,66 +19,66 @@ // Custom logging funtion void LogCustom(int msgType, const char *text, va_list args) { - char timeStr[64]; - time_t now = time(NULL); - struct tm *tm_info = localtime(&now); - - strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", tm_info); - printf("[%s] ", timeStr); - - switch (msgType) - { - case LOG_INFO: printf("[INFO] : "); break; - case LOG_ERROR: printf("[ERROR]: "); break; - case LOG_WARNING: printf("[WARN] : "); break; - case LOG_DEBUG: printf("[DEBUG]: "); break; - default: break; - } - - vprintf(text, args); - printf("\n"); + char timeStr[64]; + time_t now = time(NULL); + struct tm *tm_info = localtime(&now); + + strftime(timeStr, sizeof(timeStr), "%Y-%m-%d %H:%M:%S", tm_info); + printf("[%s] ", timeStr); + + switch (msgType) + { + case LOG_INFO: printf("[INFO] : "); break; + case LOG_ERROR: printf("[ERROR]: "); break; + case LOG_WARNING: printf("[WARN] : "); break; + case LOG_DEBUG: printf("[DEBUG]: "); break; + default: break; + } + + vprintf(text, args); + printf("\n"); } int main(int argc, char* argv[]) { - // Initialization - //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; - // First thing we do is setting our custom logger to ensure everything raylib logs - // will use our own logger instead of its internal one - SetTraceLogCallback(LogCustom); + // First thing we do is setting our custom logger to ensure everything raylib logs + // will use our own logger instead of its internal one + SetTraceLogCallback(LogCustom); - InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging"); + InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging"); - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- - // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key - { - // Update - //---------------------------------------------------------------------------------- - // TODO: Update your variables here - //---------------------------------------------------------------------------------- + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + //---------------------------------------------------------------------------------- + // TODO: Update your variables here + //---------------------------------------------------------------------------------- - // Draw - //---------------------------------------------------------------------------------- - BeginDrawing(); + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); - ClearBackground(RAYWHITE); + ClearBackground(RAYWHITE); - DrawText("Check out the console output to see the custom logger in action!", 60, 200, 20, LIGHTGRAY); + DrawText("Check out the console output to see the custom logger in action!", 60, 200, 20, LIGHTGRAY); - EndDrawing(); - //---------------------------------------------------------------------------------- - } + EndDrawing(); + //---------------------------------------------------------------------------------- + } - // De-Initialization - //-------------------------------------------------------------------------------------- - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- - return 0; + return 0; } diff --git a/examples/core/core_drop_files.c b/examples/core/core_drop_files.c index 5c1501b8..5c3af6ab 100644 --- a/examples/core/core_drop_files.c +++ b/examples/core/core_drop_files.c @@ -13,19 +13,19 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files"); - + int count = 0; char **droppedFiles = { 0 }; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -49,15 +49,15 @@ int main() else { DrawText("Dropped files:", 100, 40, 20, DARKGRAY); - + for (int i = 0; i < count; i++) { if (i%2 == 0) DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.5f)); else DrawRectangle(0, 85 + 40*i, screenWidth, 40, Fade(LIGHTGRAY, 0.3f)); - + DrawText(droppedFiles[i], 120, 100 + 40*i, 10, GRAY); } - + DrawText("Drop new files...", 100, 110 + 40*count, 20, DARKGRAY); } @@ -68,7 +68,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- ClearDroppedFiles(); // Clear internal buffers - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_input_gamepad.c b/examples/core/core_input_gamepad.c index e8a1c051..51646aab 100644 --- a/examples/core/core_input_gamepad.c +++ b/examples/core/core_input_gamepad.c @@ -3,15 +3,15 @@ * raylib [core] example - Gamepad input * * NOTE: This example requires a Gamepad connected to the system -* raylib is configured to work with the following gamepads: +* raylib is configured to work with the following gamepads: * - Xbox 360 Controller (Xbox 360, Xbox One) -* - PLAYSTATION(R)3 Controller +* - PLAYSTATION(R)3 Controller * Check raylib.h for buttons configuration * -* This example has been created using raylib 1.6 (www.raylib.com) +* This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5) * ********************************************************************************************/ @@ -26,21 +26,21 @@ #define PS3_NAME_ID "PLAYSTATION(R)3 Controller" #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; + + SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation - SetConfigFlags(FLAG_MSAA_4X_HINT); // Set MSAA 4X hint before windows creation - InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad input"); - + Texture2D texPs3Pad = LoadTexture("resources/ps3.png"); Texture2D texXboxPad = LoadTexture("resources/xbox.png"); - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -56,7 +56,7 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + if (IsGamepadAvailable(GAMEPAD_PLAYER1)) { DrawText(FormatText("GP1: %s", GetGamepadName(GAMEPAD_PLAYER1)), 10, 10, 10, BLACK); @@ -64,7 +64,7 @@ int main() if (IsGamepadName(GAMEPAD_PLAYER1, XBOX360_NAME_ID)) { DrawTexture(texXboxPad, 0, 0, DARKGRAY); - + // Draw buttons: xbox home if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(394, 89, 19, RED); @@ -75,7 +75,7 @@ int main() if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_DOWN)) DrawCircle(536, 187, 15, LIME); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_RIGHT)) DrawCircle(572, 151, 15, MAROON); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_FACE_UP)) DrawCircle(536, 115, 15, GOLD); - + // Draw buttons: d-pad DrawRectangle(317, 202, 19, 71, BLACK); DrawRectangle(293, 228, 69, 19, BLACK); @@ -83,7 +83,7 @@ int main() if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(317, 202 + 45, 19, 26, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(292, 228, 25, 19, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(292 + 44, 228, 26, 19, RED); - + // Draw buttons: left-right back if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(259, 61, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(536, 61, 20, RED); @@ -91,21 +91,21 @@ int main() // Draw axis: left joystick DrawCircle(259, 152, 39, BLACK); DrawCircle(259, 152, 34, LIGHTGRAY); - DrawCircle(259 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), + DrawCircle(259 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), 152 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK); - + // Draw axis: right joystick DrawCircle(461, 237, 38, BLACK); DrawCircle(461, 237, 33, LIGHTGRAY); - DrawCircle(461 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), + DrawCircle(461 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), 237 - (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK); // Draw axis: left-right triggers DrawRectangle(170, 30, 15, 70, GRAY); - DrawRectangle(604, 30, 15, 70, GRAY); + DrawRectangle(604, 30, 15, 70, GRAY); DrawRectangle(170, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED); DrawRectangle(604, 30, 15, (((1.0f + GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED); - + //DrawText(FormatText("Xbox axis LT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER)), 10, 40, 10, BLACK); //DrawText(FormatText("Xbox axis RT: %02.02f", GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER)), 10, 60, 10, BLACK); } @@ -115,7 +115,7 @@ int main() // Draw buttons: ps if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE)) DrawCircle(396, 222, 13, RED); - + // Draw buttons: basic if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_LEFT)) DrawRectangle(328, 170, 32, 13, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_MIDDLE_RIGHT)) DrawTriangle((Vector2){ 436, 168 }, (Vector2){ 436, 185 }, (Vector2){ 464, 177 }, RED); @@ -131,7 +131,7 @@ int main() if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_DOWN)) DrawRectangle(225, 132 + 54, 24, 30, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_LEFT)) DrawRectangle(195, 161, 30, 25, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_FACE_RIGHT)) DrawRectangle(195 + 54, 161, 30, 25, RED); - + // Draw buttons: left-right back buttons if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_LEFT_TRIGGER_1)) DrawCircle(239, 82, 20, RED); if (IsGamepadButtonDown(GAMEPAD_PLAYER1, GAMEPAD_BUTTON_RIGHT_TRIGGER_1)) DrawCircle(557, 82, 20, RED); @@ -139,42 +139,42 @@ int main() // Draw axis: left joystick DrawCircle(319, 255, 35, BLACK); DrawCircle(319, 255, 31, LIGHTGRAY); - DrawCircle(319 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), + DrawCircle(319 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_X)*20), 255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_Y)*20), 25, BLACK); - + // Draw axis: right joystick DrawCircle(475, 255, 35, BLACK); DrawCircle(475, 255, 31, LIGHTGRAY); - DrawCircle(475 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), + DrawCircle(475 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_X)*20), 255 + (GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_Y)*20), 25, BLACK); // Draw axis: left-right triggers DrawRectangle(169, 48, 15, 70, GRAY); - DrawRectangle(611, 48, 15, 70, GRAY); + DrawRectangle(611, 48, 15, 70, GRAY); DrawRectangle(169, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_LEFT_TRIGGER))/2.0f)*70), RED); DrawRectangle(611, 48, 15, (((1.0f - GetGamepadAxisMovement(GAMEPAD_PLAYER1, GAMEPAD_AXIS_RIGHT_TRIGGER))/2.0f)*70), RED); } else { DrawText("- GENERIC GAMEPAD -", 280, 180, 20, GRAY); - + // TODO: Draw generic gamepad } - - DrawText(FormatText("DETECTED AXIS [%i]:", GetGamepadAxisCount(GAMEPAD_PLAYER1)), 10, 50, 10, MAROON); - + + DrawText(FormatText("DETECTED AXIS [%i]:", GetGamepadAxisCount(GAMEPAD_PLAYER1)), 10, 50, 10, MAROON); + for (int i = 0; i < GetGamepadAxisCount(GAMEPAD_PLAYER1); i++) { DrawText(FormatText("AXIS %i: %.02f", i, GetGamepadAxisMovement(GAMEPAD_PLAYER1, i)), 20, 70 + 20*i, 10, DARKGRAY); } - + if (GetGamepadButtonPressed() != -1) DrawText(FormatText("DETECTED BUTTON: %i", GetGamepadButtonPressed()), 10, 430, 10, RED); else DrawText("DETECTED BUTTON: NONE", 10, 430, 10, GRAY); } else { DrawText("GP1: NOT DETECTED", 10, 10, 10, GRAY); - + DrawTexture(texXboxPad, 0, 0, LIGHTGRAY); } @@ -186,7 +186,7 @@ int main() //-------------------------------------------------------------------------------------- UnloadTexture(texPs3Pad); UnloadTexture(texXboxPad); - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_input_gestures.c b/examples/core/core_input_gestures.c index ce2ed86c..affab3eb 100644 --- a/examples/core/core_input_gestures.c +++ b/examples/core/core_input_gestures.c @@ -14,27 +14,27 @@ #define MAX_GESTURE_STRINGS 20 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - + const int screenWidth = 800; + const int screenHeight = 450; + InitWindow(screenWidth, screenHeight, "raylib [core] example - input gestures"); - + Vector2 touchPosition = { 0, 0 }; Rectangle touchArea = { 220, 10, screenWidth - 230, screenHeight - 20 }; - + int gesturesCount = 0; char gestureStrings[MAX_GESTURE_STRINGS][32]; int currentGesture = GESTURE_NONE; int lastGesture = GESTURE_NONE; - + //SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -65,14 +65,14 @@ int main() case GESTURE_PINCH_OUT: strcpy(gestureStrings[gesturesCount], "GESTURE PINCH OUT"); break; default: break; } - + gesturesCount++; - + // Reset gestures strings if (gesturesCount >= MAX_GESTURE_STRINGS) { for (int i = 0; i < MAX_GESTURE_STRINGS; i++) strcpy(gestureStrings[i], "\0"); - + gesturesCount = 0; } } @@ -84,32 +84,32 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawRectangleRec(touchArea, GRAY); DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, RAYWHITE); - + DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, Fade(GRAY, 0.5f)); - + for (int i = 0; i < gesturesCount; i++) { if (i%2 == 0) DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.5f)); else DrawRectangle(10, 30 + 20*i, 200, 20, Fade(LIGHTGRAY, 0.3f)); - + if (i < gesturesCount - 1) DrawText(gestureStrings[i], 35, 36 + 20*i, 10, DARKGRAY); else DrawText(gestureStrings[i], 35, 36 + 20*i, 10, MAROON); } - + DrawRectangleLines(10, 29, 200, screenHeight - 50, GRAY); DrawText("DETECTED GESTURES", 50, 15, 10, GRAY); - + if (currentGesture != GESTURE_NONE) DrawCircleV(touchPosition, 30, MAROON); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- } \ No newline at end of file diff --git a/examples/core/core_input_keys.c b/examples/core/core_input_keys.c index 69384fd9..bbb71ee3 100644 --- a/examples/core/core_input_keys.c +++ b/examples/core/core_input_keys.c @@ -11,18 +11,18 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input"); Vector2 ballPosition = { (float)screenWidth/2, (float)screenHeight/2 }; - SetTargetFPS(60); // Set target frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/core/core_input_mouse.c b/examples/core/core_input_mouse.c index 24d2dfcd..ad205aed 100644 --- a/examples/core/core_input_mouse.c +++ b/examples/core/core_input_mouse.c @@ -11,19 +11,19 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input"); Vector2 ballPosition = { -100.0f, -100.0f }; Color ballColor = DARKBLUE; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //--------------------------------------------------------------------------------------- // Main game loop @@ -32,7 +32,7 @@ int main() // Update //---------------------------------------------------------------------------------- ballPosition = GetMousePosition(); - + if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON; else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME; else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE; diff --git a/examples/core/core_input_mouse_wheel.c b/examples/core/core_input_mouse_wheel.c index 48cf7042..7c3e2a16 100644 --- a/examples/core/core_input_mouse_wheel.c +++ b/examples/core/core_input_mouse_wheel.c @@ -11,19 +11,19 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel"); int boxPositionY = screenHeight/2 - 40; int scrollSpeed = 4; // Scrolling speed in pixels - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/core/core_input_multitouch.c b/examples/core/core_input_multitouch.c index 5baab271..5fbb086c 100644 --- a/examples/core/core_input_multitouch.c +++ b/examples/core/core_input_multitouch.c @@ -13,31 +13,31 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch"); Vector2 ballPosition = { -100.0f, -100.0f }; Color ballColor = BEIGE; - + int touchCounter = 0; - Vector2 touchPosition; + Vector2 touchPosition = { 0.0f }; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //--------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- ballPosition = GetMousePosition(); - + ballColor = BEIGE; if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) ballColor = MAROON; @@ -47,7 +47,7 @@ int main() if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) touchCounter = 10; - + if (touchCounter > 0) touchCounter--; //---------------------------------------------------------------------------------- @@ -59,15 +59,15 @@ int main() // Multitouch for (int i = 0; i < MAX_TOUCH_POINTS; ++i) - { + { touchPosition = GetTouchPosition(i); // Get the touch point - + if ((touchPosition.x >= 0) && (touchPosition.y >= 0)) // Make sure point is not (-1,-1) as this means there is no touch for it { // Draw circle and touch index number DrawCircleV(touchPosition, 34, ORANGE); DrawText(FormatText("%d", i), touchPosition.x - 10, touchPosition.y - 70, 40, BLACK); - } + } } // Draw the normal mouse location diff --git a/examples/core/core_loading_thread.c b/examples/core/core_loading_thread.c index 1dacd69f..773ad2ea 100644 --- a/examples/core/core_loading_thread.c +++ b/examples/core/core_loading_thread.c @@ -2,7 +2,7 @@ * * raylib example - loading thread * -* NOTE: This example requires linking with pthreads library, +* NOTE: This example requires linking with pthreads library, * on MinGW, it can be accomplished passing -static parameter to compiler * * This example has been created using raylib 2.5 (www.raylib.com) @@ -27,21 +27,21 @@ static void *LoadDataThread(void *arg); // Loading data thread function decl static int dataProgress = 0; // Data progress accumulator -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread"); - + pthread_t threadId; // Loading data thread id enum { STATE_WAITING, STATE_LOADING, STATE_FINISHED } state = STATE_WAITING; int framesCounter = 0; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -90,25 +90,25 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - - switch (state) + + switch (state) { case STATE_WAITING: DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY); break; case STATE_LOADING: { DrawRectangle(150, 200, dataProgress, 60, SKYBLUE); if ((framesCounter/15)%2) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE); - + } break; case STATE_FINISHED: { DrawRectangle(150, 200, 500, 60, LIME); DrawText("DATA LOADED!", 250, 210, 40, GREEN); - + } break; default: break; } - + DrawRectangleLines(150, 200, 500, 60, DARKGRAY); EndDrawing(); @@ -130,11 +130,11 @@ static void *LoadDataThread(void *arg) clock_t prevTime = clock(); // Previous time // We simulate data loading with a time counter for 5 seconds - while (timeCounter < 5000) + while (timeCounter < 5000) { clock_t currentTime = clock() - prevTime; timeCounter = currentTime*1000/CLOCKS_PER_SEC; - + // We accumulate time over a global variable to be used in // main thread as a progress bar dataProgress = timeCounter/10; diff --git a/examples/core/core_random_values.c b/examples/core/core_random_values.c index 06e550dd..52dabe0a 100644 --- a/examples/core/core_random_values.c +++ b/examples/core/core_random_values.c @@ -11,20 +11,20 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values"); - int framesCounter = 0; // Variable used to count frames + int framesCounter = 0; // Variable used to count frames int randValue = GetRandomValue(-8, 5); // Get a random integer number between -8 and 5 (both included) - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/core/core_storage_values.c b/examples/core/core_storage_values.c index 43f0882f..fbbbc528 100644 --- a/examples/core/core_storage_values.c +++ b/examples/core/core_storage_values.c @@ -14,21 +14,20 @@ // NOTE: Storage positions must start with 0, directly related to file memory layout typedef enum { STORAGE_SCORE = 0, STORAGE_HISCORE } StorageData; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values"); - + int score = 0; int hiscore = 0; - int framesCounter = 0; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -41,7 +40,7 @@ int main() score = GetRandomValue(1000, 2000); hiscore = GetRandomValue(2000, 4000); } - + if (IsKeyPressed(KEY_ENTER)) { StorageSaveValue(STORAGE_SCORE, score); @@ -53,7 +52,7 @@ int main() score = StorageLoadValue(STORAGE_SCORE); hiscore = StorageLoadValue(STORAGE_HISCORE); } - + framesCounter++; //---------------------------------------------------------------------------------- @@ -65,9 +64,9 @@ int main() DrawText(FormatText("SCORE: %i", score), 280, 130, 40, MAROON); DrawText(FormatText("HI-SCORE: %i", hiscore), 210, 200, 50, BLACK); - + DrawText(FormatText("frames: %i", framesCounter), 10, 10, 20, LIME); - + DrawText("Press R to generate random numbers", 220, 40, 20, LIGHTGRAY); DrawText("Press ENTER to SAVE values", 250, 310, 20, LIGHTGRAY); DrawText("Press SPACE to LOAD values", 252, 350, 20, LIGHTGRAY); @@ -77,7 +76,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/core/core_vr_simulator.c b/examples/core/core_vr_simulator.c index b79ed90e..134a36f0 100644 --- a/examples/core/core_vr_simulator.c +++ b/examples/core/core_vr_simulator.c @@ -17,22 +17,22 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 1080; - int screenHeight = 600; - + const int screenWidth = 1080; + const int screenHeight = 600; + // NOTE: screenWidth/screenHeight should match VR device aspect ratio - + InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator"); // Init VR simulator (Oculus Rift CV1 parameters) InitVrSimulator(); VrDeviceInfo hmd = { 0 }; // VR device parameters (head-mounted-device) - + // Oculus Rift CV1 parameters for simulator hmd.hResolution = 2160; // HMD horizontal resolution in pixels hmd.vResolution = 1200; // HMD vertical resolution in pixels @@ -42,7 +42,7 @@ int main() hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters hmd.lensSeparationDistance = 0.07f; // HMD lens separation distance in meters hmd.interpupillaryDistance = 0.07f; // HMD IPD (distance between pupils) in meters - + // NOTE: CV1 uses a Fresnel-hybrid-asymmetric lenses with specific distortion compute shaders. // Following parameters are an approximation to distortion stereo rendering but results differ from actual device. hmd.lensDistortionValues[0] = 1.0f; // HMD lens distortion constant parameter 0 @@ -53,12 +53,12 @@ int main() hmd.chromaAbCorrection[1] = -0.004f; // HMD chromatic aberration correction parameter 1 hmd.chromaAbCorrection[2] = 1.014f; // HMD chromatic aberration correction parameter 2 hmd.chromaAbCorrection[3] = 0.0f; // HMD chromatic aberration correction parameter 3 - + // Distortion shader (uses device lens distortion and chroma) Shader distortion = LoadShader(0, FormatText("resources/distortion%i.fs", GLSL_VERSION)); - + SetVrConfiguration(hmd, distortion); // Set Vr device parameters for stereo rendering - + // Define the camera to look into our 3d world Camera camera; camera.position = (Vector3){ 5.0f, 2.0f, 5.0f }; // Camera position @@ -66,11 +66,11 @@ int main() camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.fovy = 60.0f; // Camera field-of-view Y camera.type = CAMERA_PERSPECTIVE; // Camera type - + Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - + SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set first person camera mode - + SetTargetFPS(90); // Set our game to run at 90 frames-per-second //-------------------------------------------------------------------------------------- @@ -89,7 +89,7 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + BeginVrDrawing(); BeginMode3D(camera); @@ -100,7 +100,7 @@ int main() DrawGrid(40, 1.0f); EndMode3D(); - + EndVrDrawing(); DrawFPS(10, 10); diff --git a/examples/core/core_window_letterbox.c b/examples/core/core_window_letterbox.c index 8c0843d2..f90214cf 100644 --- a/examples/core/core_window_letterbox.c +++ b/examples/core/core_window_letterbox.c @@ -16,7 +16,7 @@ #define max(a, b) ((a)>(b)? (a) : (b)) #define min(a, b) ((a)<(b)? (a) : (b)) -int main() +int main(void) { const int windowWidth = 800; const int windowHeight = 450; @@ -28,63 +28,63 @@ int main() int gameScreenWidth = 640; int gameScreenHeight = 480; - + // Render texture initialization RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight); SetTextureFilter(target.texture, FILTER_BILINEAR); // Texture scale filter to use - + Color colors[10] = { 0 }; for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- - + // Main game loop - while( !WindowShouldClose() ) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- // Compute required framebuffer scaling float scale = min((float)GetScreenWidth()/gameScreenWidth, (float)GetScreenHeight()/gameScreenHeight); - - if (IsKeyPressed(KEY_SPACE)) + + if (IsKeyPressed(KEY_SPACE)) { // Recalculate random colors for the bars for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; } //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); ClearBackground(BLACK); - + // Draw everything in the render texture BeginTextureMode(target); - + ClearBackground(RAYWHITE); // Clear render texture background color - + for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]); - + DrawText("You can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE); - + EndTextureMode(); // Draw RenderTexture2D to window, properly scaled DrawTexturePro(target.texture, (Rectangle){ 0.0f, 0.0f, (float)target.texture.width, (float)-target.texture.height }, - (Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5, + (Rectangle){ (GetScreenWidth() - ((float)gameScreenWidth*scale))*0.5, (GetScreenHeight() - ((float)gameScreenHeight*scale))*0.5, (float)gameScreenWidth*scale, (float)gameScreenHeight*scale }, (Vector2){ 0, 0 }, 0.0f, WHITE); - + EndDrawing(); //-------------------------------------------------------------------------------------- } - + // De-Initialization //-------------------------------------------------------------------------------------- UnloadRenderTexture(target); // Unload render texture - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } diff --git a/examples/core/core_world_screen.c b/examples/core/core_world_screen.c index 460f6b85..434952bc 100644 --- a/examples/core/core_world_screen.c +++ b/examples/core/core_world_screen.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free"); @@ -29,9 +29,9 @@ int main() camera.type = CAMERA_PERSPECTIVE; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - + Vector2 cubeScreenPosition; - + SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -43,7 +43,7 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update camera - + // Calculate cube screen space position (with a little offset to be in top) cubeScreenPosition = GetWorldToScreen((Vector3){cubePosition.x, cubePosition.y + 2.5f, cubePosition.z}, camera); //---------------------------------------------------------------------------------- @@ -62,7 +62,7 @@ int main() DrawGrid(10, 1.0f); EndMode3D(); - + DrawText("Enemy: 100 / 100", cubeScreenPosition.x - MeasureText("Enemy: 100 / 100", 20) / 2, cubeScreenPosition.y, 20, BLACK); DrawText("Text is always on top of the cube", (screenWidth - MeasureText("Text is always on top of the cube", 20)) / 2, 25, 20, GRAY); diff --git a/examples/models/models_animation.c b/examples/models/models_animation.c index a75241b3..294b07a5 100644 --- a/examples/models/models_animation.c +++ b/examples/models/models_animation.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation"); @@ -32,7 +32,7 @@ int main() Model model = LoadModel("resources/guy/guy.iqm"); // Load the animated model mesh and basic data Texture2D texture = LoadTexture("resources/guy/guytex.png"); // Load model texture and set material SetMaterialTexture(&model.materials[0], MAP_DIFFUSE, texture); // Set model material map texture - + Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position // Load animation data @@ -91,7 +91,7 @@ int main() //-------------------------------------------------------------------------------------- // Unload model animations data for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); - + UnloadModel(model); // Unload model CloseWindow(); // Close window and OpenGL context diff --git a/examples/models/models_billboard.c b/examples/models/models_billboard.c index 59655714..597e9a60 100644 --- a/examples/models/models_billboard.c +++ b/examples/models/models_billboard.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - drawing billboards"); @@ -27,10 +27,10 @@ int main() camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.fovy = 45.0f; camera.type = CAMERA_PERSPECTIVE; - + Texture2D bill = LoadTexture("resources/billboard.png"); // Our texture billboard Vector3 billPosition = { 0.0f, 2.0f, 0.0f }; // Position where draw billboard - + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -51,11 +51,11 @@ int main() ClearBackground(RAYWHITE); BeginMode3D(camera); - + DrawGrid(10, 1.0f); // Draw a grid - + DrawBillboard(camera, bill, billPosition, 2.0f, WHITE); - + EndMode3D(); DrawFPS(10, 10); diff --git a/examples/models/models_box_collisions.c b/examples/models/models_box_collisions.c index 41f6056c..0dd0710e 100644 --- a/examples/models/models_box_collisions.c +++ b/examples/models/models_box_collisions.c @@ -11,31 +11,31 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions"); // Define the camera to look into our 3d world Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; - + Vector3 playerPosition = { 0.0f, 1.0f, 2.0f }; Vector3 playerSize = { 1.0f, 2.0f, 1.0f }; Color playerColor = GREEN; - + Vector3 enemyBoxPos = { -4.0f, 1.0f, 0.0f }; Vector3 enemyBoxSize = { 2.0f, 2.0f, 2.0f }; - + Vector3 enemySpherePos = { 4.0f, 0.0f, 0.0f }; float enemySphereSize = 1.5f; - + bool collision = false; - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -43,40 +43,40 @@ int main() { // Update //---------------------------------------------------------------------------------- - + // Move player if (IsKeyDown(KEY_RIGHT)) playerPosition.x += 0.2f; else if (IsKeyDown(KEY_LEFT)) playerPosition.x -= 0.2f; else if (IsKeyDown(KEY_DOWN)) playerPosition.z += 0.2f; else if (IsKeyDown(KEY_UP)) playerPosition.z -= 0.2f; - + collision = false; - + // Check collisions player vs enemy-box if (CheckCollisionBoxes( - (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, - playerPosition.y - playerSize.y/2, - playerPosition.z - playerSize.z/2 }, + (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, + playerPosition.y - playerSize.y/2, + playerPosition.z - playerSize.z/2 }, (Vector3){ playerPosition.x + playerSize.x/2, - playerPosition.y + playerSize.y/2, + playerPosition.y + playerSize.y/2, playerPosition.z + playerSize.z/2 }}, - (BoundingBox){(Vector3){ enemyBoxPos.x - enemyBoxSize.x/2, - enemyBoxPos.y - enemyBoxSize.y/2, - enemyBoxPos.z - enemyBoxSize.z/2 }, + (BoundingBox){(Vector3){ enemyBoxPos.x - enemyBoxSize.x/2, + enemyBoxPos.y - enemyBoxSize.y/2, + enemyBoxPos.z - enemyBoxSize.z/2 }, (Vector3){ enemyBoxPos.x + enemyBoxSize.x/2, - enemyBoxPos.y + enemyBoxSize.y/2, + enemyBoxPos.y + enemyBoxSize.y/2, enemyBoxPos.z + enemyBoxSize.z/2 }})) collision = true; - + // Check collisions player vs enemy-sphere if (CheckCollisionBoxSphere( - (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, - playerPosition.y - playerSize.y/2, - playerPosition.z - playerSize.z/2 }, + (BoundingBox){(Vector3){ playerPosition.x - playerSize.x/2, + playerPosition.y - playerSize.y/2, + playerPosition.z - playerSize.z/2 }, (Vector3){ playerPosition.x + playerSize.x/2, - playerPosition.y + playerSize.y/2, - playerPosition.z + playerSize.z/2 }}, + playerPosition.y + playerSize.y/2, + playerPosition.z + playerSize.z/2 }}, enemySpherePos, enemySphereSize)) collision = true; - + if (collision) playerColor = RED; else playerColor = GREEN; //---------------------------------------------------------------------------------- @@ -92,18 +92,18 @@ int main() // Draw enemy-box DrawCube(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, GRAY); DrawCubeWires(enemyBoxPos, enemyBoxSize.x, enemyBoxSize.y, enemyBoxSize.z, DARKGRAY); - + // Draw enemy-sphere DrawSphere(enemySpherePos, enemySphereSize, GRAY); DrawSphereWires(enemySpherePos, enemySphereSize, 16, 16, DARKGRAY); - + // Draw player DrawCubeV(playerPosition, playerSize, playerColor); DrawGrid(10, 1.0f); // Draw a grid EndMode3D(); - + DrawText("Move player with cursors to collide", 220, 40, 20, GRAY); DrawFPS(10, 10); diff --git a/examples/models/models_cubicmap.c b/examples/models/models_cubicmap.c index ac24188e..f399a56e 100644 --- a/examples/models/models_cubicmap.c +++ b/examples/models/models_cubicmap.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing"); @@ -25,18 +25,18 @@ int main() Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM) - + Mesh mesh = GenMeshCubicmap(image, (Vector3){ 1.0f, 1.0f, 1.0f }); Model model = LoadModelFromMesh(mesh); - + // NOTE: By default each cube is mapped to one part of texture atlas Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture - + Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position UnloadImage(image); // Unload cubesmap image from RAM, already uploaded to VRAM - + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -61,10 +61,10 @@ int main() DrawModel(model, mapPosition, 1.0f, WHITE); EndMode3D(); - + DrawTextureEx(cubicmap, (Vector2){ screenWidth - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); DrawRectangleLines(screenWidth - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); - + DrawText("cubicmap image used to", 658, 90, 10, GRAY); DrawText("generate map 3d model", 658, 104, 10, GRAY); diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index 093334ba..42363747 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -13,12 +13,12 @@ #include // Required for: free() -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze"); @@ -29,18 +29,18 @@ int main() Texture2D cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM) Mesh mesh = GenMeshCubicmap(imMap, (Vector3){ 1.0f, 1.0f, 1.0f }); Model model = LoadModelFromMesh(mesh); - + // NOTE: By default each cube is mapped to one part of texture atlas Texture2D texture = LoadTexture("resources/cubicmap_atlas.png"); // Load map texture model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture - + // Get map image data to be used for collision detection Color *mapPixels = GetImageData(imMap); UnloadImage(imMap); // Unload image from RAM - + Vector3 mapPosition = { -16.0f, 0.0f, -8.0f }; // Set model position Vector3 playerPosition = camera.position; // Set player position - + SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -52,23 +52,23 @@ int main() // Update //---------------------------------------------------------------------------------- Vector3 oldCamPos = camera.position; // Store old camera position - + UpdateCamera(&camera); // Update camera - + // Check player collision (we simplify to 2D collision detection) Vector2 playerPos = { camera.position.x, camera.position.z }; float playerRadius = 0.1f; // Collision radius (player is modelled as a cilinder for collision) - + int playerCellX = (int)(playerPos.x - mapPosition.x + 0.5f); int playerCellY = (int)(playerPos.y - mapPosition.z + 0.5f); - + // Out-of-limits security check if (playerCellX < 0) playerCellX = 0; else if (playerCellX >= cubicmap.width) playerCellX = cubicmap.width - 1; - + if (playerCellY < 0) playerCellY = 0; else if (playerCellY >= cubicmap.height) playerCellY = cubicmap.height - 1; - + // Check map collisions using image data and player position // TODO: Improvement: Just check player surrounding cells for collision for (int y = 0; y < cubicmap.height; y++) @@ -76,7 +76,7 @@ int main() for (int x = 0; x < cubicmap.width; x++) { if ((mapPixels[y*cubicmap.width + x].r == 255) && // Collision: white pixel, only check R channel - (CheckCollisionCircleRec(playerPos, playerRadius, + (CheckCollisionCircleRec(playerPos, playerRadius, (Rectangle){ mapPosition.x - 0.5f + x*1.0f, mapPosition.z - 0.5f + y*1.0f, 1.0f, 1.0f }))) { // Collision detected, reset camera position @@ -98,10 +98,10 @@ int main() //DrawCubeV(playerPosition, (Vector3){ 0.2f, 0.4f, 0.2f }, RED); // Draw player EndMode3D(); - + DrawTextureEx(cubicmap, (Vector2){ GetScreenWidth() - cubicmap.width*4 - 20, 20 }, 0.0f, 4.0f, WHITE); DrawRectangleLines(GetScreenWidth() - cubicmap.width*4 - 20, 20, cubicmap.width*4, cubicmap.height*4, GREEN); - + // Draw player position radar DrawRectangle(GetScreenWidth() - cubicmap.width*4 - 20 + playerCellX*4, 20 + playerCellY*4, 4, 4, RED); @@ -114,7 +114,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- free(mapPixels); // Unload color array - + UnloadTexture(cubicmap); // Unload cubicmap texture UnloadTexture(texture); // Unload map texture UnloadModel(model); // Unload map model diff --git a/examples/models/models_geometric_shapes.c b/examples/models/models_geometric_shapes.c index 82ca4c60..39477927 100644 --- a/examples/models/models_geometric_shapes.c +++ b/examples/models/models_geometric_shapes.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes"); @@ -28,7 +28,7 @@ int main() camera.fovy = 45.0f; camera.type = CAMERA_PERSPECTIVE; - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/models/models_heightmap.c b/examples/models/models_heightmap.c index e0475f18..e242db16 100644 --- a/examples/models/models_heightmap.c +++ b/examples/models/models_heightmap.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing"); @@ -25,7 +25,7 @@ int main() Image image = LoadImage("resources/heightmap.png"); // Load heightmap image (RAM) Texture2D texture = LoadTextureFromImage(image); // Convert image to texture (VRAM) - + Mesh mesh = GenMeshHeightmap(image, (Vector3){ 16, 8, 16 }); // Generate heightmap mesh (RAM and VRAM) Model model = LoadModelFromMesh(mesh); // Load model from generated mesh @@ -33,7 +33,7 @@ int main() Vector3 mapPosition = { -8.0f, 0.0f, -8.0f }; // Define model position UnloadImage(image); // Unload heightmap image from RAM, already uploaded to VRAM - + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -60,7 +60,7 @@ int main() DrawGrid(20, 1.0f); EndMode3D(); - + DrawTexture(texture, screenWidth - texture.width - 20, 20, WHITE); DrawRectangleLines(screenWidth - texture.width - 20, 20, texture.width, texture.height, GREEN); diff --git a/examples/models/models_material_pbr.c b/examples/models/models_material_pbr.c index af2fc5b9..8d51eefd 100644 --- a/examples/models/models_material_pbr.c +++ b/examples/models/models_material_pbr.c @@ -25,12 +25,12 @@ // PBR material loading static Material LoadMaterialPBR(Color albedo, float metalness, float roughness); -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) InitWindow(screenWidth, screenHeight, "raylib [models] example - pbr material"); @@ -45,7 +45,7 @@ int main() // Load model and PBR material Model model = LoadModel("resources/pbr/trooper.obj"); - + // Mesh tangents are generated... and uploaded to GPU // NOTE: New VBO for tangents is generated at default location and also binded to mesh VAO MeshTangents(&model.meshes[0]); @@ -54,13 +54,13 @@ int main() // Define lights attributes // NOTE: Shader is passed to every light on creation to define shader bindings internally - Light lights[MAX_LIGHTS] = { + Light lights[MAX_LIGHTS] = { CreateLight(LIGHT_POINT, (Vector3){ LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 0, 255 }, model.materials[0].shader), CreateLight(LIGHT_POINT, (Vector3){ 0.0f, LIGHT_HEIGHT, LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 255, 0, 255 }, model.materials[0].shader), CreateLight(LIGHT_POINT, (Vector3){ -LIGHT_DISTANCE, LIGHT_HEIGHT, 0.0f }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 0, 0, 255, 255 }, model.materials[0].shader), - CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.materials[0].shader) + CreateLight(LIGHT_DIRECTIONAL, (Vector3){ 0.0f, LIGHT_HEIGHT*2.0f, -LIGHT_DISTANCE }, (Vector3){ 0.0f, 0.0f, 0.0f }, (Color){ 255, 0, 255, 255 }, model.materials[0].shader) }; - + SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -72,7 +72,7 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update camera - + // Send to material PBR shader camera view position float cameraPos[3] = { camera.position.x, camera.position.y, camera.position.z }; SetShaderValue(model.materials[0].shader, model.materials[0].shader.locs[LOC_VECTOR_VIEW], cameraPos, UNIFORM_VEC3); @@ -87,7 +87,7 @@ int main() BeginMode3D(camera); DrawModel(model, Vector3Zero(), 1.0f, WHITE); - + DrawGrid(10, 1.0f); EndMode3D(); @@ -137,7 +137,7 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) mat.shader.locs[LOC_MATRIX_MODEL] = GetShaderLocation(mat.shader, "matModel"); mat.shader.locs[LOC_MATRIX_VIEW] = GetShaderLocation(mat.shader, "view"); mat.shader.locs[LOC_VECTOR_VIEW] = GetShaderLocation(mat.shader, "viewPos"); - + // Set PBR standard maps mat.maps[MAP_ALBEDO].texture = LoadTexture("resources/pbr/trooper_albedo.png"); mat.maps[MAP_NORMAL].texture = LoadTexture("resources/pbr/trooper_normals.png"); @@ -185,27 +185,27 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness) mat.maps[MAP_BRDF].texture = GenTextureBRDF(shdrBRDF, BRDF_SIZE); UnloadTexture(cubemap); UnloadTexture(texHDR); - + // Unload already used shaders (to create specific textures) UnloadShader(shdrCubemap); UnloadShader(shdrIrradiance); UnloadShader(shdrPrefilter); UnloadShader(shdrBRDF); - + // Set textures filtering for better quality SetTextureFilter(mat.maps[MAP_ALBEDO].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_NORMAL].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_METALNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_ROUGHNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MAP_OCCLUSION].texture, FILTER_BILINEAR); - + // Enable sample usage in shader for assigned textures SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "albedo.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "normals.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "metalness.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "roughness.useSampler"), (int[1]){ 1 }, UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "occlusion.useSampler"), (int[1]){ 1 }, UNIFORM_INT); - + int renderModeLoc = GetShaderLocation(mat.shader, "renderMode"); SetShaderValue(mat.shader, renderModeLoc, (int[1]){ 0 }, UNIFORM_INT); diff --git a/examples/models/models_mesh_generation.c b/examples/models/models_mesh_generation.c index 2b4b75ab..cfc3bdd6 100644 --- a/examples/models/models_mesh_generation.c +++ b/examples/models/models_mesh_generation.c @@ -11,24 +11,24 @@ #include "raylib.h" -#define NUM_MODELS 8 // We generate 8 parametric 3d shapes +#define NUM_MODELS 8 // Parametric 3d shapes to generate -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation"); - + // We generate a checked image for texturing Image checked = GenImageChecked(2, 2, 1, 1, RED, GREEN); Texture2D texture = LoadTextureFromImage(checked); UnloadImage(checked); - + Model models[NUM_MODELS]; - + models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5)); models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f)); models[2] = LoadModelFromMesh(GenMeshSphere(2, 32, 32)); @@ -37,7 +37,7 @@ int main() models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32)); models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128)); models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f)); - + // Set checked texture as default diffuse component for all models material for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MAP_DIFFUSE].texture = texture; @@ -46,12 +46,12 @@ int main() // Model drawing position Vector3 position = { 0.0f, 0.0f, 0.0f }; - + int currentModel = 0; - + SetCameraMode(camera, CAMERA_ORBITAL); // Set a orbital camera mode - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -60,14 +60,14 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update internal camera and our camera - + if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) { currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures } - + if (IsKeyPressed(KEY_RIGHT)) - { + { currentModel++; if (currentModel >= NUM_MODELS) currentModel = 0; } @@ -91,11 +91,11 @@ int main() DrawGrid(10, 1.0); EndMode3D(); - + DrawRectangle(30, 400, 310, 30, Fade(SKYBLUE, 0.5f)); DrawRectangleLines(30, 400, 310, 30, Fade(DARKBLUE, 0.5f)); DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS", 40, 410, 10, BLUE); - + switch(currentModel) { case 0: DrawText("PLANE", 680, 10, 20, DARKBLUE); break; @@ -115,10 +115,10 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - + // Unload models data (GPU VRAM) for (int i = 0; i < NUM_MODELS; i++) UnloadModel(models[i]); - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/models/models_mesh_picking.c b/examples/models/models_mesh_picking.c index 42028829..26d9fa7e 100644 --- a/examples/models/models_mesh_picking.c +++ b/examples/models/models_mesh_picking.c @@ -15,12 +15,12 @@ #define FLT_MAX 340282346638528859811704183484516925440.0f // Maximum value of a float, from bit pattern 01111111011111111111111111111111 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking"); @@ -33,22 +33,22 @@ int main() camera.type = CAMERA_PERSPECTIVE; // Camera mode type Ray ray = { 0 }; // Picking ray - + Model tower = LoadModel("resources/models/turret.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load model texture tower.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture - + Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position BoundingBox towerBBox = MeshBoundingBox(tower.meshes[0]); // Get mesh bounding box bool hitMeshBBox = false; bool hitTriangle = false; // Test triangle - Vector3 ta = (Vector3){ -25.0, 0.5, 0.0 }; + Vector3 ta = (Vector3){ -25.0, 0.5, 0.0 }; Vector3 tb = (Vector3){ -4.0, 2.5, 1.0 }; Vector3 tc = (Vector3){ -8.0, 6.5, 0.0 }; - Vector3 bary = { 0.0f, 0.0f, 0.0f }; + Vector3 bary = { 0.0f, 0.0f, 0.0f }; SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode @@ -60,7 +60,7 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update camera - + // Display information about closest hit RayHitInfo nearestHit = { 0 }; char *hitObjectName = "None"; @@ -70,10 +70,10 @@ int main() // Get ray and test against ground, triangle, and mesh ray = GetMouseRay(GetMousePosition(), camera); - + // Check ray collision aginst ground plane RayHitInfo groundHitInfo = GetCollisionRayGround(ray, 0.0f); - + if ((groundHitInfo.hit) && (groundHitInfo.distance < nearestHit.distance)) { nearestHit = groundHitInfo; @@ -83,8 +83,8 @@ int main() // Check ray collision against test triangle RayHitInfo triHitInfo = GetCollisionRayTriangle(ray, ta, tb, tc); - - if ((triHitInfo.hit) && (triHitInfo.distance < nearestHit.distance)) + + if ((triHitInfo.hit) && (triHitInfo.distance < nearestHit.distance)) { nearestHit = triHitInfo; cursorColor = PURPLE; @@ -92,32 +92,31 @@ int main() bary = Vector3Barycenter(nearestHit.position, ta, tb, tc); hitTriangle = true; - } + } else hitTriangle = false; RayHitInfo meshHitInfo = { 0 }; // Check ray collision against bounding box first, before trying the full ray-mesh test - if (CheckCollisionRayBox(ray, towerBBox)) + if (CheckCollisionRayBox(ray, towerBBox)) { hitMeshBBox = true; - + // Check ray collision against model // NOTE: It considers model.transform matrix! - meshHitInfo = GetCollisionRayModel(ray, &tower); - - if ((meshHitInfo.hit) && (meshHitInfo.distance < nearestHit.distance)) + meshHitInfo = GetCollisionRayModel(ray, &tower); + + if ((meshHitInfo.hit) && (meshHitInfo.distance < nearestHit.distance)) { nearestHit = meshHitInfo; cursorColor = ORANGE; hitObjectName = "Mesh"; } - - } - - hitMeshBBox = false; + } + + hitMeshBBox = false; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); @@ -127,10 +126,10 @@ int main() BeginMode3D(camera); // Draw the tower - // WARNING: If scale is different than 1.0f, + // WARNING: If scale is different than 1.0f, // not considered by GetCollisionRayModel() DrawModel(tower, towerPos, 1.0f, WHITE); - + // Draw the test triangle DrawLine3D(ta, tb, PURPLE); DrawLine3D(tb, tc, PURPLE); @@ -140,7 +139,7 @@ int main() if (hitMeshBBox) DrawBoundingBox(towerBBox, LIME); // If we hit something, draw the cursor at the hit point - if (nearestHit.hit) + if (nearestHit.hit) { DrawCube(nearestHit.position, 0.3, 0.3, 0.3, cursorColor); DrawCubeWires(nearestHit.position, 0.3, 0.3, 0.3, RED); @@ -149,40 +148,40 @@ int main() normalEnd.x = nearestHit.position.x + nearestHit.normal.x; normalEnd.y = nearestHit.position.y + nearestHit.normal.y; normalEnd.z = nearestHit.position.z + nearestHit.normal.z; - + DrawLine3D(nearestHit.position, normalEnd, RED); } DrawRay(ray, MAROON); - + DrawGrid(10, 10.0f); EndMode3D(); - + // Draw some debug GUI text DrawText(FormatText("Hit Object: %s", hitObjectName), 10, 50, 10, BLACK); - if (nearestHit.hit) + if (nearestHit.hit) { int ypos = 70; DrawText(FormatText("Distance: %3.2f", nearestHit.distance), 10, ypos, 10, BLACK); - - DrawText(FormatText("Hit Pos: %3.2f %3.2f %3.2f", - nearestHit.position.x, - nearestHit.position.y, + + DrawText(FormatText("Hit Pos: %3.2f %3.2f %3.2f", + nearestHit.position.x, + nearestHit.position.y, nearestHit.position.z), 10, ypos + 15, 10, BLACK); - - DrawText(FormatText("Hit Norm: %3.2f %3.2f %3.2f", - nearestHit.normal.x, - nearestHit.normal.y, + + DrawText(FormatText("Hit Norm: %3.2f %3.2f %3.2f", + nearestHit.normal.x, + nearestHit.normal.y, nearestHit.normal.z), 10, ypos + 30, 10, BLACK); if (hitTriangle) DrawText(FormatText("Barycenter: %3.2f %3.2f %3.2f", bary.x, bary.y, bary.z), 10, ypos + 45, 10, BLACK); } DrawText("Use Mouse to Move Camera", 10, 430, 10, GRAY); - + DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); DrawFPS(10, 10); @@ -195,7 +194,7 @@ int main() //-------------------------------------------------------------------------------------- UnloadModel(tower); // Unload model UnloadTexture(texture); // Unload texture - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/models/models_obj_loading.c b/examples/models/models_obj_loading.c index 74e7d08a..51578bc1 100644 --- a/examples/models/models_obj_loading.c +++ b/examples/models/models_obj_loading.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - obj model loading"); @@ -33,7 +33,7 @@ int main() model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set map diffuse texture Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/models/models_obj_viewer.c b/examples/models/models_obj_viewer.c index 7d387441..dc6787e7 100644 --- a/examples/models/models_obj_viewer.c +++ b/examples/models/models_obj_viewer.c @@ -13,12 +13,12 @@ #include // Required for: strcpy() -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib example - obj viewer"); @@ -37,7 +37,7 @@ int main() char objFilename[64] = "turret.obj"; - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/models/models_orthographic_projection.c b/examples/models/models_orthographic_projection.c index 3ad32b60..ca9d83c9 100644 --- a/examples/models/models_orthographic_projection.c +++ b/examples/models/models_orthographic_projection.c @@ -1,6 +1,6 @@ /******************************************************************************************* * -* raylib [models] example - Show the difference between perspective and orthographic projection +* raylib [models] example - Show the difference between perspective and orthographic projection * * This program is heavily based on the geometric objects example * @@ -18,19 +18,19 @@ #define FOVY_PERSPECTIVE 45.0f #define WIDTH_ORTHOGRAPHIC 10.0f -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes"); // Define the camera to look into our 3d world Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE }; - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -38,14 +38,14 @@ int main() { // Update //---------------------------------------------------------------------------------- - if (IsKeyPressed(KEY_SPACE)) + if (IsKeyPressed(KEY_SPACE)) { - if (camera.type == CAMERA_PERSPECTIVE) + if (camera.type == CAMERA_PERSPECTIVE) { camera.fovy = WIDTH_ORTHOGRAPHIC; camera.type = CAMERA_ORTHOGRAPHIC; - } - else + } + else { camera.fovy = FOVY_PERSPECTIVE; camera.type = CAMERA_PERSPECTIVE; diff --git a/examples/models/models_rlgl_solar_system.c b/examples/models/models_rlgl_solar_system.c index 7193d6f8..cb9289ad 100644 --- a/examples/models/models_rlgl_solar_system.c +++ b/examples/models/models_rlgl_solar_system.c @@ -22,13 +22,13 @@ void DrawSphereBasic(Color color); // Draw sphere without any matrix transf //------------------------------------------------------------------------------------ // Program main entry point //------------------------------------------------------------------------------------ -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; - + const float sunRadius = 4.0f; const float earthRadius = 0.6f; const float earthOrbitRadius = 8.0f; @@ -44,26 +44,26 @@ int main() camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; camera.fovy = 45.0f; camera.type = CAMERA_PERSPECTIVE; - + SetCameraMode(camera, CAMERA_FREE); - + float rotationSpeed = 0.2f; // General system rotation speed - + float earthRotation = 0.0f; // Rotation of earth around itself (days) in degrees float earthOrbitRotation = 0.0f; // Rotation of earth around the Sun (years) in degrees float moonRotation = 0.0f; // Rotation of moon around itself float moonOrbitRotation = 0.0f; // Rotation of moon around earth in degrees - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); - + earthRotation += (5.0f*rotationSpeed); earthOrbitRotation += (365/360.0f*(5.0f*rotationSpeed)*rotationSpeed); moonRotation += (2.0f*rotationSpeed); @@ -77,12 +77,12 @@ int main() ClearBackground(RAYWHITE); BeginMode3D(camera); - + rlPushMatrix(); rlScalef(sunRadius, sunRadius, sunRadius); // Scale Sun DrawSphereBasic(GOLD); // Draw the Sun rlPopMatrix(); - + rlPushMatrix(); rlRotatef(earthOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Earth orbit around Sun rlTranslatef(earthOrbitRadius, 0.0f, 0.0f); // Translation for Earth orbit @@ -91,19 +91,19 @@ int main() rlPushMatrix(); rlRotatef(earthRotation, 0.25, 1.0, 0.0); // Rotation for Earth itself rlScalef(earthRadius, earthRadius, earthRadius);// Scale Earth - + DrawSphereBasic(BLUE); // Draw the Earth rlPopMatrix(); - + rlRotatef(moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth rlTranslatef(moonOrbitRadius, 0.0f, 0.0f); // Translation for Moon orbit rlRotatef(-moonOrbitRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon orbit around Earth inverted rlRotatef(moonRotation, 0.0f, 1.0f, 0.0f); // Rotation for Moon itself rlScalef(moonRadius, moonRadius, moonRadius); // Scale Moon - + DrawSphereBasic(LIGHTGRAY); // Draw the Moon rlPopMatrix(); - + // Some reference elements (not affected by previous matrix transformations) DrawCircle3D((Vector3){ 0.0f, 0.0f, 0.0f }, earthOrbitRadius, (Vector3){ 1, 0, 0 }, 90.0f, Fade(RED, 0.5f)); DrawGrid(20, 1.0f); @@ -135,7 +135,7 @@ void DrawSphereBasic(Color color) { int rings = 16; int slices = 16; - + rlBegin(RL_TRIANGLES); rlColor4ub(color.r, color.g, color.b, color.a); diff --git a/examples/models/models_skybox.c b/examples/models/models_skybox.c index d3369b70..1693d9bc 100644 --- a/examples/models/models_skybox.c +++ b/examples/models/models_skybox.c @@ -11,22 +11,22 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing"); // Define the camera to look into our 3d world Camera camera = {{ 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; - // Load skybox model + // Load skybox model Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); Model skybox = LoadModelFromMesh(cube); - + // Load skybox shader and set required locations // NOTE: Some locations are automatically set at shader loading #if defined(PLATFORM_DESKTOP) @@ -43,17 +43,17 @@ int main() Shader shdrCubemap = LoadShader("resources/shaders/glsl100/cubemap.vs", "resources/shaders/glsl100/cubemap.fs"); #endif SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, UNIFORM_INT); - + // Load HDR panorama (sphere) texture Texture2D texHDR = LoadTexture("resources/dresden_square.hdr"); - + // Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture // NOTE: New texture is generated rendering to texture, shader computes the sphre->cube coordinates mapping skybox.materials[0].maps[MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, texHDR, 512); - + UnloadTexture(texHDR); // Texture not required anymore, cubemap already generated UnloadShader(shdrCubemap); // Unload cubemap generation shader, not required anymore - + SetCameraMode(camera, CAMERA_FIRST_PERSON); // Set a first person camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -76,7 +76,7 @@ int main() BeginMode3D(camera); DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE); - + DrawGrid(10, 1.0f); EndMode3D(); diff --git a/examples/models/models_yaw_pitch_roll.c b/examples/models/models_yaw_pitch_roll.c index 658be084..0931c00e 100644 --- a/examples/models/models_yaw_pitch_roll.c +++ b/examples/models/models_yaw_pitch_roll.c @@ -17,10 +17,7 @@ // Draw angle gauge controls void DrawAngleGauge(Texture2D angleGauge, int x, int y, float angle, char title[], Color color); -//---------------------------------------------------------------------------------- -// Main entry point -//---------------------------------------------------------------------------------- -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -53,10 +50,10 @@ int main() float roll = 0.0f; float yaw = 0.0f; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update diff --git a/examples/physac/physics_demo.c b/examples/physac/physics_demo.c index a92bb9e1..421c82a9 100644 --- a/examples/physac/physics_demo.c +++ b/examples/physac/physics_demo.c @@ -10,7 +10,7 @@ * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* +* * Copyright (c) 2016-2018 Victor Fisac * ********************************************************************************************/ @@ -21,12 +21,12 @@ #define PHYSAC_NO_THREADS #include "physac.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics demo"); @@ -41,13 +41,13 @@ int main() // Create floor rectangle physics body PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10); - floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) + floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) // Create obstacle circle physics body PhysicsBody circle = CreatePhysicsBodyCircle((Vector2){ screenWidth/2, screenHeight/2 }, 45, 10); - circle->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) - - SetTargetFPS(60); + circle->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions) + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -132,9 +132,9 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- ClosePhysics(); // Unitialize physics - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/physac/physics_friction.c b/examples/physac/physics_friction.c index 337a1265..cbb9dc43 100644 --- a/examples/physac/physics_friction.c +++ b/examples/physac/physics_friction.c @@ -10,7 +10,7 @@ * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* +* * Copyright (c) 2016-2018 Victor Fisac * ********************************************************************************************/ @@ -21,12 +21,12 @@ #define PHYSAC_NO_THREADS #include "physac.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics friction"); @@ -65,7 +65,7 @@ int main() bodyB->dynamicFriction = 1; SetPhysicsBodyRotation(bodyB, 330*DEG2RAD); - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -82,7 +82,7 @@ int main() bodyA->velocity = (Vector2){ 0, 0 }; bodyA->angularVelocity = 0; SetPhysicsBodyRotation(bodyA, 30*DEG2RAD); - + bodyB->position = (Vector2){ screenWidth - 35, screenHeight*0.6f }; bodyB->velocity = (Vector2){ 0, 0 }; bodyB->angularVelocity = 0; @@ -137,9 +137,9 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- ClosePhysics(); // Unitialize physics - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/physac/physics_movement.c b/examples/physac/physics_movement.c index e799eaad..d946811d 100644 --- a/examples/physac/physics_movement.c +++ b/examples/physac/physics_movement.c @@ -10,7 +10,7 @@ * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* +* * Copyright (c) 2016-2018 Victor Fisac * ********************************************************************************************/ @@ -23,12 +23,12 @@ #define VELOCITY 0.5f -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics movement"); @@ -56,9 +56,9 @@ int main() // Create movement physics body PhysicsBody body = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight/2 }, 50, 50, 1); - body->freezeOrient = true; // Constrain body rotation to avoid little collision torque amounts - - SetTargetFPS(60); + body->freezeOrient = true; // Constrain body rotation to avoid little collision torque amounts + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -123,9 +123,9 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- ClosePhysics(); // Unitialize physics - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/physac/physics_restitution.c b/examples/physac/physics_restitution.c index 3231d0cf..a7012520 100644 --- a/examples/physac/physics_restitution.c +++ b/examples/physac/physics_restitution.c @@ -10,7 +10,7 @@ * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* +* * Copyright (c) 2016-2018 Victor Fisac * ********************************************************************************************/ @@ -21,12 +21,12 @@ #define PHYSAC_NO_THREADS #include "physac.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Physics restitution"); @@ -50,11 +50,11 @@ int main() circleB->restitution = 0.5f; PhysicsBody circleC = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.75f, screenHeight/2 }, 30, 10); circleC->restitution = 1; - - SetTargetFPS(60); // Restitution demo needs a very tiny physics time step for a proper simulation - SetPhysicsTimeStep(1.0/60.0/100 * 1000); + SetPhysicsTimeStep(1.0/60.0/100*1000); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -119,9 +119,9 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- ClosePhysics(); // Unitialize physics - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/physac/physics_shatter.c b/examples/physac/physics_shatter.c index 74785227..cbc65221 100644 --- a/examples/physac/physics_shatter.c +++ b/examples/physac/physics_shatter.c @@ -10,7 +10,7 @@ * gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static / * -lraylib -lpthread -lglfw3 -lopengl32 -lgdi32 -lopenal32 -lwinmm / * -std=c99 -Wl,--subsystem,windows -Wl,-allow-multiple-definition -* +* * Copyright (c) 2016-2018 Victor Fisac * ********************************************************************************************/ @@ -21,12 +21,12 @@ #define PHYSAC_NO_THREADS #include "physac.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "Physac [raylib] - Body shatter"); @@ -43,7 +43,7 @@ int main() // Create random polygon physics body to shatter CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -115,9 +115,9 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- ClosePhysics(); // Unitialize physics - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shaders/shaders_custom_uniform.c b/examples/shaders/shaders_custom_uniform.c index 74b9e771..1c82bba2 100644 --- a/examples/shaders/shaders_custom_uniform.c +++ b/examples/shaders/shaders_custom_uniform.c @@ -24,13 +24,13 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - + const int screenWidth = 800; + const int screenHeight = 450; + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable"); @@ -48,20 +48,20 @@ int main() model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position - + // Load postprocessing shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/swirl.fs", GLSL_VERSION)); - + // Get variable (uniform) location on the shader to connect with the program // NOTE: If uniform variable could not be found in the shader, function returns -1 int swirlCenterLoc = GetShaderLocation(shader, "center"); - + float swirlCenter[2] = { (float)screenWidth/2, (float)screenHeight/2 }; - + // Create a RenderTexture2D to be used for render to texture RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); - + // Setup orbital camera SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode @@ -80,7 +80,7 @@ int main() // Send new value to the shader to be used on drawing SetShaderValue(shader, swirlCenterLoc, swirlCenter, UNIFORM_VEC2); - + UpdateCamera(&camera); // Update camera //---------------------------------------------------------------------------------- @@ -89,9 +89,9 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + BeginTextureMode(target); // Enable drawing to texture - + ClearBackground(RAYWHITE); // Clear texture background BeginMode3D(camera); // Begin 3d mode drawing @@ -101,21 +101,21 @@ int main() DrawGrid(10, 1.0f); // Draw a grid EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode - + DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, RED); - + EndTextureMode(); // End drawing to texture (now we have a texture available for next passes) - + BeginShaderMode(shader); - + // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE); - + EndShaderMode(); - + // Draw some 2d text over drawn texture DrawText("(c) Barracks 3D model by Alberto Cano", screenWidth - 220, screenHeight - 20, 10, GRAY); - + DrawFPS(10, 10); EndDrawing(); diff --git a/examples/shaders/shaders_eratosthenes.c b/examples/shaders/shaders_eratosthenes.c index bfe516b5..068fc26c 100644 --- a/examples/shaders/shaders_eratosthenes.c +++ b/examples/shaders/shaders_eratosthenes.c @@ -31,7 +31,7 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -46,11 +46,11 @@ int main() // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION)); - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- @@ -64,7 +64,7 @@ int main() ClearBackground(RAYWHITE); BeginTextureMode(target); // Enable drawing to texture - ClearBackground(BLACK); // Clear the render texture + ClearBackground(BLACK); // Clear the render texture // Draw a rectangle in shader mode to be used as shader canvas // NOTE: Rectangle uses font white character texture coordinates, diff --git a/examples/shaders/shaders_julia_set.c b/examples/shaders/shaders_julia_set.c index ecaa5b6e..e64b622b 100644 --- a/examples/shaders/shaders_julia_set.c +++ b/examples/shaders/shaders_julia_set.c @@ -26,7 +26,7 @@ // A few good julia sets const float POINTS_OF_INTEREST[6][2] = -{ +{ { -0.348827, 0.607167 }, { -0.786268, 0.169728 }, { -0.8, 0.156 }, @@ -35,7 +35,7 @@ const float POINTS_OF_INTEREST[6][2] = { -0.70176, -0.3842 }, }; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -47,16 +47,16 @@ int main() // Load julia set shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/julia_set.fs", GLSL_VERSION)); - + // c constant to use in z^2 + c float c[2] = { POINTS_OF_INTEREST[0][0], POINTS_OF_INTEREST[0][1] }; - + // Offset and zoom to draw the julia set at. (centered on screen and default size) float offset[2] = { -(float)screenWidth/2, -(float)screenHeight/2 }; float zoom = 1.0f; - + Vector2 offsetSpeed = { 0.0f, 0.0f }; - + // Get variable (uniform) locations on the shader to connect with the program // NOTE: If uniform variable could not be found in the shader, function returns -1 int cLoc = GetShaderLocation(shader, "c"); @@ -64,35 +64,34 @@ int main() int offsetLoc = GetShaderLocation(shader, "offset"); // Tell the shader what the screen dimensions, zoom, offset and c are - float screenDims[2] = { (float)GetScreenWidth(), (float)GetScreenHeight() }; + float screenDims[2] = { (float)screenWidth, (float)screenHeight }; SetShaderValue(shader, GetShaderLocation(shader, "screenDims"), screenDims, UNIFORM_VEC2); - + SetShaderValue(shader, cLoc, c, UNIFORM_VEC2); SetShaderValue(shader, zoomLoc, &zoom, UNIFORM_FLOAT); SetShaderValue(shader, offsetLoc, offset, UNIFORM_VEC2); // Create a RenderTexture2D to be used for render to texture RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); - - int incrementSpeed = 0; // Multiplier of speed to change c value - bool showControls = true; // Show controls - bool pause = false; // Pause animation - SetTargetFPS(60); // Set the window to run at 60 frames-per-second + int incrementSpeed = 0; // Multiplier of speed to change c value + bool showControls = true; // Show controls + bool pause = false; // Pause animation + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- - // Press [1 - 6] to reset c to a point of interest - if (IsKeyPressed(KEY_ONE) || - IsKeyPressed(KEY_TWO) || - IsKeyPressed(KEY_THREE) || - IsKeyPressed(KEY_FOUR) || - IsKeyPressed(KEY_FIVE) || + if (IsKeyPressed(KEY_ONE) || + IsKeyPressed(KEY_TWO) || + IsKeyPressed(KEY_THREE) || + IsKeyPressed(KEY_FOUR) || + IsKeyPressed(KEY_FIVE) || IsKeyPressed(KEY_SIX)) { if (IsKeyPressed(KEY_ONE)) c[0] = POINTS_OF_INTEREST[0][0], c[1] = POINTS_OF_INTEREST[0][1]; @@ -107,7 +106,7 @@ int main() if (IsKeyPressed(KEY_SPACE)) pause = !pause; // Pause animation (c change) if (IsKeyPressed(KEY_F1)) showControls = !showControls; // Toggle whether or not to show controls - + if (!pause) { if (IsKeyPressed(KEY_RIGHT)) incrementSpeed++; @@ -121,10 +120,10 @@ int main() if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) zoom -= zoom*0.003f; Vector2 mousePos = GetMousePosition(); - + offsetSpeed.x = mousePos.x -(float)screenWidth/2; offsetSpeed.y = mousePos.y -(float)screenHeight/2; - + // Slowly move camera to targetOffset offset[0] += GetFrameTime()*offsetSpeed.x*0.8f; offset[1] += GetFrameTime()*offsetSpeed.y*0.8f; @@ -148,7 +147,7 @@ int main() BeginDrawing(); ClearBackground(BLACK); // Clear the screen of the previous frame. - + // Using a render texture to draw Julia set BeginTextureMode(target); // Enable drawing to texture ClearBackground(BLACK); // Clear the render texture @@ -165,7 +164,7 @@ int main() BeginShaderMode(shader); DrawTexture(target.texture, 0, 0, WHITE); EndShaderMode(); - + if (showControls) { DrawText("Press Mouse buttons right/left to zoom in/out and move", 10, 15, 10, RAYWHITE); diff --git a/examples/shaders/shaders_model_shader.c b/examples/shaders/shaders_model_shader.c index 2717c192..8224a337 100644 --- a/examples/shaders/shaders_model_shader.c +++ b/examples/shaders/shaders_model_shader.c @@ -24,13 +24,13 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - + const int screenWidth = 800; + const int screenHeight = 450; + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader"); @@ -45,16 +45,16 @@ int main() Model model = LoadModel("resources/models/watermill.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/watermill_diffuse.png"); // Load model texture - + // Load shader for model // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); model.materials[0].shader = shader; // Set shader effect to 3d model model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Bind texture to model - + Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position - + SetCameraMode(camera, CAMERA_FREE); // Set an orbital camera mode SetTargetFPS(60); // Set our game to run at 60 frames-per-second @@ -81,11 +81,8 @@ int main() DrawGrid(10, 1.0f); // Draw a grid EndMode3D(); - + DrawText("(c) Watermill 3D model by Alberto Cano", screenWidth - 210, screenHeight - 20, 10, GRAY); - - DrawText(FormatText("Camera position: (%.2f, %.2f, %.2f)", camera.position.x, camera.position.y, camera.position.z), 600, 20, 10, BLACK); - DrawText(FormatText("Camera target: (%.2f, %.2f, %.2f)", camera.target.x, camera.target.y, camera.target.z), 600, 40, 10, GRAY); DrawFPS(10, 10); diff --git a/examples/shaders/shaders_palette_switch.c b/examples/shaders/shaders_palette_switch.c index 4d651412..6bc27827 100644 --- a/examples/shaders/shaders_palette_switch.c +++ b/examples/shaders/shaders_palette_switch.c @@ -69,12 +69,12 @@ static const char *paletteText[] = { "RKBV (2-strip film)" }; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shaders] example - color palette switch"); @@ -117,7 +117,7 @@ int main() BeginShaderMode(shader); - for (int i = 0; i < COLORS_PER_PALETTE; i++) + for (int i = 0; i < COLORS_PER_PALETTE; i++) { // Draw horizontal screen-wide rectangles with increasing "palette index" // The used palette index is encoded in the RGB components of the pixel @@ -129,7 +129,7 @@ int main() DrawText("< >", 10, 10, 30, DARKBLUE); DrawText("CURRENT PALETTE:", 60, 15, 20, RAYWHITE); DrawText(paletteText[currentPalette], 300, 15, 20, RED); - + DrawFPS(700, 15); EndDrawing(); diff --git a/examples/shaders/shaders_postprocessing.c b/examples/shaders/shaders_postprocessing.c index 7c146419..018b8d11 100644 --- a/examples/shaders/shaders_postprocessing.c +++ b/examples/shaders/shaders_postprocessing.c @@ -58,31 +58,31 @@ static const char *postproShaderText[] = { //"FXAA" }; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - + const int screenWidth = 800; + const int screenHeight = 450; + SetConfigFlags(FLAG_MSAA_4X_HINT); // Enable Multi Sampling Anti Aliasing 4x (if available) InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader"); // Define the camera to look into our 3d world Camera camera = {{ 2.0f, 3.0f, 2.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; - + Model model = LoadModel("resources/models/church.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/church_diffuse.png"); // Load model texture (diffuse map) model.materials[0].maps[MAP_DIFFUSE].texture = texture; // Set model diffuse texture Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position - + // Load all postpro shaders // NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER) // NOTE 2: We load the correct shader depending on GLSL version Shader shaders[MAX_POSTPRO_SHADERS]; - + // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader shaders[FX_GRAYSCALE] = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); shaders[FX_POSTERIZATION] = LoadShader(0, FormatText("resources/shaders/glsl%i/posterization.fs", GLSL_VERSION)); @@ -96,12 +96,12 @@ int main() shaders[FX_SOBEL] = LoadShader(0, FormatText("resources/shaders/glsl%i/sobel.fs", GLSL_VERSION)); shaders[FX_BLOOM] = LoadShader(0, FormatText("resources/shaders/glsl%i/bloom.fs", GLSL_VERSION)); shaders[FX_BLUR] = LoadShader(0, FormatText("resources/shaders/glsl%i/blur.fs", GLSL_VERSION)); - + int currentShader = FX_GRAYSCALE; // Create a RenderTexture2D to be used for render to texture RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); - + // Setup orbital camera SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode @@ -114,10 +114,10 @@ int main() // Update //---------------------------------------------------------------------------------- UpdateCamera(&camera); // Update camera - + if (IsKeyPressed(KEY_RIGHT)) currentShader++; else if (IsKeyPressed(KEY_LEFT)) currentShader--; - + if (currentShader >= MAX_POSTPRO_SHADERS) currentShader = 0; else if (currentShader < 0) currentShader = MAX_POSTPRO_SHADERS - 1; //---------------------------------------------------------------------------------- @@ -129,7 +129,7 @@ int main() ClearBackground(RAYWHITE); BeginTextureMode(target); // Enable drawing to texture - + ClearBackground(RAYWHITE); // Clear texture background BeginMode3D(camera); // Begin 3d mode drawing @@ -139,26 +139,26 @@ int main() DrawGrid(10, 1.0f); // Draw a grid EndMode3D(); // End 3d mode drawing, returns to orthographic 2d mode - + EndTextureMode(); // End drawing to texture (now we have a texture available for next passes) - + // Render previously generated texture using selected postpro shader BeginShaderMode(shaders[currentShader]); - + // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE); - + EndShaderMode(); - + // Draw 2d shapes and text over drawn texture DrawRectangle(0, 9, 580, 30, Fade(LIGHTGRAY, 0.7f)); - + DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, GRAY); - + DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, BLACK); DrawText(postproShaderText[currentShader], 330, 15, 20, RED); DrawText("< >", 540, 10, 30, DARKBLUE); - + DrawFPS(700, 15); EndDrawing(); @@ -167,10 +167,10 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - + // Unload all postpro shaders for (int i = 0; i < MAX_POSTPRO_SHADERS; i++) UnloadShader(shaders[i]); - + UnloadTexture(texture); // Unload texture UnloadModel(model); // Unload model UnloadRenderTexture(target); // Unload render texture diff --git a/examples/shaders/shaders_raymarching.c b/examples/shaders/shaders_raymarching.c index f68222b5..34091792 100644 --- a/examples/shaders/shaders_raymarching.c +++ b/examples/shaders/shaders_raymarching.c @@ -24,13 +24,13 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; - + const int screenWidth = 800; + const int screenHeight = 450; + InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes"); Camera camera = { 0 }; @@ -44,7 +44,7 @@ int main() // Load raymarching shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/raymarching.fs", GLSL_VERSION)); - + // Get shader locations for required uniforms int viewEyeLoc = GetShaderLocation(shader, "viewEye"); int viewCenterLoc = GetShaderLocation(shader, "viewCenter"); @@ -72,7 +72,7 @@ int main() float cameraTarget[3] = { camera.target.x, camera.target.y, camera.target.z }; float cameraUp[3] = { camera.up.x, camera.up.y, camera.up.z }; - float deltaTime = GetFrameTime(); + float deltaTime = GetFrameTime(); runTime += deltaTime; // Set shader required uniform values diff --git a/examples/shaders/shaders_shapes_textures.c b/examples/shaders/shaders_shapes_textures.c index 5ee5d560..cf53bf99 100644 --- a/examples/shaders/shaders_shapes_textures.c +++ b/examples/shaders/shaders_shapes_textures.c @@ -24,23 +24,23 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders"); - + Texture2D fudesumi = LoadTexture("resources/fudesumi.png"); // Load shader to be used on some parts drawing - // NOTE 1: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version + // NOTE 1: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version // NOTE 2: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -56,19 +56,19 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + // Start drawing with default shader DrawText("USING DEFAULT SHADER", 20, 40, 10, RED); - + DrawCircle(80, 120, 35, DARKBLUE); DrawCircleGradient(80, 220, 60, GREEN, SKYBLUE); DrawCircleLines(80, 340, 80, DARKBLUE); - + // Activate our custom shader to be applied on next shapes/textures drawings BeginShaderMode(shader); - + DrawText("USING CUSTOM SHADER", 190, 40, 10, RED); DrawRectangle(250 - 60, 90, 120, 60, RED); @@ -77,29 +77,29 @@ int main() // Activate our default shader for next drawings EndShaderMode(); - + DrawText("USING DEFAULT SHADER", 370, 40, 10, RED); - + DrawTriangle((Vector2){430, 80}, (Vector2){430 - 60, 150}, (Vector2){430 + 60, 150}, VIOLET); - + DrawTriangleLines((Vector2){430, 160}, (Vector2){430 - 20, 230}, (Vector2){430 + 20, 230}, DARKBLUE); DrawPoly((Vector2){430, 320}, 6, 80, 0, BROWN); - + // Activate our custom shader to be applied on next shapes/textures drawings BeginShaderMode(shader); DrawTexture(fudesumi, 500, -30, WHITE); // Using custom shader - + // Activate our default shader for next drawings EndShaderMode(); - + DrawText("(c) Fudesumi sprite by Eiden Marsal", 380, screenHeight - 20, 10, GRAY); - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -108,7 +108,7 @@ int main() //-------------------------------------------------------------------------------------- UnloadShader(shader); // Unload shader UnloadTexture(fudesumi); // Unload texture - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shaders/shaders_texture_drawing.c b/examples/shaders/shaders_texture_drawing.c index 3a540098..697000bc 100644 --- a/examples/shaders/shaders_texture_drawing.c +++ b/examples/shaders/shaders_texture_drawing.c @@ -21,12 +21,12 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture drawing"); @@ -41,17 +41,18 @@ int main() int timeLoc = GetShaderLocation(shader, "uTime"); SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT); - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + // ------------------------------------------------------------------------------------------------------------- - while (!WindowShouldClose()) + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- time = GetTime(); SetShaderValue(shader, timeLoc, &time, UNIFORM_FLOAT); //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); @@ -61,13 +62,13 @@ int main() BeginShaderMode(shader); // Enable our custom shader for next shapes/textures drawings DrawTexture(texture, 0, 0, WHITE); // Drawing BLANK texture, all magic happens on shader EndShaderMode(); // Disable our custom shader, return to default shader - + DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, MAROON); EndDrawing(); //---------------------------------------------------------------------------------- } - + // De-Initialization //-------------------------------------------------------------------------------------- UnloadShader(shader); diff --git a/examples/shaders/shaders_texture_waves.c b/examples/shaders/shaders_texture_waves.c index e0026d36..07186d37 100644 --- a/examples/shaders/shaders_texture_waves.c +++ b/examples/shaders/shaders_texture_waves.c @@ -26,10 +26,7 @@ #define GLSL_VERSION 100 #endif -// ------------------------------------------------------------------------------------------------------------- -// Main Entry point -// ------------------------------------------------------------------------------------------------------------- -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -69,13 +66,13 @@ int main() SetShaderValue(shader, speedXLoc, &speedX, UNIFORM_FLOAT); SetShaderValue(shader, speedYLoc, &speedY, UNIFORM_FLOAT); - float seconds = 0.0f; - - SetTargetFPS(60); - // ------------------------------------------------------------------------------------------------------------- - + float seconds = 0.0f; + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + // ------------------------------------------------------------------------------------------------------------- + // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- @@ -86,9 +83,9 @@ int main() // Draw //---------------------------------------------------------------------------------- - BeginDrawing(); + BeginDrawing(); - ClearBackground(RAYWHITE); + ClearBackground(RAYWHITE); BeginShaderMode(shader); @@ -97,7 +94,7 @@ int main() EndShaderMode(); - EndDrawing(); + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -109,5 +106,5 @@ int main() CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - return 0; + return 0; } diff --git a/examples/shapes/shapes_basic_shapes.c b/examples/shapes/shapes_basic_shapes.c index 67eea9d5..f7a8d02f 100644 --- a/examples/shapes/shapes_basic_shapes.c +++ b/examples/shapes/shapes_basic_shapes.c @@ -11,16 +11,16 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes drawing"); - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/shapes/shapes_bouncing_ball.c b/examples/shapes/shapes_bouncing_ball.c index 6b27c9dd..9f01ff14 100644 --- a/examples/shapes/shapes_bouncing_ball.c +++ b/examples/shapes/shapes_bouncing_ball.c @@ -11,58 +11,58 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //--------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; - + InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball"); - - Vector2 ballPosition = { GetScreenWidth()/2, GetScreenHeight()/2 }; - Vector2 ballSpeed = { 5.0f, 4.0f }; - int ballRadius = 20; - + + Vector2 ballPosition = { GetScreenWidth()/2, GetScreenHeight()/2 }; + Vector2 ballSpeed = { 5.0f, 4.0f }; + int ballRadius = 20; + bool pause = 0; int framesCounter = 0; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //---------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //----------------------------------------------------- if (IsKeyPressed(KEY_SPACE)) pause = !pause; - + if (!pause) { ballPosition.x += ballSpeed.x; ballPosition.y += ballSpeed.y; - + // Check walls collision for bouncing if ((ballPosition.x >= (GetScreenWidth() - ballRadius)) || (ballPosition.x <= ballRadius)) ballSpeed.x *= -1.0f; if ((ballPosition.y >= (GetScreenHeight() - ballRadius)) || (ballPosition.y <= ballRadius)) ballSpeed.y *= -1.0f; } else framesCounter++; //----------------------------------------------------- - + // Draw //----------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawCircleV(ballPosition, ballRadius, MAROON); DrawText("PRESS SPACE to PAUSE BALL MOVEMENT", 10, GetScreenHeight() - 25, 20, LIGHTGRAY); - + // On pause, we draw a blinking message if (pause && ((framesCounter/30)%2)) DrawText("PAUSED", 350, 200, 30, GRAY); DrawFPS(10, 10); - + EndDrawing(); //----------------------------------------------------- } @@ -71,6 +71,6 @@ int main() //--------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //---------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/shapes/shapes_collision_area.c b/examples/shapes/shapes_collision_area.c index e61623ab..0deba0dd 100644 --- a/examples/shapes/shapes_collision_area.c +++ b/examples/shapes/shapes_collision_area.c @@ -12,89 +12,89 @@ #include "raylib.h" #include // Required for abs() -int main() +int main(void) { // Initialization //--------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area"); - + // Box A: Moving box Rectangle boxA = { 10, GetScreenHeight()/2 - 50, 200, 100 }; - int boxASpeedX = 4; - + int boxASpeedX = 4; + // Box B: Mouse moved box Rectangle boxB = { GetScreenWidth()/2 - 30, GetScreenHeight()/2 - 30, 60, 60 }; - - Rectangle boxCollision = { 0 }; // Collision rectangle - + + Rectangle boxCollision = { 0 }; // Collision rectangle + int screenUpperLimit = 40; // Top menu limits - - bool pause = false; // Movement pause - bool collision = false; // Collision detection - - SetTargetFPS(60); + + bool pause = false; // Movement pause + bool collision = false; // Collision detection + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //---------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //----------------------------------------------------- // Move box if not paused - if (!pause) boxA.x += boxASpeedX; - + if (!pause) boxA.x += boxASpeedX; + // Bounce box on x screen limits - if (((boxA.x + boxA.width) >= GetScreenWidth()) || (boxA.x <= 0)) boxASpeedX *= -1; - - // Update player-controlled-box (box02) - boxB.x = GetMouseX() - boxB.width/2; - boxB.y = GetMouseY() - boxB.height/2; - + if (((boxA.x + boxA.width) >= GetScreenWidth()) || (boxA.x <= 0)) boxASpeedX *= -1; + + // Update player-controlled-box (box02) + boxB.x = GetMouseX() - boxB.width/2; + boxB.y = GetMouseY() - boxB.height/2; + // Make sure Box B does not go out of move area limits - if ((boxB.x + boxB.width) >= GetScreenWidth()) boxB.x = GetScreenWidth() - boxB.width; - else if (boxB.x <= 0) boxB.x = 0; - - if ((boxB.y + boxB.height) >= GetScreenHeight()) boxB.y = GetScreenHeight() - boxB.height; - else if (boxB.y <= screenUpperLimit) boxB.y = screenUpperLimit; - + if ((boxB.x + boxB.width) >= GetScreenWidth()) boxB.x = GetScreenWidth() - boxB.width; + else if (boxB.x <= 0) boxB.x = 0; + + if ((boxB.y + boxB.height) >= GetScreenHeight()) boxB.y = GetScreenHeight() - boxB.height; + else if (boxB.y <= screenUpperLimit) boxB.y = screenUpperLimit; + // Check boxes collision collision = CheckCollisionRecs(boxA, boxB); - - // Get collision rectangle (only on collision) - if (collision) boxCollision = GetCollisionRec(boxA, boxB); - + + // Get collision rectangle (only on collision) + if (collision) boxCollision = GetCollisionRec(boxA, boxB); + // Pause Box A movement - if (IsKeyPressed(KEY_SPACE)) pause = !pause; + if (IsKeyPressed(KEY_SPACE)) pause = !pause; //----------------------------------------------------- - + // Draw //----------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawRectangle(0, 0, screenWidth, screenUpperLimit, collision? RED : BLACK); DrawRectangleRec(boxA, GOLD); DrawRectangleRec(boxB, BLUE); - + if (collision) { // Draw collision area DrawRectangleRec(boxCollision, LIME); - + // Draw collision message DrawText("COLLISION!", GetScreenWidth()/2 - MeasureText("COLLISION!", 20)/2, screenUpperLimit/2 - 10, 20, BLACK); - + // Draw collision area DrawText(FormatText("Collision Area: %i", (int)boxCollision.width*(int)boxCollision.height), GetScreenWidth()/2 - 100, screenUpperLimit + 10, 20, BLACK); - } + } DrawFPS(10, 10); - + EndDrawing(); //----------------------------------------------------- } @@ -103,6 +103,6 @@ int main() //--------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //---------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/shapes/shapes_colors_palette.c b/examples/shapes/shapes_colors_palette.c index d6ac30a9..7322f7e5 100644 --- a/examples/shapes/shapes_colors_palette.c +++ b/examples/shapes/shapes_colors_palette.c @@ -13,7 +13,7 @@ #define MAX_COLORS_COUNT 21 // Number of colors available -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -22,14 +22,14 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette"); - Color colors[MAX_COLORS_COUNT] = { + Color colors[MAX_COLORS_COUNT] = { DARKGRAY, MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, DARKBROWN, GRAY, RED, GOLD, LIME, BLUE, VIOLET, BROWN, LIGHTGRAY, PINK, YELLOW, GREEN, SKYBLUE, PURPLE, BEIGE }; - - const char *colorNames[MAX_COLORS_COUNT] = { - "DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE", - "DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN", + + const char *colorNames[MAX_COLORS_COUNT] = { + "DARKGRAY", "MAROON", "ORANGE", "DARKGREEN", "DARKBLUE", "DARKPURPLE", + "DARKBROWN", "GRAY", "RED", "GOLD", "LIME", "BLUE", "VIOLET", "BROWN", "LIGHTGRAY", "PINK", "YELLOW", "GREEN", "SKYBLUE", "PURPLE", "BEIGE" }; Rectangle colorsRecs[MAX_COLORS_COUNT] = { 0 }; // Rectangles array @@ -69,19 +69,19 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("raylib colors palette", 28, 42, 20, BLACK); DrawText("press SPACE to see all colors", GetScreenWidth() - 180, GetScreenHeight() - 40, 10, GRAY); for (int i = 0; i < MAX_COLORS_COUNT; i++) // Draw all rectangles { DrawRectangleRec(colorsRecs[i], Fade(colors[i], colorState[i]? 0.6f : 1.0f)); - - if (IsKeyDown(KEY_SPACE) || colorState[i]) + + if (IsKeyDown(KEY_SPACE) || colorState[i]) { DrawRectangle(colorsRecs[i].x, colorsRecs[i].y + colorsRecs[i].height - 26, colorsRecs[i].width, 20, BLACK); DrawRectangleLinesEx(colorsRecs[i], 6, Fade(BLACK, 0.3f)); - DrawText(colorNames[i], colorsRecs[i].x + colorsRecs[i].width - MeasureText(colorNames[i], 10) - 12, + DrawText(colorNames[i], colorsRecs[i].x + colorsRecs[i].width - MeasureText(colorNames[i], 10) - 12, colorsRecs[i].y + colorsRecs[i].height - 20, 10, colors[i]); } } diff --git a/examples/shapes/shapes_draw_circle_sector.c b/examples/shapes/shapes_draw_circle_sector.c index 597b85a7..ae6de5ff 100644 --- a/examples/shapes/shapes_draw_circle_sector.c +++ b/examples/shapes/shapes_draw_circle_sector.c @@ -16,7 +16,7 @@ #define RAYGUI_IMPLEMENTATION #include "raygui.h" // Required for GUI controls -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -32,7 +32,7 @@ int main() int endAngle = 180; int segments = 0; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/shapes/shapes_draw_rectangle_rounded.c b/examples/shapes/shapes_draw_rectangle_rounded.c index e36e2731..c183e88b 100644 --- a/examples/shapes/shapes_draw_rectangle_rounded.c +++ b/examples/shapes/shapes_draw_rectangle_rounded.c @@ -30,12 +30,12 @@ int main(void) int height = 100; int segments = 0; int lineThick = 1; - + bool drawRect = false; bool drawRoundedRect = true; bool drawRoundedLines = false; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -45,20 +45,20 @@ int main(void) //---------------------------------------------------------------------------------- Rectangle rec = { (GetScreenWidth() - width - 250)/2, (GetScreenHeight() - height)/2, width, height }; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawLine(560, 0, 560, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f)); DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f)); if (drawRect) DrawRectangleRec(rec, Fade(GOLD, 0.6)); if (drawRoundedRect) DrawRectangleRounded(rec, roundness, segments, Fade(MAROON, 0.2)); if (drawRoundedLines) DrawRectangleRoundedLines(rec,roundness, segments, lineThick, Fade(MAROON, 0.4)); - + // Draw GUI controls //------------------------------------------------------------------------------ width = GuiSliderBar((Rectangle){ 640, 40, 105, 20 }, "Width", width, 0, GetScreenWidth() - 300, true ); @@ -66,22 +66,22 @@ int main(void) roundness = GuiSliderBar((Rectangle){ 640, 140, 105, 20 }, "Roundness", roundness, 0.0f, 1.0f, true); lineThick = GuiSliderBar((Rectangle){ 640, 170, 105, 20 }, "Thickness", lineThick, 0, 20, true); segments = GuiSliderBar((Rectangle){ 640, 240, 105, 20}, "Segments", segments, 0, 60, true); - + drawRoundedRect = GuiCheckBox((Rectangle){ 640, 320, 20, 20 }, "DrawRoundedRect", drawRoundedRect); drawRoundedLines = GuiCheckBox((Rectangle){ 640, 350, 20, 20 }, "DrawRoundedLines", drawRoundedLines); drawRect = GuiCheckBox((Rectangle){ 640, 380, 20, 20}, "DrawRect", drawRect); //------------------------------------------------------------------------------ - + DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 640, 280, 10, (segments >= 4)? MAROON : DARKGRAY); - + DrawFPS(10, 10); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_draw_ring.c b/examples/shapes/shapes_draw_ring.c index 44a3ec5f..a90feab7 100644 --- a/examples/shapes/shapes_draw_ring.c +++ b/examples/shapes/shapes_draw_ring.c @@ -16,7 +16,7 @@ #define RAYGUI_IMPLEMENTATION #include "raygui.h" // Required for GUI controls -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -29,16 +29,16 @@ int main() float innerRadius = 80.0f; float outerRadius = 190.0f; - + int startAngle = 0; int endAngle = 360; int segments = 0; - + bool drawRing = true; bool drawRingLines = false; bool drawCircleLines = false; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -48,13 +48,13 @@ int main() //---------------------------------------------------------------------------------- // NOTE: All variables update happens inside GUI control functions //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawLine(500, 0, 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f)); DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f)); @@ -66,27 +66,27 @@ int main() //------------------------------------------------------------------------------ startAngle = GuiSliderBar((Rectangle){ 600, 40, 120, 20 }, "StartAngle", startAngle, -450, 450, true); endAngle = GuiSliderBar((Rectangle){ 600, 70, 120, 20 }, "EndAngle", endAngle, -450, 450, true); - + innerRadius = GuiSliderBar((Rectangle){ 600, 140, 120, 20 }, "InnerRadius", innerRadius, 0, 100, true); outerRadius = GuiSliderBar((Rectangle){ 600, 170, 120, 20 }, "OuterRadius", outerRadius, 0, 200, true); - + segments = GuiSliderBar((Rectangle){ 600, 240, 120, 20 }, "Segments", segments, 0, 100, true); - + drawRing = GuiCheckBox((Rectangle){ 600, 320, 20, 20 }, "Draw Ring", drawRing); drawRingLines = GuiCheckBox((Rectangle){ 600, 350, 20, 20 }, "Draw RingLines", drawRingLines); drawCircleLines = GuiCheckBox((Rectangle){ 600, 380, 20, 20 }, "Draw CircleLines", drawCircleLines); //------------------------------------------------------------------------------ - + DrawText(FormatText("MODE: %s", (segments >= 4)? "MANUAL" : "AUTO"), 600, 270, 10, (segments >= 4)? MAROON : DARKGRAY); - + DrawFPS(10, 10); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_easings_ball_anim.c b/examples/shapes/shapes_easings_ball_anim.c index 4477203c..5bb2b4c6 100644 --- a/examples/shapes/shapes_easings_ball_anim.c +++ b/examples/shapes/shapes_easings_ball_anim.c @@ -11,9 +11,9 @@ #include "raylib.h" -#include "easings.h" // Required for easing functions +#include "easings.h" // Required for easing functions -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -21,16 +21,16 @@ int main() const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball anim"); - + // Ball variable value to be animated with easings int ballPositionX = -100; int ballRadius = 20; float ballAlpha = 0.0f; - + int state = 0; int framesCounter = 0; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -42,7 +42,7 @@ int main() { framesCounter++; ballPositionX = EaseElasticOut(framesCounter, -100, screenWidth/2 + 100, 120); - + if (framesCounter >= 120) { framesCounter = 0; @@ -53,7 +53,7 @@ int main() { framesCounter++; ballRadius = EaseElasticIn(framesCounter, 20, 500, 200); - + if (framesCounter >= 200) { framesCounter = 0; @@ -64,7 +64,7 @@ int main() { framesCounter++; ballAlpha = EaseCubicOut(framesCounter, 0.0f, 1.0f, 200); - + if (framesCounter >= 200) { framesCounter = 0; @@ -73,7 +73,7 @@ int main() } else if (state == 3) // Reset state to play again { - if (IsKeyPressed(KEY_ENTER)) + if (IsKeyPressed(KEY_ENTER)) { // Reset required variables to play again ballPositionX = -100; @@ -82,7 +82,7 @@ int main() state = 0; } } - + if (IsKeyPressed(KEY_R)) framesCounter = 0; //---------------------------------------------------------------------------------- @@ -94,15 +94,15 @@ int main() if (state >= 2) DrawRectangle(0, 0, screenWidth, screenHeight, GREEN); DrawCircle(ballPositionX, 200, ballRadius, Fade(RED, 1.0f - ballAlpha)); - + if (state == 3) DrawText("PRESS [ENTER] TO PLAY AGAIN!", 240, 200, 20, BLACK); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_easings_box_anim.c b/examples/shapes/shapes_easings_box_anim.c index c74cb2a3..6805d531 100644 --- a/examples/shapes/shapes_easings_box_anim.c +++ b/examples/shapes/shapes_easings_box_anim.c @@ -13,7 +13,7 @@ #include "easings.h" // Required for easing functions -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -21,16 +21,16 @@ int main() const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box anim"); - + // Box variables to be animated with easings Rectangle rec = { GetScreenWidth()/2, -100, 100, 100 }; float rotation = 0.0f; float alpha = 1.0f; - + int state = 0; int framesCounter = 0; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -43,12 +43,12 @@ int main() case 0: // Move box down to center of screen { framesCounter++; - + // NOTE: Remember that 3rd parameter of easing function refers to // desired value variation, do not confuse it with expected final value! rec.y = EaseElasticOut(framesCounter, -100, GetScreenHeight()/2 + 100, 120); - if (framesCounter >= 120) + if (framesCounter >= 120) { framesCounter = 0; state = 1; @@ -59,8 +59,8 @@ int main() framesCounter++; rec.height = EaseBounceOut(framesCounter, 100, -90, 120); rec.width = EaseBounceOut(framesCounter, 100, GetScreenWidth(), 120); - - if (framesCounter >= 120) + + if (framesCounter >= 120) { framesCounter = 0; state = 2; @@ -70,8 +70,8 @@ int main() { framesCounter++; rotation = EaseQuadOut(framesCounter, 0.0f, 270.0f, 240); - - if (framesCounter >= 240) + + if (framesCounter >= 240) { framesCounter = 0; state = 3; @@ -81,8 +81,8 @@ int main() { framesCounter++; rec.height = EaseCircOut(framesCounter, 10, GetScreenWidth(), 120); - - if (framesCounter >= 120) + + if (framesCounter >= 120) { framesCounter = 0; state = 4; @@ -92,7 +92,7 @@ int main() { framesCounter++; alpha = EaseSineOut(framesCounter, 1.0f, -1.0f, 160); - + if (framesCounter >= 160) { framesCounter = 0; @@ -101,7 +101,7 @@ int main() } break; default: break; } - + // Reset animation at any moment if (IsKeyPressed(KEY_SPACE)) { @@ -112,7 +112,7 @@ int main() framesCounter = 0; } //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); @@ -120,7 +120,7 @@ int main() ClearBackground(RAYWHITE); DrawRectanglePro(rec, (Vector2){ rec.width/2, rec.height/2 }, rotation, Fade(BLACK, alpha)); - + DrawText("PRESS [SPACE] TO RESET BOX ANIMATION!", 10, GetScreenHeight() - 25, 20, LIGHTGRAY); EndDrawing(); @@ -128,7 +128,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_easings_rectangle_array.c b/examples/shapes/shapes_easings_rectangle_array.c index 27bad5c9..9844af6a 100644 --- a/examples/shapes/shapes_easings_rectangle_array.c +++ b/examples/shapes/shapes_easings_rectangle_array.c @@ -2,7 +2,7 @@ * * raylib [shapes] example - easings rectangle array * -* NOTE: This example requires 'easings.h' library, provided on raylib/src. Just copy +* NOTE: This example requires 'easings.h' library, provided on raylib/src. Just copy * the library to same directory as example or make sure it's available on include path. * * This example has been created using raylib 2.0 (www.raylib.com) @@ -24,17 +24,17 @@ #define PLAY_TIME_IN_FRAMES 240 // At 60 fps = 4 seconds -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array"); - + Rectangle recs[MAX_RECS_X*MAX_RECS_Y]; - + for (int y = 0; y < MAX_RECS_Y; y++) { for (int x = 0; x < MAX_RECS_X; x++) @@ -45,12 +45,12 @@ int main() recs[y*MAX_RECS_X + x].height = RECS_HEIGHT; } } - + float rotation = 0.0f; int framesCounter = 0; - int state = 0; // Rectangles animation state: 0-Playing, 1-Finished - - SetTargetFPS(60); + int state = 0; // Rectangles animation state: 0-Playing, 1-Finished + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -62,16 +62,16 @@ int main() { framesCounter++; - for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) + for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) { recs[i].height = EaseCircOut(framesCounter, RECS_HEIGHT, -RECS_HEIGHT, PLAY_TIME_IN_FRAMES); recs[i].width = EaseCircOut(framesCounter, RECS_WIDTH, -RECS_WIDTH, PLAY_TIME_IN_FRAMES); - + if (recs[i].height < 0) recs[i].height = 0; if (recs[i].width < 0) recs[i].width = 0; - + if ((recs[i].height == 0) && (recs[i].width == 0)) state = 1; // Finish playing - + rotation = EaseLinearIn(framesCounter, 0.0f, 360.0f, PLAY_TIME_IN_FRAMES); } } @@ -79,13 +79,13 @@ int main() { // When animation has finished, press space to restart framesCounter = 0; - - for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) + + for (int i = 0; i < MAX_RECS_X*MAX_RECS_Y; i++) { recs[i].height = RECS_HEIGHT; recs[i].width = RECS_WIDTH; } - + state = 0; } //---------------------------------------------------------------------------------- @@ -110,7 +110,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_following_eyes.c b/examples/shapes/shapes_following_eyes.c index e99a7e07..a36a8d67 100644 --- a/examples/shapes/shapes_following_eyes.c +++ b/examples/shapes/shapes_following_eyes.c @@ -13,7 +13,7 @@ #include // Required for: atan2f() -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -21,19 +21,19 @@ int main() const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes"); - + Vector2 scleraLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 scleraRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2 }; float scleraRadius = 80; - + Vector2 irisLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 irisRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2}; float irisRadius = 24; - - float angle; - float dx, dy, dxx, dyy; - - SetTargetFPS(60); + + float angle = 0.0f; + float dx = 0.0f, dy = 0.0f, dxx = 0.0f, dyy = 0.0f; + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -43,13 +43,13 @@ int main() //---------------------------------------------------------------------------------- irisLeftPosition = GetMousePosition(); irisRightPosition = GetMousePosition(); - + // Check not inside the left eye sclera if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20)) { dx = irisLeftPosition.x - scleraLeftPosition.x; dy = irisLeftPosition.y - scleraLeftPosition.y; - + angle = atan2f(dy, dx); dxx = (scleraRadius - irisRadius)*cosf(angle); @@ -64,7 +64,7 @@ int main() { dx = irisRightPosition.x - scleraRightPosition.x; dy = irisRightPosition.y - scleraRightPosition.y; - + angle = atan2f(dy, dx); dxx = (scleraRadius - irisRadius)*cosf(angle); @@ -84,19 +84,19 @@ int main() DrawCircleV(scleraLeftPosition, scleraRadius, LIGHTGRAY); DrawCircleV(irisLeftPosition, irisRadius, BROWN); DrawCircleV(irisLeftPosition, 10, BLACK); - + DrawCircleV(scleraRightPosition, scleraRadius, LIGHTGRAY); DrawCircleV(irisRightPosition, irisRadius, DARKGREEN); DrawCircleV(irisRightPosition, 10, BLACK); - + DrawFPS(10, 10); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_lines_bezier.c b/examples/shapes/shapes_lines_bezier.c index f4133459..3d4edcde 100644 --- a/examples/shapes/shapes_lines_bezier.c +++ b/examples/shapes/shapes_lines_bezier.c @@ -11,20 +11,20 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; SetConfigFlags(FLAG_MSAA_4X_HINT); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines"); - + Vector2 start = { 0, 0 }; Vector2 end = { screenWidth, screenHeight }; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -41,17 +41,17 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS", 15, 20, 20, GRAY); DrawLineBezier(start, end, 2.0f, RED); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_logo_raylib.c b/examples/shapes/shapes_logo_raylib.c index be94988c..3e2d343f 100644 --- a/examples/shapes/shapes_logo_raylib.c +++ b/examples/shapes/shapes_logo_raylib.c @@ -11,16 +11,16 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo using shapes"); - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/shapes/shapes_logo_raylib_anim.c b/examples/shapes/shapes_logo_raylib_anim.c index 9be1d963..b8558393 100644 --- a/examples/shapes/shapes_logo_raylib_anim.c +++ b/examples/shapes/shapes_logo_raylib_anim.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation"); @@ -35,7 +35,7 @@ int main() int state = 0; // Tracking animation states (State Machine) float alpha = 1.0f; // Useful for fading - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/shapes/shapes_rectangle_scaling.c b/examples/shapes/shapes_rectangle_scaling.c index 036a1dd4..6940cbcd 100644 --- a/examples/shapes/shapes_rectangle_scaling.c +++ b/examples/shapes/shapes_rectangle_scaling.c @@ -15,23 +15,23 @@ #define MOUSE_SCALE_MARK_SIZE 12 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse"); - + Rectangle rec = { 100, 100, 200, 80 }; - + Vector2 mousePosition = { 0 }; - + bool mouseScaleReady = false; bool mouseScaleMode = false; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -40,25 +40,25 @@ int main() // Update //---------------------------------------------------------------------------------- mousePosition = GetMousePosition(); - - if (CheckCollisionPointRec(mousePosition, rec) && + + if (CheckCollisionPointRec(mousePosition, rec) && CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE })) { mouseScaleReady = true; if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true; } else mouseScaleReady = false; - + if (mouseScaleMode) { mouseScaleReady = true; - + rec.width = (mousePosition.x - rec.x); rec.height = (mousePosition.y - rec.y); - + if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE; if (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE; - + if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false; } //---------------------------------------------------------------------------------- @@ -68,15 +68,15 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, GRAY); DrawRectangleRec(rec, Fade(GREEN, 0.5f)); - - if (mouseScaleReady) + + if (mouseScaleReady) { DrawRectangleLinesEx(rec, 1, RED); - DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height }, + DrawTriangle((Vector2){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height }, (Vector2){ rec.x + rec.width, rec.y + rec.height }, (Vector2){ rec.x + rec.width, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE }, RED); } @@ -86,7 +86,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/text/text_bmfont_ttf.c b/examples/text/text_bmfont_ttf.c index ca26b2cf..175d3f16 100644 --- a/examples/text/text_bmfont_ttf.c +++ b/examples/text/text_bmfont_ttf.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - bmfont and ttf sprite fonts loading"); @@ -25,17 +25,17 @@ int main() const char msg[256] = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ"; // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) - + // BMFont (AngelCode) : Font data and image atlas have been generated using external program Font fontBm = LoadFont("resources/pixantiqua.fnt"); - + // TTF font : Font data and atlas are generated directly from TTF // NOTE: We define a font base size of 32 pixels tall and up-to 250 characters Font fontTtf = LoadFontEx("resources/pixantiqua.ttf", 32, 0, 250); - + bool useTtf = false; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -52,7 +52,7 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("Press SPACE to use TTF generated font", 20, 20, 20, LIGHTGRAY); if (!useTtf) diff --git a/examples/text/text_font_sdf.c b/examples/text/text_font_sdf.c index 69cff471..d3c76c4f 100644 --- a/examples/text/text_font_sdf.c +++ b/examples/text/text_font_sdf.c @@ -17,17 +17,17 @@ #define GLSL_VERSION 100 #endif -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts"); // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) - + const char msg[50] = "Signed Distance Fields"; // Default font generation from TTF font @@ -40,7 +40,7 @@ int main() Image atlas = GenImageFontAtlas(fontDefault.chars, 95, 16, 4, 0); fontDefault.texture = LoadTextureFromImage(atlas); UnloadImage(atlas); - + // SDF font generation from TTF font Font fontSDF = { 0 }; fontSDF.baseSize = 16; @@ -51,7 +51,7 @@ int main() atlas = GenImageFontAtlas(fontSDF.chars, 95, 16, 0, 1); fontSDF.texture = LoadTextureFromImage(atlas); UnloadImage(atlas); - + // Load SDF required shader (we use default vertex shader) Shader shader = LoadShader(0, FormatText("resources/shaders/glsl%i/sdf.fs", GLSL_VERSION)); SetTextureFilter(fontSDF.texture, FILTER_BILINEAR); // Required for SDF font @@ -59,51 +59,51 @@ int main() Vector2 fontPosition = { 40, screenHeight/2 - 50 }; Vector2 textSize = { 0.0f }; float fontSize = 16.0f; - int currentFont = 0; // 0 - fontDefault, 1 - fontSDF - - SetTargetFPS(60); - //-------------------------------------------------------------------------------------- + int currentFont = 0; // 0 - fontDefault, 1 - fontSDF + SetTargetFPS(60); // Set our game to run at 60 frames-per-second + //-------------------------------------------------------------------------------------- + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- fontSize += GetMouseWheelMove()*8.0f; - + if (fontSize < 6) fontSize = 6; - + if (IsKeyDown(KEY_SPACE)) currentFont = 1; else currentFont = 0; - + if (currentFont == 0) textSize = MeasureTextEx(fontDefault, msg, fontSize, 0); else textSize = MeasureTextEx(fontSDF, msg, fontSize, 0); - + fontPosition.x = GetScreenWidth()/2 - textSize.x/2; fontPosition.y = GetScreenHeight()/2 - textSize.y/2 + 80; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + if (currentFont == 1) { // NOTE: SDF fonts require a custom SDf shader to compute fragment color BeginShaderMode(shader); // Activate SDF font shader DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, BLACK); EndShaderMode(); // Activate our default shader for next drawings - + DrawTexture(fontSDF.texture, 10, 10, BLACK); } - else + else { DrawTextEx(fontDefault, msg, fontPosition, fontSize, 0, BLACK); DrawTexture(fontDefault.texture, 10, 10, BLACK); } - + if (currentFont == 1) DrawText("SDF!", 320, 20, 80, RED); else DrawText("default font", 315, 40, 30, GRAY); @@ -112,7 +112,7 @@ int main() DrawText("Use MOUSE WHEEL to SCALE TEXT!", GetScreenWidth() - 240, 90, 10, DARKGRAY); DrawText("PRESS SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, MAROON); - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -121,11 +121,11 @@ int main() //-------------------------------------------------------------------------------------- UnloadFont(fontDefault); // Default font unloading UnloadFont(fontSDF); // SDF font unloading - + UnloadShader(shader); // Unload SDF shader - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/text/text_format_text.c b/examples/text/text_format_text.c index ca28be74..a9f04176 100644 --- a/examples/text/text_format_text.c +++ b/examples/text/text_format_text.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - text formatting"); @@ -24,7 +24,7 @@ int main() int hiscore = 200450; int lives = 5; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/text/text_input_box.c b/examples/text/text_input_box.c index 5f8d1c01..ea3d2992 100644 --- a/examples/text/text_input_box.c +++ b/examples/text/text_input_box.c @@ -13,12 +13,12 @@ #define MAX_INPUT_CHARS 9 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - input box"); @@ -30,7 +30,7 @@ int main() int framesCounter = 0; - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -40,27 +40,27 @@ int main() //---------------------------------------------------------------------------------- if (CheckCollisionPointRec(GetMousePosition(), textBox)) mouseOnText = true; else mouseOnText = false; - + if (mouseOnText) { int key = GetKeyPressed(); - + // NOTE: Only allow keys in range [32..125] if ((key >= 32) && (key <= 125) && (letterCount < MAX_INPUT_CHARS)) { name[letterCount] = (char)key; letterCount++; } - + if (IsKeyPressed(KEY_BACKSPACE)) { letterCount--; name[letterCount] = '\0'; - + if (letterCount < 0) letterCount = 0; } } - + if (mouseOnText) framesCounter++; else framesCounter = 0; //---------------------------------------------------------------------------------- @@ -70,15 +70,15 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("PLACE MOUSE OVER INPUT BOX!", 240, 140, 20, GRAY); DrawRectangleRec(textBox, LIGHTGRAY); if (mouseOnText) DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, RED); else DrawRectangleLines(textBox.x, textBox.y, textBox.width, textBox.height, DARKGRAY); - + DrawText(name, textBox.x + 5, textBox.y + 8, 40, MAROON); - + DrawText(FormatText("INPUT CHARS: %i/%i", letterCount, MAX_INPUT_CHARS), 315, 250, 20, DARKGRAY); if (mouseOnText) @@ -90,13 +90,13 @@ int main() } else DrawText("Press BACKSPACE to delete chars...", 230, 300, 20, GRAY); } - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/text/text_raylib_fonts.c b/examples/text/text_raylib_fonts.c index 3c930ac2..06e63725 100644 --- a/examples/text/text_raylib_fonts.c +++ b/examples/text/text_raylib_fonts.c @@ -16,18 +16,18 @@ #define MAX_FONTS 8 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - raylib fonts"); // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) Font fonts[MAX_FONTS]; - + fonts[0] = LoadFont("resources/fonts/alagard.png"); fonts[1] = LoadFont("resources/fonts/pixelplay.png"); fonts[2] = LoadFont("resources/fonts/mecha.png"); @@ -36,32 +36,34 @@ int main() fonts[5] = LoadFont("resources/fonts/pixantiqua.png"); fonts[6] = LoadFont("resources/fonts/alpha_beta.png"); fonts[7] = LoadFont("resources/fonts/jupiter_crash.png"); - - const char *messages[MAX_FONTS] = { "ALAGARD FONT designed by Hewett Tsoi", + + const char *messages[MAX_FONTS] = { "ALAGARD FONT designed by Hewett Tsoi", "PIXELPLAY FONT designed by Aleksander Shevchuk", - "MECHA FONT designed by Captain Falcon", - "SETBACK FONT designed by Brian Kent (AEnigma)", - "ROMULUS FONT designed by Hewett Tsoi", + "MECHA FONT designed by Captain Falcon", + "SETBACK FONT designed by Brian Kent (AEnigma)", + "ROMULUS FONT designed by Hewett Tsoi", "PIXANTIQUA FONT designed by Gerhard Grossmann", "ALPHA_BETA FONT designed by Brian Kent (AEnigma)", "JUPITER_CRASH FONT designed by Brian Kent (AEnigma)" }; - + const int spacings[MAX_FONTS] = { 2, 4, 8, 4, 3, 4, 4, 1 }; - + Vector2 positions[MAX_FONTS]; - + for (int i = 0; i < MAX_FONTS; i++) { positions[i].x = screenWidth/2 - MeasureTextEx(fonts[i], messages[i], fonts[i].baseSize*2, spacings[i]).x/2; positions[i].y = 60 + fonts[i].baseSize + 45*i; } - + // Small Y position corrections positions[3].y += 8; positions[4].y += 2; positions[7].y -= 8; - + Color colors[MAX_FONTS] = { MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, LIME, GOLD, RED }; + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -77,10 +79,10 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("free fonts included with raylib", 250, 20, 20, DARKGRAY); DrawLine(220, 50, 590, 50, DARKGRAY); - + for (int i = 0; i < MAX_FONTS; i++) { DrawTextEx(fonts[i], messages[i], positions[i], fonts[i].baseSize*2, spacings[i], colors[i]); @@ -92,7 +94,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - + // Fonts unloading for (int i = 0; i < MAX_FONTS; i++) UnloadFont(fonts[i]); diff --git a/examples/text/text_rectangle_bounds.c b/examples/text/text_rectangle_bounds.c index d4cd240a..5871278f 100644 --- a/examples/text/text_rectangle_bounds.c +++ b/examples/text/text_rectangle_bounds.c @@ -13,36 +13,36 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); - + char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ - a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ - tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; - + a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ + tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; + bool resizing = false; bool wordWrap = true; - + Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250}; Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 }; - + // Minimum width and heigh for the container rectangle const int minWidth = 60; - const int minHeight = 60; + const int minHeight = 60; const int maxWidth = screenWidth - 50; const int maxHeight = screenHeight - 160; - + Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates Color borderColor = MAROON; // Container border color Font font = GetFontDefault(); // Get default system font - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -51,34 +51,34 @@ int main() // Update //---------------------------------------------------------------------------------- if (IsKeyPressed(KEY_SPACE)) wordWrap = !wordWrap; - + Vector2 mouse = GetMousePosition(); - + // Check if the mouse is inside the container and toggle border color if (CheckCollisionPointRec(mouse, container)) borderColor = Fade(MAROON, 0.4f); else if (!resizing) borderColor = MAROON; - + // Container resizing logic - if (resizing) + if (resizing) { if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; - + int width = container.width + (mouse.x - lastMouse.x); container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth; - + int height = container.height + (mouse.y - lastMouse.y); container.height = (height > minHeight)? ((height < maxHeight)? height : maxHeight) : minHeight; - } - else + } + else { // Check if we're resizing if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; } - + // Move resizer rectangle properly resizer.x = container.x + container.width - 17; resizer.y = container.y + container.height - 17; - + lastMouse = mouse; // Update mouse //---------------------------------------------------------------------------------- @@ -89,10 +89,10 @@ int main() ClearBackground(RAYWHITE); DrawRectangleLinesEx(container, 3, borderColor); // Draw container border - + // Draw text in container (add some padding) - DrawTextRec(font, text, - (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, + DrawTextRec(font, text, + (Rectangle){ container.x + 4, container.y + 4, container.width - 4, container.height - 4 }, 20.0f, 2.0f, wordWrap, GRAY); DrawRectangleRec(resizer, borderColor); // Draw the resize box @@ -106,13 +106,13 @@ int main() DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/text/text_sprite_fonts.c b/examples/text/text_sprite_fonts.c index 7ce2fef5..30028937 100644 --- a/examples/text/text_sprite_fonts.c +++ b/examples/text/text_sprite_fonts.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite fonts usage"); @@ -40,6 +40,7 @@ int main() fontPosition3.x = screenWidth/2 - MeasureTextEx(font3, msg3, font3.baseSize, 2).x/2; fontPosition3.y = screenHeight/2 - font3.baseSize/2 + 50; + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop diff --git a/examples/text/text_ttf_loading.c b/examples/text/text_ttf_loading.c index 0e964ebd..cc59417d 100644 --- a/examples/text/text_ttf_loading.c +++ b/examples/text/text_ttf_loading.c @@ -11,22 +11,22 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - ttf loading"); - + const char msg[50] = "TTF Font"; // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) - + // TTF Font loading with custom generation parameters Font font = LoadFontEx("resources/KAISG.ttf", 96, 0, 0); - + // Generate mipmap levels to use trilinear filtering // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR GenTextureMipmaps(&font.texture); @@ -35,25 +35,20 @@ int main() Vector2 fontPosition = { 40, screenHeight/2 - 80 }; Vector2 textSize; + // Setup texture scaling filter SetTextureFilter(font.texture, FILTER_POINT); int currentFontFilter = 0; // FILTER_POINT - - // NOTE: Drag and drop support only available for desktop platforms: Windows, Linux, OSX -#if defined(PLATFORM_DESKTOP) - int count = 0; - char **droppedFiles; -#endif - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- fontSize += GetMouseWheelMove()*4.0f; - + // Choose font texture filter method if (IsKeyPressed(KEY_ONE)) { @@ -71,18 +66,18 @@ int main() SetTextureFilter(font.texture, FILTER_TRILINEAR); currentFontFilter = 2; } - + textSize = MeasureTextEx(font, msg, fontSize, 0); - + if (IsKeyDown(KEY_LEFT)) fontPosition.x -= 10; else if (IsKeyDown(KEY_RIGHT)) fontPosition.x += 10; - -#if defined(PLATFORM_DESKTOP) + // Load a dropped TTF file dynamically (at current fontSize) if (IsFileDropped()) { - droppedFiles = GetDroppedFiles(&count); - + int count = 0; + char **droppedFiles = GetDroppedFiles(&count); + if (count == 1) // Only support one ttf file dropped { UnloadFont(font); @@ -90,47 +85,45 @@ int main() ClearDroppedFiles(); } } -#endif //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawText("Use mouse wheel to change font size", 20, 20, 10, GRAY); DrawText("Use KEY_RIGHT and KEY_LEFT to move text", 20, 40, 10, GRAY); DrawText("Use 1, 2, 3 to change texture filter", 20, 60, 10, GRAY); DrawText("Drop a new TTF font for dynamic loading", 20, 80, 10, DARKGRAY); DrawTextEx(font, msg, fontPosition, fontSize, 0, BLACK); - + // TODO: It seems texSize measurement is not accurate due to chars offsets... //DrawRectangleLines(fontPosition.x, fontPosition.y, textSize.x, textSize.y, RED); - + DrawRectangle(0, screenHeight - 80, screenWidth, 80, LIGHTGRAY); DrawText(FormatText("Font size: %02.02f", fontSize), 20, screenHeight - 50, 10, DARKGRAY); DrawText(FormatText("Text size: [%02.02f, %02.02f]", textSize.x, textSize.y), 20, screenHeight - 30, 10, DARKGRAY); DrawText("CURRENT TEXTURE FILTER:", 250, 400, 20, GRAY); - + if (currentFontFilter == 0) DrawText("POINT", 570, 400, 20, BLACK); else if (currentFontFilter == 1) DrawText("BILINEAR", 570, 400, 20, BLACK); else if (currentFontFilter == 2) DrawText("TRILINEAR", 570, 400, 20, BLACK); - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- -#if defined(PLATFORM_DESKTOP) ClearDroppedFiles(); // Clear internal buffers -#endif - UnloadFont(font); // Font unloading - + + UnloadFont(font); // Font unloading + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/text/text_unicode.c b/examples/text/text_unicode.c index f3c2612c..3525f01a 100644 --- a/examples/text/text_unicode.c +++ b/examples/text/text_unicode.c @@ -139,15 +139,12 @@ static void RandomizeEmoji(void); // Fills the emoji array with random emojis // Arrays that holds the random emojis struct { int index; // Index inside `emojiCodepoints` - int message; // Message index + int message; // Message index Color color; // Emoji color } emoji[EMOJI_PER_WIDTH*EMOJI_PER_HEIGHT] = { 0 }; static int hovered = -1, selected = -1; -//-------------------------------------------------------------------------------------- -// Main entry point -//-------------------------------------------------------------------------------------- int main(int argc, char **argv) { // Initialization @@ -159,23 +156,23 @@ int main(int argc, char **argv) InitWindow(screenWidth, screenHeight, "raylib [text] example - unicode"); // Load the font resources - // NOTE: fontAsian is for asian languages, - // fontEmoji is the emojis and fontDefault is used for everything else + // NOTE: fontAsian is for asian languages, + // fontEmoji is the emojis and fontDefault is used for everything else Font fontDefault = LoadFont("resources/dejavu.fnt"); Font fontAsian = LoadFont("resources/notoCJK.fnt"); Font fontEmoji = LoadFont("resources/emoji.fnt"); - + Vector2 hoveredPos = { 0.0f, 0.0f }; Vector2 selectedPos = { 0.0f, 0.0f }; // Set a random set of emojis when starting up RandomizeEmoji(); - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- - + // Main loop - while (!WindowShouldClose()) + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- @@ -189,89 +186,89 @@ int main(int argc, char **argv) selectedPos = hoveredPos; SetClipboardText(messages[emoji[selected].message].text); } - + Vector2 mouse = GetMousePosition(); Vector2 pos = { 28.8f, 10.0f }; hovered = -1; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + // Draw random emojis in the background //------------------------------------------------------------------------------ for (int i = 0; i < SIZEOF(emoji); ++i) { const char *txt = &emojiCodepoints[emoji[i].index]; Rectangle emojiRect = { pos.x, pos.y, fontEmoji.baseSize, fontEmoji.baseSize }; - + if (!CheckCollisionPointRec(mouse, emojiRect)) { DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, selected == i ? emoji[i].color : Fade(LIGHTGRAY, 0.4f)); } - else + else { DrawTextEx(fontEmoji, txt, pos, fontEmoji.baseSize, 1.0, emoji[i].color ); hovered = i; hoveredPos = pos; } - + if ((i != 0) && (i%EMOJI_PER_WIDTH == 0)) { pos.y += fontEmoji.baseSize + 24.25f; pos.x = 28.8f; } else pos.x += fontEmoji.baseSize + 28.8f; } //------------------------------------------------------------------------------ - + // Draw the message when a emoji is selected //------------------------------------------------------------------------------ - if (selected != -1) + if (selected != -1) { const int message = emoji[selected].message; const int horizontalPadding = 20, verticalPadding = 30; Font *font = &fontDefault; - + // Set correct font for asian languages - if (TextIsEqual(messages[message].language, "Chinese") || - TextIsEqual(messages[message].language, "Korean") || + if (TextIsEqual(messages[message].language, "Chinese") || + TextIsEqual(messages[message].language, "Korean") || TextIsEqual(messages[message].language, "Japanese")) font = &fontAsian; - + // Calculate size for the message box (approximate the height and width) Vector2 sz = MeasureTextEx(*font, messages[message].text, font->baseSize, 1.0f); - if (sz.x > 300) { sz.y *= sz.x/300; sz.x = 300; } + if (sz.x > 300) { sz.y *= sz.x/300; sz.x = 300; } else if (sz.x < 160) sz.x = 160; - + Rectangle msgRect = { selectedPos.x - 38.8f, selectedPos.y, 2 * horizontalPadding + sz.x, 2 * verticalPadding + sz.y }; msgRect.y -= msgRect.height; - + // Coordinates for the chat bubble triangle Vector2 a = { selectedPos.x, msgRect.y + msgRect.height }, b = {a.x + 8, a.y + 10}, c= { a.x + 10, a.y }; - + // Don't go outside the screen if (msgRect.x < 10) msgRect.x += 28; - if (msgRect.y < 10) + if (msgRect.y < 10) { msgRect.y = selectedPos.y + 84; a.y = msgRect.y; c.y = a.y; b.y = a.y - 10; - + // Swap values so we can actually render the triangle :( Vector2 tmp = a; a = b; b = tmp; } if (msgRect.x + msgRect.width > screenWidth) msgRect.x -= (msgRect.x + msgRect.width) - screenWidth + 10; - + // Draw chat bubble DrawRectangleRec(msgRect, emoji[selected].color); DrawTriangle(a, b, c, emoji[selected].color); - + // Draw the main text message Rectangle textRect = { msgRect.x + horizontalPadding/2, msgRect.y + verticalPadding/2, msgRect.width - horizontalPadding, msgRect.height }; DrawTextRec(*font, messages[message].text, textRect, font->baseSize, 1.0f, true, WHITE); - + // Draw the info text below the main message int size = strlen(messages[message].text); unsigned int len = TextCountCodepoints(messages[message].text); @@ -281,25 +278,25 @@ int main(int argc, char **argv) DrawText(info, pos.x, pos.y, 10, RAYWHITE); } //------------------------------------------------------------------------------ - + // Draw the info text DrawText("These emojis have something to tell you, click each to find out!", (screenWidth - 650)/2, screenHeight - 40, 20, GRAY); DrawText("Each emoji is a unicode character from a font, not a texture... Press [SPACEBAR] to refresh", (screenWidth - 484)/2, screenHeight - 16, 10, GRAY); - - EndDrawing(); + + EndDrawing(); //---------------------------------------------------------------------------------- - } - + } + // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- UnloadFont(fontDefault); // Unload font resource UnloadFont(fontAsian); // Unload font resource UnloadFont(fontEmoji); // Unload font resource - - CloseWindow(); // Close window and OpenGL context - //-------------------------------------------------------------------------------------- - return 0; + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; } // Fills the emoji array with random emoji (only those emojis present in fontEmoji) @@ -307,16 +304,16 @@ static void RandomizeEmoji(void) { hovered = selected = -1; int start = GetRandomValue(45, 360); - + for (int i = 0; i < SIZEOF(emoji); ++i) { // 0-179 emoji codepoints (from emoji char array) each 4bytes + null char emoji[i].index = GetRandomValue(0, 179)*5; - + // Generate a random color for this emoji Vector3 hsv = {(start*(i + 1))%360, 0.6f, 0.85f}; emoji[i].color = Fade(ColorFromHSV(hsv), 0.8f); - + // Set a random message for this emoji emoji[i].message = GetRandomValue(0, SIZEOF(messages) - 1); } diff --git a/examples/text/text_writing_anim.c b/examples/text/text_writing_anim.c index b2aba697..2cf2eaa2 100644 --- a/examples/text/text_writing_anim.c +++ b/examples/text/text_writing_anim.c @@ -11,20 +11,20 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [text] example - text writing anim"); - + const char message[128] = "This sample illustrates a text writing\nanimation effect! Check it out! ;)"; - + int framesCounter = 0; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -34,7 +34,7 @@ int main() //---------------------------------------------------------------------------------- if (IsKeyDown(KEY_SPACE)) framesCounter += 8; else framesCounter++; - + if (IsKeyPressed(KEY_ENTER)) framesCounter = 0; //---------------------------------------------------------------------------------- @@ -45,7 +45,7 @@ int main() ClearBackground(RAYWHITE); DrawText(TextSubtext(message, 0, framesCounter/10), 210, 160, 20, MAROON); - + DrawText("PRESS [ENTER] to RESTART!", 240, 260, 20, LIGHTGRAY); DrawText("PRESS [SPACE] to SPEED UP!", 239, 300, 20, LIGHTGRAY); @@ -54,7 +54,7 @@ int main() } // De-Initialization - //-------------------------------------------------------------------------------------- + //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/textures/textures_background_scrolling.c b/examples/textures/textures_background_scrolling.c index 2be0810a..d91b2585 100644 --- a/examples/textures/textures_background_scrolling.c +++ b/examples/textures/textures_background_scrolling.c @@ -11,26 +11,26 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - background scrolling"); - + // NOTE: Be careful, background width must be equal or bigger than screen width // if not, texture should be draw more than two times for scrolling effect Texture2D background = LoadTexture("resources/cyberpunk_street_background.png"); Texture2D midground = LoadTexture("resources/cyberpunk_street_midground.png"); Texture2D foreground = LoadTexture("resources/cyberpunk_street_foreground.png"); - + float scrollingBack = 0; float scrollingMid = 0; float scrollingFore = 0; - - SetTargetFPS(60); + + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -41,7 +41,7 @@ int main() scrollingBack -= 0.1f; scrollingMid -= 0.5f; scrollingFore -= 1.0f; - + // NOTE: Texture is scaled twice its size, so it sould be considered on scrolling if (scrollingBack <= -background.width*2) scrollingBack = 0; if (scrollingMid <= -midground.width*2) scrollingMid = 0; @@ -58,15 +58,15 @@ int main() // NOTE: Texture is scaled twice its size DrawTextureEx(background, (Vector2){ scrollingBack, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(background, (Vector2){ background.width*2 + scrollingBack, 20 }, 0.0f, 2.0f, WHITE); - + // Draw midground image twice DrawTextureEx(midground, (Vector2){ scrollingMid, 20 }, 0.0f, 2.0f, WHITE); DrawTextureEx(midground, (Vector2){ midground.width*2 + scrollingMid, 20 }, 0.0f, 2.0f, WHITE); - + // Draw foreground image twice DrawTextureEx(foreground, (Vector2){ scrollingFore, 70 }, 0.0f, 2.0f, WHITE); DrawTextureEx(foreground, (Vector2){ foreground.width*2 + scrollingFore, 70 }, 0.0f, 2.0f, WHITE); - + DrawText("BACKGROUND SCROLLING & PARALLAX", 10, 10, 20, RED); DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", screenWidth - 330, screenHeight - 20, 10, RAYWHITE); diff --git a/examples/textures/textures_bunnymark.c b/examples/textures/textures_bunnymark.c index 76078838..6b91d646 100644 --- a/examples/textures/textures_bunnymark.c +++ b/examples/textures/textures_bunnymark.c @@ -25,7 +25,7 @@ typedef struct Bunny { Color color; } Bunny; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- @@ -34,13 +34,14 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [textures] example - bunnymark"); + // Load bunny texture Texture2D texBunny = LoadTexture("resources/wabbit_alpha.png"); - Bunny *bunnies = (Bunny *)malloc(MAX_BUNNIES*sizeof(Bunny)); // Bunnies array + Bunny *bunnies = (Bunny *)malloc(MAX_BUNNIES*sizeof(Bunny)); // Bunnies array - int bunniesCount = 0; // Bunnies counter + int bunniesCount = 0; // Bunnies counter - SetTargetFPS(60); + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop @@ -56,8 +57,8 @@ int main() bunnies[bunniesCount].position = GetMousePosition(); bunnies[bunniesCount].speed.x = (float)GetRandomValue(-250, 250)/60.0f; bunnies[bunniesCount].speed.y = (float)GetRandomValue(-250, 250)/60.0f; - bunnies[bunniesCount].color = (Color){ GetRandomValue(50, 240), - GetRandomValue(80, 240), + bunnies[bunniesCount].color = (Color){ GetRandomValue(50, 240), + GetRandomValue(80, 240), GetRandomValue(100, 240), 255 }; bunniesCount++; } @@ -69,9 +70,9 @@ int main() bunnies[i].position.x += bunnies[i].speed.x; bunnies[i].position.y += bunnies[i].speed.y; - if (((bunnies[i].position.x + texBunny.width/2) > GetScreenWidth()) || + if (((bunnies[i].position.x + texBunny.width/2) > GetScreenWidth()) || ((bunnies[i].position.x + texBunny.width/2) < 0)) bunnies[i].speed.x *= -1; - if (((bunnies[i].position.y + texBunny.height/2) > GetScreenHeight()) || + if (((bunnies[i].position.y + texBunny.height/2) > GetScreenHeight()) || ((bunnies[i].position.y + texBunny.height/2 - 40) < 0)) bunnies[i].speed.y *= -1; } //---------------------------------------------------------------------------------- @@ -84,9 +85,9 @@ int main() for (int i = 0; i < bunniesCount; i++) { - // NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), + // NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), // a draw call is launched and buffer starts being filled again; - // before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... + // before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... // Process of sending data is costly and it could happen that GPU data has not been completely // processed for drawing while new data is tried to be sent (updating current in-use buffers) // it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies @@ -96,7 +97,7 @@ int main() DrawRectangle(0, 0, screenWidth, 40, BLACK); DrawText(FormatText("bunnies: %i", bunniesCount), 120, 10, 20, GREEN); DrawText(FormatText("batched draw calls: %i", 1 + bunniesCount/MAX_BATCH_ELEMENTS), 320, 10, 20, MAROON); - + DrawFPS(10, 10); EndDrawing(); @@ -106,7 +107,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- free(bunnies); // Unload bunnies data array - + UnloadTexture(texBunny); // Unload bunny texture CloseWindow(); // Close window and OpenGL context diff --git a/examples/textures/textures_image_drawing.c b/examples/textures/textures_image_drawing.c index b179612d..f5c3c85d 100644 --- a/examples/textures/textures_image_drawing.c +++ b/examples/textures/textures_image_drawing.c @@ -13,12 +13,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - image drawing"); @@ -28,26 +28,26 @@ int main() ImageCrop(&cat, (Rectangle){ 100, 10, 280, 380 }); // Crop an image piece ImageFlipHorizontal(&cat); // Flip cropped image horizontally ImageResize(&cat, 150, 200); // Resize flipped-cropped image - + Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM) - + // Draw one image over the other with a scaling of 1.5f ImageDraw(&parrots, cat, (Rectangle){ 0, 0, cat.width, cat.height }, (Rectangle){ 30, 40, cat.width*1.5f, cat.height*1.5f }); ImageCrop(&parrots, (Rectangle){ 0, 50, parrots.width, parrots.height - 100 }); // Crop resulting image - + UnloadImage(cat); // Unload image from RAM - + // Load custom font for frawing on image Font font = LoadFont("resources/custom_jupiter_crash.png"); - + // Draw over image using custom font ImageDrawTextEx(&parrots, (Vector2){ 300, 230 }, font, "PARROTS & CAT", font.baseSize, -2, WHITE); - + UnloadFont(font); // Unload custom spritefont (already drawn used on image) Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM) UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM - + SetTargetFPS(60); //--------------------------------------------------------------------------------------- diff --git a/examples/textures/textures_image_generation.c b/examples/textures/textures_image_generation.c index b9608c89..d9a39a25 100644 --- a/examples/textures/textures_image_generation.c +++ b/examples/textures/textures_image_generation.c @@ -13,12 +13,12 @@ #define NUM_TEXTURES 7 // Currently we have 7 generation algorithms -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - procedural images generation"); @@ -38,7 +38,7 @@ int main() textures[4] = LoadTextureFromImage(whiteNoise); textures[5] = LoadTextureFromImage(perlinNoise); textures[6] = LoadTextureFromImage(cellular); - + // Unload image data (CPU RAM) UnloadImage(verticalGradient); UnloadImage(horizontalGradient); @@ -49,10 +49,10 @@ int main() UnloadImage(cellular); int currentTexture = 0; - + SetTargetFPS(60); //--------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) { @@ -67,15 +67,15 @@ int main() // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + DrawTexture(textures[currentTexture], 0, 0, WHITE); - + DrawRectangle(30, 400, 325, 30, Fade(SKYBLUE, 0.5f)); DrawRectangleLines(30, 400, 325, 30, Fade(WHITE, 0.5f)); DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL TEXTURES", 40, 410, 10, WHITE); - + switch(currentTexture) { case 0: DrawText("VERTICAL GRADIENT", 560, 10, 20, RAYWHITE); break; @@ -87,19 +87,19 @@ int main() case 6: DrawText("CELLULAR", 670, 10, 20, RAYWHITE); break; default: break; } - + EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- - + // Unload textures data (GPU VRAM) for (int i = 0; i < NUM_TEXTURES; i++) UnloadTexture(textures[i]); - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } diff --git a/examples/textures/textures_image_loading.c b/examples/textures/textures_image_loading.c index 54c73586..265cab44 100644 --- a/examples/textures/textures_image_loading.c +++ b/examples/textures/textures_image_loading.c @@ -13,12 +13,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - image loading"); diff --git a/examples/textures/textures_image_processing.c b/examples/textures/textures_image_processing.c index 6d33d95b..b9ed51d7 100644 --- a/examples/textures/textures_image_processing.c +++ b/examples/textures/textures_image_processing.c @@ -13,19 +13,19 @@ #include "raylib.h" -#include // Required for: free() +#include // Required for: free() #define NUM_PROCESSES 8 -typedef enum { - NONE = 0, - COLOR_GRAYSCALE, - COLOR_TINT, - COLOR_INVERT, - COLOR_CONTRAST, - COLOR_BRIGHTNESS, - FLIP_VERTICAL, - FLIP_HORIZONTAL +typedef enum { + NONE = 0, + COLOR_GRAYSCALE, + COLOR_TINT, + COLOR_INVERT, + COLOR_CONTRAST, + COLOR_BRIGHTNESS, + FLIP_VERTICAL, + FLIP_HORIZONTAL } ImageProcess; static const char *processText[] = { @@ -39,12 +39,12 @@ static const char *processText[] = { "FLIP HORIZONTAL" }; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - image processing"); @@ -58,9 +58,9 @@ int main() bool textureReload = false; Rectangle selectRecs[NUM_PROCESSES]; - + for (int i = 0; i < NUM_PROCESSES; i++) selectRecs[i] = (Rectangle){ 40.0f, (float)(50 + 32*i), 150.0f, 30.0f }; - + SetTargetFPS(60); //--------------------------------------------------------------------------------------- @@ -81,14 +81,14 @@ int main() if (currentProcess < 0) currentProcess = 7; textureReload = true; } - + if (textureReload) { UnloadImage(image); // Unload current image data image = LoadImage("resources/parrots.png"); // Re-load image data - // NOTE: Image processing is a costly CPU process to be done every frame, - // If image processing is required in a frame-basis, it should be done + // NOTE: Image processing is a costly CPU process to be done every frame, + // If image processing is required in a frame-basis, it should be done // with a texture and by shaders switch (currentProcess) { @@ -101,11 +101,11 @@ int main() case FLIP_HORIZONTAL: ImageFlipHorizontal(&image); break; default: break; } - + Color *pixels = GetImageData(image); // Get pixel data from image (RGBA 32bit) UpdateTexture(texture, pixels); // Update texture with new image data free(pixels); // Unload pixels data from RAM - + textureReload = false; } //---------------------------------------------------------------------------------- @@ -115,9 +115,9 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); - + DrawText("IMAGE PROCESSING:", 40, 30, 10, DARKGRAY); - + // Draw rectangles for (int i = 0; i < NUM_PROCESSES; i++) { @@ -128,7 +128,7 @@ int main() DrawTexture(texture, screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, WHITE); DrawRectangleLines(screenWidth - texture.width - 60, screenHeight/2 - texture.height/2, texture.width, texture.height, BLACK); - + EndDrawing(); //---------------------------------------------------------------------------------- } diff --git a/examples/textures/textures_image_text.c b/examples/textures/textures_image_text.c index ce91fbf2..c8dfe458 100644 --- a/examples/textures/textures_image_text.c +++ b/examples/textures/textures_image_text.c @@ -11,28 +11,28 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [texture] example - image text drawing"); + Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM) + // TTF Font loading with custom generation parameters Font font = LoadFontEx("resources/KAISG.ttf", 64, 0, 0); - - Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM) // Draw over image using custom font ImageDrawTextEx(&parrots, (Vector2){ 20.0f, 20.0f }, font, "[Parrots font drawing]", (float)font.baseSize, 0.0f, RED); Texture2D texture = LoadTextureFromImage(parrots); // Image converted to texture, uploaded to GPU memory (VRAM) UnloadImage(parrots); // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM - + Vector2 position = { (float)(screenWidth/2 - texture.width/2), (float)(screenHeight/2 - texture.height/2 - 20) }; - + bool showFont = false; SetTargetFPS(60); @@ -57,15 +57,15 @@ int main() { // Draw texture with text already drawn inside DrawTextureV(texture, position, WHITE); - + // Draw text directly using sprite font - DrawTextEx(font, "[Parrots font drawing]", (Vector2){ position.x + 20, + DrawTextEx(font, "[Parrots font drawing]", (Vector2){ position.x + 20, position.y + 20 + 280 }, (float)font.baseSize, 0.0f, WHITE); } else DrawTexture(font.texture, screenWidth/2 - font.texture.width/2, 50, BLACK); - + DrawText("PRESS SPACE to SEE USED SPRITEFONT ", 290, 420, 10, DARKGRAY); - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -73,9 +73,9 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- UnloadTexture(texture); // Texture unloading - - UnloadFont(font); // Unload custom spritefont - + + UnloadFont(font); // Unload custom spritefont + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/textures/textures_logo_raylib.c b/examples/textures/textures_logo_raylib.c index f2f93128..de8bb2ae 100644 --- a/examples/textures/textures_logo_raylib.c +++ b/examples/textures/textures_logo_raylib.c @@ -11,12 +11,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture loading and drawing"); diff --git a/examples/textures/textures_npatch_drawing.c b/examples/textures/textures_npatch_drawing.c index 0514efe7..1c57e2e7 100644 --- a/examples/textures/textures_npatch_drawing.c +++ b/examples/textures/textures_npatch_drawing.c @@ -15,18 +15,18 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - N-patch drawing"); // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) Texture2D nPatchTexture = LoadTexture("resources/ninepatch_button.png"); - + Vector2 mousePosition = { 0 }; Vector2 origin = { 0.0f, 0.0f }; @@ -39,13 +39,13 @@ int main() // A 9-patch (NPT_9PATCH) changes its sizes in both axis NPatchInfo ninePatchInfo1 = { (Rectangle){ 0.0f, 0.0f, 64.0f, 64.0f }, 12, 40, 12, 12, NPT_9PATCH }; NPatchInfo ninePatchInfo2 = { (Rectangle){ 0.0f, 128.0f, 64.0f, 64.0f }, 16, 16, 16, 16, NPT_9PATCH }; - + // A horizontal 3-patch (NPT_3PATCH_HORIZONTAL) changes its sizes along the x axis only NPatchInfo h3PatchInfo = { (Rectangle){ 0.0f, 64.0f, 64.0f, 64.0f }, 8, 8, 8, 8, NPT_3PATCH_HORIZONTAL }; - + // A vertical 3-patch (NPT_3PATCH_VERTICAL) changes its sizes along the y axis only NPatchInfo v3PatchInfo = { (Rectangle){ 0.0f, 192.0f, 64.0f, 64.0f }, 6, 6, 6, 6, NPT_3PATCH_VERTICAL }; - + SetTargetFPS(60); //--------------------------------------------------------------------------------------- @@ -55,7 +55,7 @@ int main() // Update //---------------------------------------------------------------------------------- mousePosition = GetMousePosition(); - + // Resize the n-patches based on mouse position dstRec1.width = mousePosition.x - dstRec1.x; dstRec1.height = mousePosition.y - dstRec1.y; @@ -86,7 +86,7 @@ int main() DrawTextureNPatch(nPatchTexture, ninePatchInfo1, dstRec1, origin, 0.0f, WHITE); DrawTextureNPatch(nPatchTexture, h3PatchInfo, dstRecH, origin, 0.0f, WHITE); DrawTextureNPatch(nPatchTexture, v3PatchInfo, dstRecV, origin, 0.0f, WHITE); - + // Draw the source texture DrawRectangleLines(5, 88, 74, 266, BLUE); DrawTexture(nPatchTexture, 10, 93, WHITE); diff --git a/examples/textures/textures_particles_blending.c b/examples/textures/textures_particles_blending.c index 3b7dcaa3..75287ea7 100644 --- a/examples/textures/textures_particles_blending.c +++ b/examples/textures/textures_particles_blending.c @@ -23,18 +23,18 @@ typedef struct { bool active; // NOTE: Use it to activate/deactive particle } Particle; -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - particles blending"); - + // Particles pool, reuse them! - Particle mouseTail[MAX_PARTICLES]; - + Particle mouseTail[MAX_PARTICLES]; + // Initialize particles for (int i = 0; i < MAX_PARTICLES; i++) { @@ -45,13 +45,13 @@ int main() mouseTail[i].rotation = (float)GetRandomValue(0, 360); mouseTail[i].active = false; } - + float gravity = 3.0f; Texture2D smoke = LoadTexture("resources/smoke.png"); - + int blending = BLEND_ALPHA; - + SetTargetFPS(60); //-------------------------------------------------------------------------------------- @@ -60,7 +60,7 @@ int main() { // Update //---------------------------------------------------------------------------------- - + // Activate one particle every frame and Update active particles // NOTE: Particles initial position should be mouse position when activated // NOTE: Particles fall down with gravity and rotation... and disappear after 2 seconds (alpha = 0) @@ -82,13 +82,13 @@ int main() { mouseTail[i].position.y += gravity; mouseTail[i].alpha -= 0.01f; - + if (mouseTail[i].alpha <= 0.0f) mouseTail[i].active = false; - + mouseTail[i].rotation += 5.0f; } } - + if (IsKeyPressed(KEY_SPACE)) { if (blending == BLEND_ALPHA) blending = BLEND_ADDITIVE; @@ -101,25 +101,25 @@ int main() BeginDrawing(); ClearBackground(DARKGRAY); - + BeginBlendMode(blending); // Draw active particles for (int i = 0; i < MAX_PARTICLES; i++) { - if (mouseTail[i].active) DrawTexturePro(smoke, (Rectangle){ 0.0f, 0.0f, (float)smoke.width, (float)smoke.height }, + if (mouseTail[i].active) DrawTexturePro(smoke, (Rectangle){ 0.0f, 0.0f, (float)smoke.width, (float)smoke.height }, (Rectangle){ mouseTail[i].position.x, mouseTail[i].position.y, smoke.width*mouseTail[i].size, smoke.height*mouseTail[i].size }, (Vector2){ (float)(smoke.width*mouseTail[i].size/2.0f), (float)(smoke.height*mouseTail[i].size/2.0f) }, mouseTail[i].rotation, Fade(mouseTail[i].color, mouseTail[i].alpha)); } - + EndBlendMode(); - + DrawText("PRESS SPACE to CHANGE BLENDING MODE", 180, 20, 20, BLACK); - + if (blending == BLEND_ALPHA) DrawText("ALPHA BLENDING", 290, screenHeight - 40, 20, BLACK); else DrawText("ADDITIVE BLENDING", 280, screenHeight - 40, 20, RAYWHITE); - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -127,7 +127,7 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- UnloadTexture(smoke); - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- diff --git a/examples/textures/textures_raw_data.c b/examples/textures/textures_raw_data.c index 481bd66a..17604bde 100644 --- a/examples/textures/textures_raw_data.c +++ b/examples/textures/textures_raw_data.c @@ -13,31 +13,31 @@ #include "raylib.h" -#include // Required for malloc() and free() +#include // Required for: malloc() and free() -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture from raw data"); // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) - + // Load RAW image data (512x512, 32bit RGBA, no file header) Image fudesumiRaw = LoadImageRaw("resources/fudesumi.raw", 384, 512, UNCOMPRESSED_R8G8B8A8, 0); - Texture2D fudesumi = LoadTextureFromImage(fudesumiRaw); // Upload CPU (RAM) image to GPU (VRAM) - UnloadImage(fudesumiRaw); // Unload CPU (RAM) image data - + Texture2D fudesumi = LoadTextureFromImage(fudesumiRaw); // Upload CPU (RAM) image to GPU (VRAM) + UnloadImage(fudesumiRaw); // Unload CPU (RAM) image data + // Generate a checked texture by code (1024x1024 pixels) int width = 960; int height = 480; - + // Dynamic memory allocation to store pixels data (Color type) Color *pixels = (Color *)malloc(width*height*sizeof(Color)); - + for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) @@ -46,14 +46,14 @@ int main() else pixels[y*width + x] = GOLD; } } - + // Load pixels data into an image structure and create texture Image checkedIm = LoadImageEx(pixels, width, height); Texture2D checked = LoadTextureFromImage(checkedIm); - UnloadImage(checkedIm); // Unload CPU (RAM) image data - + UnloadImage(checkedIm); // Unload CPU (RAM) image data + // Dynamic memory must be freed after using it - free(pixels); // Unload CPU (RAM) pixels data + free(pixels); // Unload CPU (RAM) pixels data //--------------------------------------------------------------------------------------- // Main game loop @@ -76,7 +76,7 @@ int main() DrawText("CHECKED TEXTURE ", 84, 85, 30, BROWN); DrawText("GENERATED by CODE", 72, 148, 30, BROWN); DrawText("and RAW IMAGE LOADING", 46, 210, 30, BROWN); - + DrawText("(c) Fudesumi sprite by Eiden Marsal", 310, screenHeight - 20, 10, BROWN); EndDrawing(); diff --git a/examples/textures/textures_rectangle.c b/examples/textures/textures_rectangle.c index e1247746..8be647a2 100644 --- a/examples/textures/textures_rectangle.c +++ b/examples/textures/textures_rectangle.c @@ -14,12 +14,12 @@ #define MAX_FRAME_SPEED 15 #define MIN_FRAME_SPEED 1 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [texture] example - texture rectangle"); @@ -29,10 +29,10 @@ int main() Vector2 position = { 350.0f, 280.0f }; Rectangle frameRec = { 0.0f, 0.0f, (float)scarfy.width/6, (float)scarfy.height }; int currentFrame = 0; - + int framesCounter = 0; - int framesSpeed = 8; // Number of spritesheet frames shown by second - + int framesSpeed = 8; // Number of spritesheet frames shown by second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- @@ -42,20 +42,20 @@ int main() // Update //---------------------------------------------------------------------------------- framesCounter++; - + if (framesCounter >= (60/framesSpeed)) { framesCounter = 0; currentFrame++; - + if (currentFrame > 5) currentFrame = 0; - + frameRec.x = (float)currentFrame*(float)scarfy.width/6; } - + if (IsKeyPressed(KEY_RIGHT)) framesSpeed++; else if (IsKeyPressed(KEY_LEFT)) framesSpeed--; - + if (framesSpeed > MAX_FRAME_SPEED) framesSpeed = MAX_FRAME_SPEED; else if (framesSpeed < MIN_FRAME_SPEED) framesSpeed = MIN_FRAME_SPEED; //---------------------------------------------------------------------------------- @@ -69,17 +69,17 @@ int main() DrawTexture(scarfy, 15, 40, WHITE); DrawRectangleLines(15, 40, scarfy.width, scarfy.height, LIME); DrawRectangleLines(15 + frameRec.x, 40 + frameRec.y, frameRec.width, frameRec.height, RED); - + DrawText("FRAME SPEED: ", 165, 210, 10, DARKGRAY); DrawText(FormatText("%02i FPS", framesSpeed), 575, 210, 10, DARKGRAY); DrawText("PRESS RIGHT/LEFT KEYS to CHANGE SPEED!", 290, 240, 10, DARKGRAY); - + for (int i = 0; i < MAX_FRAME_SPEED; i++) { if (i < framesSpeed) DrawRectangle(250 + 21*i, 205, 20, 20, RED); DrawRectangleLines(250 + 21*i, 205, 20, 20, MAROON); } - + DrawTextureRec(scarfy, frameRec, position, WHITE); // Draw part of the texture DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY); diff --git a/examples/textures/textures_sprite_button.c b/examples/textures/textures_sprite_button.c index bbd57328..a5b2d8d1 100644 --- a/examples/textures/textures_sprite_button.c +++ b/examples/textures/textures_sprite_button.c @@ -13,35 +13,35 @@ #define NUM_FRAMES 3 // Number of frames (rectangles) for the button sprite texture -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; - + InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite button"); InitAudioDevice(); // Initialize audio device - + Sound fxButton = LoadSound("resources/buttonfx.wav"); // Load button sound Texture2D button = LoadTexture("resources/button.png"); // Load button texture - + // Define frame rectangle for drawing int frameHeight = button.height/NUM_FRAMES; Rectangle sourceRec = { 0, 0, button.width, frameHeight }; - + // Define button bounds on screen Rectangle btnBounds = { screenWidth/2 - button.width/2, screenHeight/2 - button.height/NUM_FRAMES/2, button.width, frameHeight }; - + int btnState = 0; // Button state: 0-NORMAL, 1-MOUSE_HOVER, 2-PRESSED bool btnAction = false; // Button action should be activated - + Vector2 mousePoint = { 0.0f, 0.0f }; - + SetTargetFPS(60); //-------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { @@ -49,7 +49,7 @@ int main() //---------------------------------------------------------------------------------- mousePoint = GetMousePosition(); btnAction = false; - + // Check button state if (CheckCollisionPointRec(mousePoint, btnBounds)) { @@ -59,26 +59,26 @@ int main() if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) btnAction = true; } else btnState = 0; - + if (btnAction) { PlaySound(fxButton); - + // TODO: Any desired action } - + // Calculate button frame rectangle to draw depending on button state sourceRec.y = btnState*frameHeight; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); DrawTextureRec(button, sourceRec, (Vector2){ btnBounds.x, btnBounds.y }, WHITE); // Draw button frame - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -89,9 +89,9 @@ int main() UnloadSound(fxButton); // Unload sound CloseAudioDevice(); // Close audio device - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/textures/textures_sprite_explosion.c b/examples/textures/textures_sprite_explosion.c index 47c994b0..58a8f6fc 100644 --- a/examples/textures/textures_sprite_explosion.c +++ b/examples/textures/textures_sprite_explosion.c @@ -11,23 +11,23 @@ #include "raylib.h" -#define NUM_FRAMES 8 -#define NUM_LINES 6 +#define NUM_FRAMES 8 +#define NUM_LINES 6 -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- const int screenWidth = 800; const int screenHeight = 450; - + InitWindow(screenWidth, screenHeight, "raylib [textures] example - sprite explosion"); - + InitAudioDevice(); - + // Load explosion sound Sound fxBoom = LoadSound("resources/boom.wav"); - + // Load explosion texture Texture2D explosion = LoadTexture("resources/explosion.png"); @@ -36,72 +36,72 @@ int main() int frameHeight = explosion.height/NUM_LINES; // Sprite one frame rectangle height int currentFrame = 0; int currentLine = 0; - + Rectangle frameRec = { 0, 0, frameWidth, frameHeight }; Vector2 position = { 0, 0 }; - + bool active = false; int framesCounter = 0; - + SetTargetFPS(120); //-------------------------------------------------------------------------------------- - + // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- - + // Check for mouse button pressed and activate explosion (if not active) if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && !active) { position = GetMousePosition(); active = true; - + position.x -= frameWidth/2; position.y -= frameHeight/2; - + PlaySound(fxBoom); } - + // Compute explosion animation frames if (active) { framesCounter++; - + if (framesCounter > 2) { currentFrame++; - + if (currentFrame >= NUM_FRAMES) { currentFrame = 0; currentLine++; - + if (currentLine >= NUM_LINES) { currentLine = 0; active = false; } } - + framesCounter = 0; } } - + frameRec.x = frameWidth*currentFrame; frameRec.y = frameHeight*currentLine; //---------------------------------------------------------------------------------- - + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); - + ClearBackground(RAYWHITE); - + // Draw explosion required frame rectangle if (active) DrawTextureRec(explosion, frameRec, position, WHITE); - + EndDrawing(); //---------------------------------------------------------------------------------- } @@ -109,12 +109,12 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- UnloadTexture(explosion); // Unload texture - UnloadSound(fxBoom); // Unload sound - + UnloadSound(fxBoom); // Unload sound + CloseAudioDevice(); - + CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- - + return 0; } \ No newline at end of file diff --git a/examples/textures/textures_srcrec_dstrec.c b/examples/textures/textures_srcrec_dstrec.c index 298a0c65..e86b729d 100644 --- a/examples/textures/textures_srcrec_dstrec.c +++ b/examples/textures/textures_srcrec_dstrec.c @@ -11,32 +11,33 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] examples - texture source and destination rectangles"); // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) + Texture2D scarfy = LoadTexture("resources/scarfy.png"); // Texture loading int frameWidth = scarfy.width/6; int frameHeight = scarfy.height; - - // NOTE: Source rectangle (part of the texture to use for drawing) + + // Source rectangle (part of the texture to use for drawing) Rectangle sourceRec = { 0.0f, 0.0f, frameWidth, frameHeight }; - // NOTE: Destination rectangle (screen rectangle where drawing part of texture) + // Destination rectangle (screen rectangle where drawing part of texture) Rectangle destRec = { screenWidth/2, screenHeight/2, frameWidth*2, frameHeight*2 }; - // NOTE: Origin of the texture (rotation/scale point), it's relative to destination rectangle size + // Origin of the texture (rotation/scale point), it's relative to destination rectangle size Vector2 origin = { frameWidth, frameHeight }; - + int rotation = 0; - + SetTargetFPS(60); //-------------------------------------------------------------------------------------- @@ -63,7 +64,7 @@ int main() DrawLine((int)destRec.x, 0, (int)destRec.x, screenHeight, GRAY); DrawLine(0, (int)destRec.y, screenWidth, (int)destRec.y, GRAY); - + DrawText("(c) Scarfy sprite by Eiden Marsal", screenWidth - 200, screenHeight - 20, 10, GRAY); EndDrawing(); diff --git a/examples/textures/textures_to_image.c b/examples/textures/textures_to_image.c index 37c3b5a0..c0989baf 100644 --- a/examples/textures/textures_to_image.c +++ b/examples/textures/textures_to_image.c @@ -1,6 +1,6 @@ /******************************************************************************************* * -* raylib [textures] example - Retrieve image data from texture: GetTextureData() +* raylib [textures] example - Retrieve image data from texture: GetTextureData() * * NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM) * @@ -13,12 +13,12 @@ #include "raylib.h" -int main() +int main(void) { // Initialization //-------------------------------------------------------------------------------------- - int screenWidth = 800; - int screenHeight = 450; + const int screenWidth = 800; + const int screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib [textures] example - texture to image"); @@ -27,10 +27,10 @@ int main() Image image = LoadImage("resources/raylib_logo.png"); // Load image data into CPU memory (RAM) Texture2D texture = LoadTextureFromImage(image); // Image converted to texture, GPU memory (RAM -> VRAM) UnloadImage(image); // Unload image data from CPU memory (RAM) - + image = GetTextureData(texture); // Retrieve image data from GPU memory (VRAM -> RAM) UnloadTexture(texture); // Unload texture from GPU memory (VRAM) - + texture = LoadTextureFromImage(image); // Recreate texture from retrieved image data (RAM -> VRAM) UnloadImage(image); // Unload retrieved image data from CPU memory (RAM) //--------------------------------------------------------------------------------------- -- cgit v1.2.3 From e6ca2c4ba338fcb56949a3beb978a87803aa38b0 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 22 May 2019 09:57:17 +0200 Subject: Comment tweaks --- examples/models/models_mesh_picking.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_mesh_picking.c b/examples/models/models_mesh_picking.c index 26d9fa7e..0bf95dd1 100644 --- a/examples/models/models_mesh_picking.c +++ b/examples/models/models_mesh_picking.c @@ -5,8 +5,9 @@ * This example has been created using raylib 1.7 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2015 Ramon Santamaria (@raysan5) -* Example contributed by Joel Davis (@joeld42) +* Example contributed by Joel Davis (@joeld42) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2017 Joel Davis (@joeld42) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ -- cgit v1.2.3 From 87774a0a21f8d2998b4dc13e989005270476ae92 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 27 May 2019 00:18:15 +0200 Subject: Review variables initialization --- examples/audio/audio_module_playing.c | 2 +- examples/audio/audio_sound_loading.c | 1 - examples/core/core_2d_camera.c | 5 ++--- examples/core/core_3d_camera_first_person.c | 6 +++--- examples/core/core_3d_camera_free.c | 2 +- examples/core/core_custom_logging.c | 2 +- examples/core/core_vr_simulator.c | 2 +- examples/core/core_world_screen.c | 3 +-- examples/models/models_box_collisions.c | 2 +- examples/models/models_cubicmap.c | 2 +- examples/models/models_first_person_maze.c | 2 +- examples/models/models_heightmap.c | 2 +- examples/models/models_mesh_generation.c | 4 ++-- examples/models/models_obj_viewer.c | 2 +- examples/models/models_orthographic_projection.c | 2 +- examples/models/models_skybox.c | 2 +- examples/others/raudio_standalone.c | 2 +- examples/others/rlgl_standalone.c | 2 +- examples/physac/physics_friction.c | 4 ++-- examples/shaders/shaders_postprocessing.c | 4 ++-- examples/shapes/shapes_colors_palette.c | 2 +- examples/shapes/shapes_easings_rectangle_array.c | 2 +- examples/text/text_font_sdf.c | 2 +- examples/text/text_raylib_fonts.c | 4 ++-- examples/text/text_rectangle_bounds.c | 12 ++++++------ examples/text/text_sprite_fonts.c | 14 ++++++-------- examples/text/text_ttf_loading.c | 2 +- examples/textures/textures_background_scrolling.c | 6 +++--- examples/textures/textures_image_generation.c | 3 ++- examples/textures/textures_image_processing.c | 2 +- examples/textures/textures_particles_blending.c | 2 +- examples/textures/textures_raw_data.c | 2 +- examples/textures/textures_sprite_explosion.c | 2 +- 33 files changed, 52 insertions(+), 56 deletions(-) (limited to 'examples/models') diff --git a/examples/audio/audio_module_playing.c b/examples/audio/audio_module_playing.c index 4aebd1e6..4842519a 100644 --- a/examples/audio/audio_module_playing.c +++ b/examples/audio/audio_module_playing.c @@ -40,7 +40,7 @@ int main(void) YELLOW, GREEN, SKYBLUE, PURPLE, BEIGE }; // Creates ome circles for visual effect - CircleWave circles[MAX_CIRCLES]; + CircleWave circles[MAX_CIRCLES] = { 0 }; for (int i = MAX_CIRCLES - 1; i >= 0; i--) { diff --git a/examples/audio/audio_sound_loading.c b/examples/audio/audio_sound_loading.c index d208dd9a..4bc9c704 100644 --- a/examples/audio/audio_sound_loading.c +++ b/examples/audio/audio_sound_loading.c @@ -46,7 +46,6 @@ int main(void) ClearBackground(RAYWHITE); DrawText("Press SPACE to PLAY the WAV sound!", 200, 180, 20, LIGHTGRAY); - DrawText("Press ENTER to PLAY the OGG sound!", 200, 220, 20, LIGHTGRAY); EndDrawing(); diff --git a/examples/core/core_2d_camera.c b/examples/core/core_2d_camera.c index fe8e584b..81f580ad 100644 --- a/examples/core/core_2d_camera.c +++ b/examples/core/core_2d_camera.c @@ -23,8 +23,8 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera"); Rectangle player = { 400, 280, 40, 40 }; - Rectangle buildings[MAX_BUILDINGS]; - Color buildColors[MAX_BUILDINGS]; + Rectangle buildings[MAX_BUILDINGS] = { 0 }; + Color buildColors[MAX_BUILDINGS] = { 0 }; int spacing = 0; @@ -41,7 +41,6 @@ int main(void) } Camera2D camera = { 0 }; - camera.target = (Vector2){ player.x + 20, player.y + 20 }; camera.offset = (Vector2){ 0, 0 }; camera.rotation = 0.0f; diff --git a/examples/core/core_3d_camera_first_person.c b/examples/core/core_3d_camera_first_person.c index 825a9ca8..39fbfb2e 100644 --- a/examples/core/core_3d_camera_first_person.c +++ b/examples/core/core_3d_camera_first_person.c @@ -31,9 +31,9 @@ int main(void) camera.type = CAMERA_PERSPECTIVE; // Generates some random columns - float heights[MAX_COLUMNS]; - Vector3 positions[MAX_COLUMNS]; - Color colors[MAX_COLUMNS]; + float heights[MAX_COLUMNS] = { 0.0f }; + Vector3 positions[MAX_COLUMNS] = { 0 }; + Color colors[MAX_COLUMNS] = { 0 }; for (int i = 0; i < MAX_COLUMNS; i++) { diff --git a/examples/core/core_3d_camera_free.c b/examples/core/core_3d_camera_free.c index c1445f60..5053fd63 100644 --- a/examples/core/core_3d_camera_free.c +++ b/examples/core/core_3d_camera_free.c @@ -21,7 +21,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free"); // Define the camera to look into our 3d world - Camera3D camera; + Camera3D camera = { 0 }; camera.position = (Vector3){ 10.0f, 10.0f, 10.0f }; // Camera position camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) diff --git a/examples/core/core_custom_logging.c b/examples/core/core_custom_logging.c index 0ab3fa45..56e168ee 100644 --- a/examples/core/core_custom_logging.c +++ b/examples/core/core_custom_logging.c @@ -19,7 +19,7 @@ // Custom logging funtion void LogCustom(int msgType, const char *text, va_list args) { - char timeStr[64]; + char timeStr[64] = { 0 }; time_t now = time(NULL); struct tm *tm_info = localtime(&now); diff --git a/examples/core/core_vr_simulator.c b/examples/core/core_vr_simulator.c index 134a36f0..628d7cf4 100644 --- a/examples/core/core_vr_simulator.c +++ b/examples/core/core_vr_simulator.c @@ -60,7 +60,7 @@ int main(void) SetVrConfiguration(hmd, distortion); // Set Vr device parameters for stereo rendering // Define the camera to look into our 3d world - Camera camera; + Camera camera = { 0 }; camera.position = (Vector3){ 5.0f, 2.0f, 5.0f }; // Camera position camera.target = (Vector3){ 0.0f, 2.0f, 0.0f }; // Camera looking at point camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) diff --git a/examples/core/core_world_screen.c b/examples/core/core_world_screen.c index 434952bc..31d3653d 100644 --- a/examples/core/core_world_screen.c +++ b/examples/core/core_world_screen.c @@ -29,8 +29,7 @@ int main(void) camera.type = CAMERA_PERSPECTIVE; Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; - - Vector2 cubeScreenPosition; + Vector2 cubeScreenPosition = { 0.0f, 0.0f }; SetCameraMode(camera, CAMERA_FREE); // Set a free camera mode diff --git a/examples/models/models_box_collisions.c b/examples/models/models_box_collisions.c index 0dd0710e..7a937ea7 100644 --- a/examples/models/models_box_collisions.c +++ b/examples/models/models_box_collisions.c @@ -21,7 +21,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions"); // Define the camera to look into our 3d world - Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Vector3 playerPosition = { 0.0f, 1.0f, 2.0f }; Vector3 playerSize = { 1.0f, 2.0f, 1.0f }; diff --git a/examples/models/models_cubicmap.c b/examples/models/models_cubicmap.c index f399a56e..f5087845 100644 --- a/examples/models/models_cubicmap.c +++ b/examples/models/models_cubicmap.c @@ -21,7 +21,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing"); // Define the camera to look into our 3d world - Camera camera = {{ 16.0f, 14.0f, 16.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 16.0f, 14.0f, 16.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Image image = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) Texture2D cubicmap = LoadTextureFromImage(image); // Convert image to texture to display (VRAM) diff --git a/examples/models/models_first_person_maze.c b/examples/models/models_first_person_maze.c index 42363747..07c51b9a 100644 --- a/examples/models/models_first_person_maze.c +++ b/examples/models/models_first_person_maze.c @@ -23,7 +23,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze"); // Define the camera to look into our 3d world - Camera camera = {{ 0.2f, 0.4f, 0.2f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 0.2f, 0.4f, 0.2f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Image imMap = LoadImage("resources/cubicmap.png"); // Load cubicmap image (RAM) Texture2D cubicmap = LoadTextureFromImage(imMap); // Convert image to texture to display (VRAM) diff --git a/examples/models/models_heightmap.c b/examples/models/models_heightmap.c index e242db16..a2c2e310 100644 --- a/examples/models/models_heightmap.c +++ b/examples/models/models_heightmap.c @@ -21,7 +21,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing"); // Define our custom camera to look into our 3d world - Camera camera = {{ 18.0f, 16.0f, 18.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 18.0f, 16.0f, 18.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Image image = LoadImage("resources/heightmap.png"); // Load heightmap image (RAM) Texture2D texture = LoadTextureFromImage(image); // Convert image to texture (VRAM) diff --git a/examples/models/models_mesh_generation.c b/examples/models/models_mesh_generation.c index cfc3bdd6..6c0ae653 100644 --- a/examples/models/models_mesh_generation.c +++ b/examples/models/models_mesh_generation.c @@ -27,7 +27,7 @@ int main(void) Texture2D texture = LoadTextureFromImage(checked); UnloadImage(checked); - Model models[NUM_MODELS]; + Model models[NUM_MODELS] = { 0 }; models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5)); models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f)); @@ -42,7 +42,7 @@ int main(void) for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MAP_DIFFUSE].texture = texture; // Define the camera to look into our 3d world - Camera camera = {{ 5.0f, 5.0f, 5.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 5.0f, 5.0f, 5.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; // Model drawing position Vector3 position = { 0.0f, 0.0f, 0.0f }; diff --git a/examples/models/models_obj_viewer.c b/examples/models/models_obj_viewer.c index dc6787e7..83c8f2f1 100644 --- a/examples/models/models_obj_viewer.c +++ b/examples/models/models_obj_viewer.c @@ -23,7 +23,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib example - obj viewer"); // Define the camera to look into our 3d world - Camera camera = {{ 30.0f, 30.0f, 30.0f }, { 0.0f, 10.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 30.0f, 30.0f, 30.0f }, { 0.0f, 10.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Model model = LoadModel("resources/models/turret.obj"); // Load default model obj Texture2D texture = LoadTexture("resources/models/turret_diffuse.png"); // Load default model texture diff --git a/examples/models/models_orthographic_projection.c b/examples/models/models_orthographic_projection.c index ca9d83c9..8c9b5b1c 100644 --- a/examples/models/models_orthographic_projection.c +++ b/examples/models/models_orthographic_projection.c @@ -28,7 +28,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes"); // Define the camera to look into our 3d world - Camera camera = {{ 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE }; + Camera camera = { { 0.0f, 10.0f, 10.0f }, { 0.0f, 0.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, FOVY_PERSPECTIVE, CAMERA_PERSPECTIVE }; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- diff --git a/examples/models/models_skybox.c b/examples/models/models_skybox.c index 1693d9bc..bad29b96 100644 --- a/examples/models/models_skybox.c +++ b/examples/models/models_skybox.c @@ -21,7 +21,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing"); // Define the camera to look into our 3d world - Camera camera = {{ 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 1.0f, 1.0f, 1.0f }, { 4.0f, 1.0f, 4.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; // Load skybox model Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); diff --git a/examples/others/raudio_standalone.c b/examples/others/raudio_standalone.c index 02720837..63d5b8d2 100644 --- a/examples/others/raudio_standalone.c +++ b/examples/others/raudio_standalone.c @@ -94,7 +94,7 @@ int main() { // Initialization //-------------------------------------------------------------------------------------- - static unsigned char key; + static unsigned char key = 0; InitAudioDevice(); diff --git a/examples/others/rlgl_standalone.c b/examples/others/rlgl_standalone.c index 42aec2e2..d8100ce5 100644 --- a/examples/others/rlgl_standalone.c +++ b/examples/others/rlgl_standalone.c @@ -131,7 +131,7 @@ int main(void) rlClearColor(245, 245, 245, 255); // Define clear color rlEnableDepthTest(); // Enable DEPTH_TEST for 3D - Camera camera; + Camera camera = { 0 }; camera.position = (Vector3){ 5.0f, 5.0f, 5.0f }; // Camera position camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) diff --git a/examples/physac/physics_friction.c b/examples/physac/physics_friction.c index cbb9dc43..0acf88ae 100644 --- a/examples/physac/physics_friction.c +++ b/examples/physac/physics_friction.c @@ -61,8 +61,8 @@ int main(void) SetPhysicsBodyRotation(bodyA, 30*DEG2RAD); PhysicsBody bodyB = CreatePhysicsBodyRectangle((Vector2){ screenWidth - 35, screenHeight*0.6f }, 40, 40, 10); - bodyB->staticFriction = 1; - bodyB->dynamicFriction = 1; + bodyB->staticFriction = 1.0f; + bodyB->dynamicFriction = 1.0f; SetPhysicsBodyRotation(bodyB, 330*DEG2RAD); SetTargetFPS(60); // Set our game to run at 60 frames-per-second diff --git a/examples/shaders/shaders_postprocessing.c b/examples/shaders/shaders_postprocessing.c index 018b8d11..ed9da8bb 100644 --- a/examples/shaders/shaders_postprocessing.c +++ b/examples/shaders/shaders_postprocessing.c @@ -70,7 +70,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader"); // Define the camera to look into our 3d world - Camera camera = {{ 2.0f, 3.0f, 2.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; + Camera camera = { { 2.0f, 3.0f, 2.0f }, { 0.0f, 1.0f, 0.0f }, { 0.0f, 1.0f, 0.0f }, 45.0f, 0 }; Model model = LoadModel("resources/models/church.obj"); // Load OBJ model Texture2D texture = LoadTexture("resources/models/church_diffuse.png"); // Load model texture (diffuse map) @@ -81,7 +81,7 @@ int main(void) // Load all postpro shaders // NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER) // NOTE 2: We load the correct shader depending on GLSL version - Shader shaders[MAX_POSTPRO_SHADERS]; + Shader shaders[MAX_POSTPRO_SHADERS] = { 0 }; // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader shaders[FX_GRAYSCALE] = LoadShader(0, FormatText("resources/shaders/glsl%i/grayscale.fs", GLSL_VERSION)); diff --git a/examples/shapes/shapes_colors_palette.c b/examples/shapes/shapes_colors_palette.c index 7322f7e5..a0bba002 100644 --- a/examples/shapes/shapes_colors_palette.c +++ b/examples/shapes/shapes_colors_palette.c @@ -45,7 +45,7 @@ int main(void) int colorState[MAX_COLORS_COUNT] = { 0 }; // Color state: 0-DEFAULT, 1-MOUSE_HOVER - Vector2 mousePoint; + Vector2 mousePoint = { 0.0f, 0.0f }; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- diff --git a/examples/shapes/shapes_easings_rectangle_array.c b/examples/shapes/shapes_easings_rectangle_array.c index 9844af6a..07de98a0 100644 --- a/examples/shapes/shapes_easings_rectangle_array.c +++ b/examples/shapes/shapes_easings_rectangle_array.c @@ -33,7 +33,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array"); - Rectangle recs[MAX_RECS_X*MAX_RECS_Y]; + Rectangle recs[MAX_RECS_X*MAX_RECS_Y] = { 0 }; for (int y = 0; y < MAX_RECS_Y; y++) { diff --git a/examples/text/text_font_sdf.c b/examples/text/text_font_sdf.c index d3c76c4f..91e43f75 100644 --- a/examples/text/text_font_sdf.c +++ b/examples/text/text_font_sdf.c @@ -57,7 +57,7 @@ int main(void) SetTextureFilter(fontSDF.texture, FILTER_BILINEAR); // Required for SDF font Vector2 fontPosition = { 40, screenHeight/2 - 50 }; - Vector2 textSize = { 0.0f }; + Vector2 textSize = { 0.0f, 0.0f }; float fontSize = 16.0f; int currentFont = 0; // 0 - fontDefault, 1 - fontSDF diff --git a/examples/text/text_raylib_fonts.c b/examples/text/text_raylib_fonts.c index 06e63725..d7e41a78 100644 --- a/examples/text/text_raylib_fonts.c +++ b/examples/text/text_raylib_fonts.c @@ -26,7 +26,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [text] example - raylib fonts"); // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) - Font fonts[MAX_FONTS]; + Font fonts[MAX_FONTS] = { 0 }; fonts[0] = LoadFont("resources/fonts/alagard.png"); fonts[1] = LoadFont("resources/fonts/pixelplay.png"); @@ -48,7 +48,7 @@ int main(void) const int spacings[MAX_FONTS] = { 2, 4, 8, 4, 3, 4, 4, 1 }; - Vector2 positions[MAX_FONTS]; + Vector2 positions[MAX_FONTS] = { 0 }; for (int i = 0; i < MAX_FONTS; i++) { diff --git a/examples/text/text_rectangle_bounds.c b/examples/text/text_rectangle_bounds.c index 5871278f..abfb142b 100644 --- a/examples/text/text_rectangle_bounds.c +++ b/examples/text/text_rectangle_bounds.c @@ -22,7 +22,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle"); - char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ + const char text[] = "Text cannot escape\tthis container\t...word wrap also works when active so here's\ a long text for testing.\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod\ tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget."; @@ -38,15 +38,15 @@ int main(void) const int maxWidth = screenWidth - 50; const int maxHeight = screenHeight - 160; - Vector2 lastMouse = { 0, 0 }; // Stores last mouse coordinates - Color borderColor = MAROON; // Container border color - Font font = GetFontDefault(); // Get default system font + Vector2 lastMouse = { 0.0f, 0.0f }; // Stores last mouse coordinates + Color borderColor = MAROON; // Container border color + Font font = GetFontDefault(); // Get default system font - SetTargetFPS(60); // Set our game to run at 60 frames-per-second + SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop - while (!WindowShouldClose()) // Detect window close button or ESC key + while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- diff --git a/examples/text/text_sprite_fonts.c b/examples/text/text_sprite_fonts.c index 30028937..b7c9ab10 100644 --- a/examples/text/text_sprite_fonts.c +++ b/examples/text/text_sprite_fonts.c @@ -29,16 +29,14 @@ int main(void) Font font2 = LoadFont("resources/custom_alagard.png"); // Font loading Font font3 = LoadFont("resources/custom_jupiter_crash.png"); // Font loading - Vector2 fontPosition1, fontPosition2, fontPosition3; + Vector2 fontPosition1 = { screenWidth/2 - MeasureTextEx(font1, msg1, font1.baseSize, -3).x/2, + screenHeight/2 - font1.baseSize/2 - 80 }; - fontPosition1.x = screenWidth/2 - MeasureTextEx(font1, msg1, font1.baseSize, -3).x/2; - fontPosition1.y = screenHeight/2 - font1.baseSize/2 - 80; + Vector2 fontPosition2 = { screenWidth/2 - MeasureTextEx(font2, msg2, font2.baseSize, -2).x/2, + screenHeight/2 - font2.baseSize/2 - 10 }; - fontPosition2.x = screenWidth/2 - MeasureTextEx(font2, msg2, font2.baseSize, -2).x/2; - fontPosition2.y = screenHeight/2 - font2.baseSize/2 - 10; - - fontPosition3.x = screenWidth/2 - MeasureTextEx(font3, msg3, font3.baseSize, 2).x/2; - fontPosition3.y = screenHeight/2 - font3.baseSize/2 + 50; + Vector2 fontPosition3 = { screenWidth/2 - MeasureTextEx(font3, msg3, font3.baseSize, 2).x/2, + screenHeight/2 - font3.baseSize/2 + 50 }; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- diff --git a/examples/text/text_ttf_loading.c b/examples/text/text_ttf_loading.c index cc59417d..b256bd1d 100644 --- a/examples/text/text_ttf_loading.c +++ b/examples/text/text_ttf_loading.c @@ -33,7 +33,7 @@ int main(void) float fontSize = font.baseSize; Vector2 fontPosition = { 40, screenHeight/2 - 80 }; - Vector2 textSize; + Vector2 textSize = { 0.0f, 0.0f }; // Setup texture scaling filter SetTextureFilter(font.texture, FILTER_POINT); diff --git a/examples/textures/textures_background_scrolling.c b/examples/textures/textures_background_scrolling.c index d91b2585..c2e5ac80 100644 --- a/examples/textures/textures_background_scrolling.c +++ b/examples/textures/textures_background_scrolling.c @@ -26,9 +26,9 @@ int main(void) Texture2D midground = LoadTexture("resources/cyberpunk_street_midground.png"); Texture2D foreground = LoadTexture("resources/cyberpunk_street_foreground.png"); - float scrollingBack = 0; - float scrollingMid = 0; - float scrollingFore = 0; + float scrollingBack = 0.0f; + float scrollingMid = 0.0f; + float scrollingFore = 0.0f; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- diff --git a/examples/textures/textures_image_generation.c b/examples/textures/textures_image_generation.c index d9a39a25..0bb10583 100644 --- a/examples/textures/textures_image_generation.c +++ b/examples/textures/textures_image_generation.c @@ -30,7 +30,8 @@ int main(void) Image perlinNoise = GenImagePerlinNoise(screenWidth, screenHeight, 50, 50, 4.0f); Image cellular = GenImageCellular(screenWidth, screenHeight, 32); - Texture2D textures[NUM_TEXTURES]; + Texture2D textures[NUM_TEXTURES] = { 0 }; + textures[0] = LoadTextureFromImage(verticalGradient); textures[1] = LoadTextureFromImage(horizontalGradient); textures[2] = LoadTextureFromImage(radialGradient); diff --git a/examples/textures/textures_image_processing.c b/examples/textures/textures_image_processing.c index b9ed51d7..14442290 100644 --- a/examples/textures/textures_image_processing.c +++ b/examples/textures/textures_image_processing.c @@ -57,7 +57,7 @@ int main(void) int currentProcess = NONE; bool textureReload = false; - Rectangle selectRecs[NUM_PROCESSES]; + Rectangle selectRecs[NUM_PROCESSES] = { 0 }; for (int i = 0; i < NUM_PROCESSES; i++) selectRecs[i] = (Rectangle){ 40.0f, (float)(50 + 32*i), 150.0f, 30.0f }; diff --git a/examples/textures/textures_particles_blending.c b/examples/textures/textures_particles_blending.c index 75287ea7..d094c6c2 100644 --- a/examples/textures/textures_particles_blending.c +++ b/examples/textures/textures_particles_blending.c @@ -33,7 +33,7 @@ int main(void) InitWindow(screenWidth, screenHeight, "raylib [textures] example - particles blending"); // Particles pool, reuse them! - Particle mouseTail[MAX_PARTICLES]; + Particle mouseTail[MAX_PARTICLES] = { 0 }; // Initialize particles for (int i = 0; i < MAX_PARTICLES; i++) diff --git a/examples/textures/textures_raw_data.c b/examples/textures/textures_raw_data.c index 17604bde..08269bf7 100644 --- a/examples/textures/textures_raw_data.c +++ b/examples/textures/textures_raw_data.c @@ -31,7 +31,7 @@ int main(void) Texture2D fudesumi = LoadTextureFromImage(fudesumiRaw); // Upload CPU (RAM) image to GPU (VRAM) UnloadImage(fudesumiRaw); // Unload CPU (RAM) image data - // Generate a checked texture by code (1024x1024 pixels) + // Generate a checked texture by code int width = 960; int height = 480; diff --git a/examples/textures/textures_sprite_explosion.c b/examples/textures/textures_sprite_explosion.c index 58a8f6fc..823c1b8a 100644 --- a/examples/textures/textures_sprite_explosion.c +++ b/examples/textures/textures_sprite_explosion.c @@ -38,7 +38,7 @@ int main(void) int currentLine = 0; Rectangle frameRec = { 0, 0, frameWidth, frameHeight }; - Vector2 position = { 0, 0 }; + Vector2 position = { 0.0f, 0.0f }; bool active = false; int framesCounter = 0; -- cgit v1.2.3 From a9f33c9a8962735fed5dd1857709d159bc4056fc Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 31 May 2019 10:03:44 +0200 Subject: Reduce textures size --- .../models/resources/models/castle_diffuse.png | Bin 1538906 -> 444546 bytes examples/models/resources/pbr/trooper_albedo.png | Bin 7676508 -> 1838043 bytes examples/models/resources/pbr/trooper_ao.png | Bin 1832292 -> 559997 bytes examples/models/resources/pbr/trooper_normals.png | Bin 4959793 -> 1313366 bytes .../models/resources/pbr/trooper_roughness.png | Bin 2862048 -> 733780 bytes 5 files changed, 0 insertions(+), 0 deletions(-) (limited to 'examples/models') diff --git a/examples/models/resources/models/castle_diffuse.png b/examples/models/resources/models/castle_diffuse.png index b616e1dd..361144e9 100644 Binary files a/examples/models/resources/models/castle_diffuse.png and b/examples/models/resources/models/castle_diffuse.png differ diff --git a/examples/models/resources/pbr/trooper_albedo.png b/examples/models/resources/pbr/trooper_albedo.png index ac1422e4..9ba0f5a6 100644 Binary files a/examples/models/resources/pbr/trooper_albedo.png and b/examples/models/resources/pbr/trooper_albedo.png differ diff --git a/examples/models/resources/pbr/trooper_ao.png b/examples/models/resources/pbr/trooper_ao.png index 8567f7b4..442dd7fb 100644 Binary files a/examples/models/resources/pbr/trooper_ao.png and b/examples/models/resources/pbr/trooper_ao.png differ diff --git a/examples/models/resources/pbr/trooper_normals.png b/examples/models/resources/pbr/trooper_normals.png index 59c7bdc4..e04be883 100644 Binary files a/examples/models/resources/pbr/trooper_normals.png and b/examples/models/resources/pbr/trooper_normals.png differ diff --git a/examples/models/resources/pbr/trooper_roughness.png b/examples/models/resources/pbr/trooper_roughness.png index 53186d51..29f418f7 100644 Binary files a/examples/models/resources/pbr/trooper_roughness.png and b/examples/models/resources/pbr/trooper_roughness.png differ -- cgit v1.2.3 From 923f4b9bbd1af4bff0037807ec0f6e6514c043cd Mon Sep 17 00:00:00 2001 From: Codecat Date: Wed, 5 Jun 2019 10:35:20 +0200 Subject: Added waving cubes example --- examples/models/models_waving_cubes.c | 105 ++++++++++++++++++++++++++++++++ examples/models/models_waving_cubes.png | Bin 0 -> 37712 bytes 2 files changed, 105 insertions(+) create mode 100644 examples/models/models_waving_cubes.c create mode 100644 examples/models/models_waving_cubes.png (limited to 'examples/models') diff --git a/examples/models/models_waving_cubes.c b/examples/models/models_waving_cubes.c new file mode 100644 index 00000000..0fefbcf2 --- /dev/null +++ b/examples/models/models_waving_cubes.c @@ -0,0 +1,105 @@ +/******************************************************************************************* +* +* raylib [models] example - Waving cubes +* +* This example has been created using raylib 2.5 (www.raylib.com) +* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) +* +* Copyright (c) 2019 Ramon Santamaria (@raysan5) +* +********************************************************************************************/ + +#include "raylib.h" + +#include + +int main() +{ + // Initialization + //-------------------------------------------------------------------------------------- + const int screenWidth = 800; + const int screenHeight = 450; + + InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes"); + + // Initialize the camera + Camera3D camera; + camera.position = (Vector3){ 30.0f, 20.0f, 30.0f }; + camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; + camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; + camera.fovy = 70.0f; + camera.type = CAMERA_PERSPECTIVE; + + // Specify the amount of blocks in each direction + const int numBlocks = 15; + + SetTargetFPS(60); + //-------------------------------------------------------------------------------------- + + // Main game loop + while (!WindowShouldClose()) // Detect window close button or ESC key + { + // Update + double time = GetTime(); + + // Calculate time scale for cube position and size + float scale = (2.0f + (float)sin(time)) * 0.7f; + + // Move camera around the scene + double cameraTime = time * 0.3; + camera.position.x = (float)cos(cameraTime) * 40.0f; + camera.position.z = (float)sin(cameraTime) * 40.0f; + + // Draw + //---------------------------------------------------------------------------------- + BeginDrawing(); + + ClearBackground(RAYWHITE); + + BeginMode3D(camera); + + DrawGrid(10, 5.0f); + + for (int x = 0; x < numBlocks; x++) { + for (int y = 0; y < numBlocks; y++) { + for (int z = 0; z < numBlocks; z++) { + // Scale of the blocks depends on x/y/z positions + float blockScale = (x + y + z) / 30.0f; + + // Scatter makes the waving effect by adding blockScale over time + float scatter = sinf(blockScale * 20.0f + (float)(time * 4.0f)); + + // Calculate the cube position + Vector3 cubePos = { + (float)(x - numBlocks / 2) * (scale * 3.0f) + scatter, + (float)(y - numBlocks / 2) * (scale * 2.0f) + scatter, + (float)(z - numBlocks / 2) * (scale * 3.0f) + scatter + }; + + // Pick a color with a hue depending on cube position for the rainbow color effect + Color cubeColor = ColorFromHSV((Vector3){ (float)(((x + y + z) * 18) % 360), 0.75f, 0.9f }); + + // Calculate cube size + float cubeSize = (2.4f - scale) * blockScale; + + // And finally, draw the cube! + DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor); + } + } + } + + DrawFPS(10, 10); + + EndMode3D(); + + EndDrawing(); + //---------------------------------------------------------------------------------- + } + + // De-Initialization + //-------------------------------------------------------------------------------------- + CloseWindow(); // Close window and OpenGL context + //-------------------------------------------------------------------------------------- + + return 0; +} diff --git a/examples/models/models_waving_cubes.png b/examples/models/models_waving_cubes.png new file mode 100644 index 00000000..37a1761e Binary files /dev/null and b/examples/models/models_waving_cubes.png differ -- cgit v1.2.3 From ddaa4a304d5a8fe8bf7fc6d4d94a2bcd01298119 Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 5 Jun 2019 12:58:35 +0200 Subject: Review contributor info --- examples/models/models_animation.c | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'examples/models') diff --git a/examples/models/models_animation.c b/examples/models/models_animation.c index 294b07a5..7f38b7f5 100644 --- a/examples/models/models_animation.c +++ b/examples/models/models_animation.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Ramon Santamaria (@raysan5) and @culacant +* Example contributed by Culacant (@culacant) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Culacant (@culacant) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ -- cgit v1.2.3 From 03720b30a135d9acab1f008c7ffb2aa46f8dbffb Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 5 Jun 2019 12:58:53 +0200 Subject: Review contributed example --- examples/models/models_waving_cubes.c | 47 ++++++++++++++++++++--------------- 1 file changed, 27 insertions(+), 20 deletions(-) (limited to 'examples/models') diff --git a/examples/models/models_waving_cubes.c b/examples/models/models_waving_cubes.c index 0fefbcf2..f6309bd6 100644 --- a/examples/models/models_waving_cubes.c +++ b/examples/models/models_waving_cubes.c @@ -5,7 +5,9 @@ * This example has been created using raylib 2.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) * -* Copyright (c) 2019 Ramon Santamaria (@raysan5) +* Example contributed by Codecat (@codecat) and reviewed by Ramon Santamaria (@raysan5) +* +* Copyright (c) 2019 Codecat (@codecat) and Ramon Santamaria (@raysan5) * ********************************************************************************************/ @@ -23,7 +25,7 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes"); // Initialize the camera - Camera3D camera; + Camera3D camera = { 0 }; camera.position = (Vector3){ 30.0f, 20.0f, 30.0f }; camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; @@ -40,16 +42,18 @@ int main() while (!WindowShouldClose()) // Detect window close button or ESC key { // Update + //---------------------------------------------------------------------------------- double time = GetTime(); // Calculate time scale for cube position and size - float scale = (2.0f + (float)sin(time)) * 0.7f; + float scale = (2.0f + (float)sin(time))*0.7f; // Move camera around the scene - double cameraTime = time * 0.3; - camera.position.x = (float)cos(cameraTime) * 40.0f; - camera.position.z = (float)sin(cameraTime) * 40.0f; - + double cameraTime = time*0.3; + camera.position.x = (float)cos(cameraTime)*40.0f; + camera.position.z = (float)sin(cameraTime)*40.0f; + //---------------------------------------------------------------------------------- + // Draw //---------------------------------------------------------------------------------- BeginDrawing(); @@ -60,37 +64,40 @@ int main() DrawGrid(10, 5.0f); - for (int x = 0; x < numBlocks; x++) { - for (int y = 0; y < numBlocks; y++) { - for (int z = 0; z < numBlocks; z++) { + for (int x = 0; x < numBlocks; x++) + { + for (int y = 0; y < numBlocks; y++) + { + for (int z = 0; z < numBlocks; z++) + { // Scale of the blocks depends on x/y/z positions - float blockScale = (x + y + z) / 30.0f; + float blockScale = (x + y + z)/30.0f; // Scatter makes the waving effect by adding blockScale over time - float scatter = sinf(blockScale * 20.0f + (float)(time * 4.0f)); + float scatter = sinf(blockScale*20.0f + (float)(time*4.0f)); // Calculate the cube position Vector3 cubePos = { - (float)(x - numBlocks / 2) * (scale * 3.0f) + scatter, - (float)(y - numBlocks / 2) * (scale * 2.0f) + scatter, - (float)(z - numBlocks / 2) * (scale * 3.0f) + scatter + (float)(x - numBlocks/2)*(scale*3.0f) + scatter, + (float)(y - numBlocks/2)*(scale*2.0f) + scatter, + (float)(z - numBlocks/2)*(scale*3.0f) + scatter }; // Pick a color with a hue depending on cube position for the rainbow color effect - Color cubeColor = ColorFromHSV((Vector3){ (float)(((x + y + z) * 18) % 360), 0.75f, 0.9f }); + Color cubeColor = ColorFromHSV((Vector3){ (float)(((x + y + z)*18)%360), 0.75f, 0.9f }); // Calculate cube size - float cubeSize = (2.4f - scale) * blockScale; + float cubeSize = (2.4f - scale)*blockScale; // And finally, draw the cube! DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor); } } } - - DrawFPS(10, 10); - + EndMode3D(); + + DrawFPS(10, 10); EndDrawing(); //---------------------------------------------------------------------------------- -- cgit v1.2.3