subrepo:
  subdir:   "OTRGui"
  merged:   "a6066a251"
upstream:
  origin:   "https://github.com/HarbourMasters/otrgui.git"
  branch:   "master"
  commit:   "a6066a251"
git-subrepo:
  version:  "0.4.1"
  origin:   "???"
  commit:   "???"
This commit is contained in:
M4xw 2022-03-22 02:53:51 +01:00
commit f52a2a6406
1018 changed files with 511803 additions and 0 deletions

View file

@ -0,0 +1,263 @@
/*******************************************************************************************
*
* raylib easings (header only file)
*
* Useful easing functions for values animation
*
* This header uses:
* #define EASINGS_STATIC_INLINE // Inlines all functions code, so it runs faster.
* // This requires lots of memory on system.
* How to use:
* The four inputs t,b,c,d are defined as follows:
* t = current time (in any unit measure, but same unit as duration)
* b = starting value to interpolate
* c = the total change in value of b that needs to occur
* d = total time it should take to complete (duration)
*
* Example:
*
* int currentTime = 0;
* int duration = 100;
* float startPositionX = 0.0f;
* float finalPositionX = 30.0f;
* float currentPositionX = startPositionX;
*
* while (currentPositionX < finalPositionX)
* {
* currentPositionX = EaseSineIn(currentTime, startPositionX, finalPositionX - startPositionX, duration);
* currentTime++;
* }
*
* A port of Robert Penner's easing equations to C (http://robertpenner.com/easing/)
*
* Robert Penner License
* ---------------------------------------------------------------------------------
* Open source under the BSD License.
*
* Copyright (c) 2001 Robert Penner. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the author nor the names of contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ---------------------------------------------------------------------------------
*
* Copyright (c) 2015 Ramon Santamaria
*
* 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.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
**********************************************************************************************/
#ifndef EASINGS_H
#define EASINGS_H
#define EASINGS_STATIC_INLINE // NOTE: By default, compile functions as static inline
#if defined(EASINGS_STATIC_INLINE)
#define EASEDEF static inline
#else
#define EASEDEF extern
#endif
#include <math.h> // Required for: sinf(), cosf(), sqrt(), pow()
#ifndef PI
#define PI 3.14159265358979323846f //Required as PI is not always defined in math.h
#endif
#ifdef __cplusplus
extern "C" { // Prevents name mangling of functions
#endif
// Linear Easing functions
EASEDEF float EaseLinearNone(float t, float b, float c, float d) { return (c*t/d + b); }
EASEDEF float EaseLinearIn(float t, float b, float c, float d) { return (c*t/d + b); }
EASEDEF float EaseLinearOut(float t, float b, float c, float d) { return (c*t/d + b); }
EASEDEF float EaseLinearInOut(float t,float b, float c, float d) { return (c*t/d + b); }
// Sine Easing functions
EASEDEF float EaseSineIn(float t, float b, float c, float d) { return (-c*cosf(t/d*(PI/2.0f)) + c + b); }
EASEDEF float EaseSineOut(float t, float b, float c, float d) { return (c*sinf(t/d*(PI/2.0f)) + b); }
EASEDEF float EaseSineInOut(float t, float b, float c, float d) { return (-c/2.0f*(cosf(PI*t/d) - 1.0f) + b); }
// Circular Easing functions
EASEDEF float EaseCircIn(float t, float b, float c, float d) { t /= d; return (-c*(sqrtf(1.0f - t*t) - 1.0f) + b); }
EASEDEF float EaseCircOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*sqrtf(1.0f - t*t) + b); }
EASEDEF float EaseCircInOut(float t, float b, float c, float d)
{
if ((t/=d/2.0f) < 1.0f) return (-c/2.0f*(sqrtf(1.0f - t*t) - 1.0f) + b);
t -= 2.0f; return (c/2.0f*(sqrtf(1.0f - t*t) + 1.0f) + b);
}
// Cubic Easing functions
EASEDEF float EaseCubicIn(float t, float b, float c, float d) { t /= d; return (c*t*t*t + b); }
EASEDEF float EaseCubicOut(float t, float b, float c, float d) { t = t/d - 1.0f; return (c*(t*t*t + 1.0f) + b); }
EASEDEF float EaseCubicInOut(float t, float b, float c, float d)
{
if ((t/=d/2.0f) < 1.0f) return (c/2.0f*t*t*t + b);
t -= 2.0f; return (c/2.0f*(t*t*t + 2.0f) + b);
}
// Quadratic Easing functions
EASEDEF float EaseQuadIn(float t, float b, float c, float d) { t /= d; return (c*t*t + b); }
EASEDEF float EaseQuadOut(float t, float b, float c, float d) { t /= d; return (-c*t*(t - 2.0f) + b); }
EASEDEF float EaseQuadInOut(float t, float b, float c, float d)
{
if ((t/=d/2) < 1) return (((c/2)*(t*t)) + b);
return (-c/2.0f*(((t - 1.0f)*(t - 3.0f)) - 1.0f) + b);
}
// Exponential Easing functions
EASEDEF float EaseExpoIn(float t, float b, float c, float d) { return (t == 0.0f) ? b : (c * powf(2.0f, 10.0f*(t/d - 1.0f)) + b); }
EASEDEF float EaseExpoOut(float t, float b, float c, float d) { return (t == d) ? (b + c) : (c * (-powf(2.0f, -10.0f*t/d) + 1.0f) + b); }
EASEDEF float EaseExpoInOut(float t, float b, float c, float d)
{
if (t == 0.0f) return b;
if (t == d) return (b + c);
if ((t/=d/2.0f) < 1.0f) return (c/2.0f* powf(2.0f, 10.0f*(t - 1.0f)) + b);
return (c/2.0f*(-powf(2.0f, -10.0f*(t - 1.0f)) + 2.0f) + b);
}
// Back Easing functions
EASEDEF float EaseBackIn(float t, float b, float c, float d)
{
float s = 1.70158f;
float postFix = t/=d;
return (c*(postFix)*t*((s + 1.0f)*t - s) + b);
}
EASEDEF float EaseBackOut(float t, float b, float c, float d)
{
float s = 1.70158f;
t = t/d - 1.0f;
return (c*(t*t*((s + 1.0f)*t + s) + 1.0f) + b);
}
EASEDEF float EaseBackInOut(float t, float b, float c, float d)
{
float s = 1.70158f;
if ((t/=d/2.0f) < 1.0f)
{
s *= 1.525f;
return (c/2.0f*(t*t*((s + 1.0f)*t - s)) + b);
}
float postFix = t-=2.0f;
s *= 1.525f;
return (c/2.0f*((postFix)*t*((s + 1.0f)*t + s) + 2.0f) + b);
}
// Bounce Easing functions
EASEDEF float EaseBounceOut(float t, float b, float c, float d)
{
if ((t/=d) < (1.0f/2.75f))
{
return (c*(7.5625f*t*t) + b);
}
else if (t < (2.0f/2.75f))
{
float postFix = t-=(1.5f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.75f) + b);
}
else if (t < (2.5/2.75))
{
float postFix = t-=(2.25f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.9375f) + b);
}
else
{
float postFix = t-=(2.625f/2.75f);
return (c*(7.5625f*(postFix)*t + 0.984375f) + b);
}
}
EASEDEF float EaseBounceIn(float t, float b, float c, float d) { return (c - EaseBounceOut(d - t, 0.0f, c, d) + b); }
EASEDEF float EaseBounceInOut(float t, float b, float c, float d)
{
if (t < d/2.0f) return (EaseBounceIn(t*2.0f, 0.0f, c, d)*0.5f + b);
else return (EaseBounceOut(t*2.0f - d, 0.0f, c, d)*0.5f + c*0.5f + b);
}
// Elastic Easing functions
EASEDEF float EaseElasticIn(float t, float b, float c, float d)
{
if (t == 0.0f) return b;
if ((t/=d) == 1.0f) return (b + c);
float p = d*0.3f;
float a = c;
float s = p/4.0f;
float postFix = a*powf(2.0f, 10.0f*(t-=1.0f));
return (-(postFix*sinf((t*d-s)*(2.0f*PI)/p )) + b);
}
EASEDEF float EaseElasticOut(float t, float b, float c, float d)
{
if (t == 0.0f) return b;
if ((t/=d) == 1.0f) return (b + c);
float p = d*0.3f;
float a = c;
float s = p/4.0f;
return (a*powf(2.0f,-10.0f*t)*sinf((t*d-s)*(2.0f*PI)/p) + c + b);
}
EASEDEF float EaseElasticInOut(float t, float b, float c, float d)
{
if (t == 0.0f) return b;
if ((t/=d/2.0f) == 2.0f) return (b + c);
float p = d*(0.3f*1.5f);
float a = c;
float s = p/4.0f;
if (t < 1.0f)
{
float postFix = a*powf(2.0f, 10.0f*(t-=1.0f));
return -0.5f*(postFix*sinf((t*d-s)*(2.0f*PI)/p)) + b;
}
float postFix = a*powf(2.0f, -10.0f*(t-=1.0f));
return (postFix*sinf((t*d-s)*(2.0f*PI)/p)*0.5f + c + b);
}
#ifdef __cplusplus
}
#endif
#endif // EASINGS_H

View file

@ -0,0 +1,227 @@
/*******************************************************************************************
*
* raylib [easings] example - Easings Testbed
*
* 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 Juan Miguel López (@flashback-fx) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Juan Miguel López (@flashback-fx ) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include <raylib.h>
#include "easings.h"
#define FONT_SIZE 20
#define D_STEP 20.0f
#define D_STEP_FINE 2.0f
#define D_MIN 1.0f
#define D_MAX 10000.0f
// Easing types
enum EasingTypes {
EASE_LINEAR_NONE = 0,
EASE_LINEAR_IN,
EASE_LINEAR_OUT,
EASE_LINEAR_IN_OUT,
EASE_SINE_IN,
EASE_SINE_OUT,
EASE_SINE_IN_OUT,
EASE_CIRC_IN,
EASE_CIRC_OUT,
EASE_CIRC_IN_OUT,
EASE_CUBIC_IN,
EASE_CUBIC_OUT,
EASE_CUBIC_IN_OUT,
EASE_QUAD_IN,
EASE_QUAD_OUT,
EASE_QUAD_IN_OUT,
EASE_EXPO_IN,
EASE_EXPO_OUT,
EASE_EXPO_IN_OUT,
EASE_BACK_IN,
EASE_BACK_OUT,
EASE_BACK_IN_OUT,
EASE_BOUNCE_OUT,
EASE_BOUNCE_IN,
EASE_BOUNCE_IN_OUT,
EASE_ELASTIC_IN,
EASE_ELASTIC_OUT,
EASE_ELASTIC_IN_OUT,
NUM_EASING_TYPES,
EASING_NONE = NUM_EASING_TYPES
};
static float NoEase(float t, float b, float c, float d); // NoEase function declaration, function used when "no easing" is selected for any axis
// Easing functions reference data
static const struct {
const char *name;
float (*func)(float, float, float, float);
} Easings[] = {
[EASE_LINEAR_NONE] = { .name = "EaseLinearNone", .func = EaseLinearNone },
[EASE_LINEAR_IN] = { .name = "EaseLinearIn", .func = EaseLinearIn },
[EASE_LINEAR_OUT] = { .name = "EaseLinearOut", .func = EaseLinearOut },
[EASE_LINEAR_IN_OUT] = { .name = "EaseLinearInOut", .func = EaseLinearInOut },
[EASE_SINE_IN] = { .name = "EaseSineIn", .func = EaseSineIn },
[EASE_SINE_OUT] = { .name = "EaseSineOut", .func = EaseSineOut },
[EASE_SINE_IN_OUT] = { .name = "EaseSineInOut", .func = EaseSineInOut },
[EASE_CIRC_IN] = { .name = "EaseCircIn", .func = EaseCircIn },
[EASE_CIRC_OUT] = { .name = "EaseCircOut", .func = EaseCircOut },
[EASE_CIRC_IN_OUT] = { .name = "EaseCircInOut", .func = EaseCircInOut },
[EASE_CUBIC_IN] = { .name = "EaseCubicIn", .func = EaseCubicIn },
[EASE_CUBIC_OUT] = { .name = "EaseCubicOut", .func = EaseCubicOut },
[EASE_CUBIC_IN_OUT] = { .name = "EaseCubicInOut", .func = EaseCubicInOut },
[EASE_QUAD_IN] = { .name = "EaseQuadIn", .func = EaseQuadIn },
[EASE_QUAD_OUT] = { .name = "EaseQuadOut", .func = EaseQuadOut },
[EASE_QUAD_IN_OUT] = { .name = "EaseQuadInOut", .func = EaseQuadInOut },
[EASE_EXPO_IN] = { .name = "EaseExpoIn", .func = EaseExpoIn },
[EASE_EXPO_OUT] = { .name = "EaseExpoOut", .func = EaseExpoOut },
[EASE_EXPO_IN_OUT] = { .name = "EaseExpoInOut", .func = EaseExpoInOut },
[EASE_BACK_IN] = { .name = "EaseBackIn", .func = EaseBackIn },
[EASE_BACK_OUT] = { .name = "EaseBackOut", .func = EaseBackOut },
[EASE_BACK_IN_OUT] = { .name = "EaseBackInOut", .func = EaseBackInOut },
[EASE_BOUNCE_OUT] = { .name = "EaseBounceOut", .func = EaseBounceOut },
[EASE_BOUNCE_IN] = { .name = "EaseBounceIn", .func = EaseBounceIn },
[EASE_BOUNCE_IN_OUT] = { .name = "EaseBounceInOut", .func = EaseBounceInOut },
[EASE_ELASTIC_IN] = { .name = "EaseElasticIn", .func = EaseElasticIn },
[EASE_ELASTIC_OUT] = { .name = "EaseElasticOut", .func = EaseElasticOut },
[EASE_ELASTIC_IN_OUT] = { .name = "EaseElasticInOut", .func = EaseElasticInOut },
[EASING_NONE] = { .name = "None", .func = NoEase },
};
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [easings] example - easings testbed");
Vector2 ballPosition = { 100.0f, 200.0f };
float t = 0.0f; // Current time (in any unit measure, but same unit as duration)
float d = 300.0f; // Total time it should take to complete (duration)
bool paused = true;
bool boundedT = true; // If true, t will stop when d >= td, otherwise t will keep adding td to its value every loop
int easingX = EASING_NONE; // Easing selected for x axis
int easingY = EASING_NONE; // Easing selected for y axis
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KEY_T)) boundedT = !boundedT;
// Choose easing for the X axis
if (IsKeyPressed(KEY_RIGHT))
{
easingX++;
if (easingX > EASING_NONE) easingX = 0;
}
else if (IsKeyPressed(KEY_LEFT))
{
if (easingX == 0) easingX = EASING_NONE;
else easingX--;
}
// Choose easing for the Y axis
if (IsKeyPressed(KEY_DOWN))
{
easingY++;
if (easingY > EASING_NONE) easingY = 0;
}
else if (IsKeyPressed(KEY_UP))
{
if (easingY == 0) easingY = EASING_NONE;
else easingY--;
}
// Change d (duration) value
if (IsKeyPressed(KEY_W) && d < D_MAX - D_STEP) d += D_STEP;
else if (IsKeyPressed(KEY_Q) && d > D_MIN + D_STEP) d -= D_STEP;
if (IsKeyDown(KEY_S) && d < D_MAX - D_STEP_FINE) d += D_STEP_FINE;
else if (IsKeyDown(KEY_A) && d > D_MIN + D_STEP_FINE) d -= D_STEP_FINE;
// Play, pause and restart controls
if (IsKeyPressed(KEY_SPACE) || IsKeyPressed(KEY_T) ||
IsKeyPressed(KEY_RIGHT) || IsKeyPressed(KEY_LEFT) ||
IsKeyPressed(KEY_DOWN) || IsKeyPressed(KEY_UP) ||
IsKeyPressed(KEY_W) || IsKeyPressed(KEY_Q) ||
IsKeyDown(KEY_S) || IsKeyDown(KEY_A) ||
(IsKeyPressed(KEY_ENTER) && (boundedT == true) && (t >= d)))
{
t = 0.0f;
ballPosition.x = 100.0f;
ballPosition.y = 100.0f;
paused = true;
}
if (IsKeyPressed(KEY_ENTER)) paused = !paused;
// Movement computation
if (!paused && ((boundedT && t < d) || !boundedT))
{
ballPosition.x = Easings[easingX].func(t, 100.0f, 700.0f - 100.0f, d);
ballPosition.y = Easings[easingY].func(t, 100.0f, 400.0f - 100.0f, d);
t += 1.0f;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
// Draw information text
DrawText(TextFormat("Easing x: %s", Easings[easingX].name), 0, FONT_SIZE*2, FONT_SIZE, LIGHTGRAY);
DrawText(TextFormat("Easing y: %s", Easings[easingY].name), 0, FONT_SIZE*3, FONT_SIZE, LIGHTGRAY);
DrawText(TextFormat("t (%c) = %.2f d = %.2f", (boundedT == true)? 'b' : 'u', t, d), 0, FONT_SIZE*4, FONT_SIZE, LIGHTGRAY);
// Draw instructions text
DrawText("Use ENTER to play or pause movement, use SPACE to restart", 0, GetScreenHeight() - FONT_SIZE*2, FONT_SIZE, LIGHTGRAY);
DrawText("Use D and W or A and S keys to change duration", 0, GetScreenHeight() - FONT_SIZE*3, FONT_SIZE, LIGHTGRAY);
DrawText("Use LEFT or RIGHT keys to choose easing for the x axis", 0, GetScreenHeight() - FONT_SIZE*4, FONT_SIZE, LIGHTGRAY);
DrawText("Use UP or DOWN keys to choose easing for the y axis", 0, GetScreenHeight() - FONT_SIZE*5, FONT_SIZE, LIGHTGRAY);
// Draw ball
DrawCircleV(ballPosition, 16.0f, MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// NoEase function, used when "no easing" is selected for any axis. It just ignores all parameters besides b.
static float NoEase(float t, float b, float c, float d)
{
float burn = t + b + c + d; // Hack to avoid compiler warning (about unused variables)
d += burn;
return b;
}

View file

@ -0,0 +1,103 @@
/*******************************************************************************************
*
* raylib [others] example - Embedded files loading (Wave and Image)
*
* This example has been created using raylib 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Kristian Holmgren (@defutura) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2020 Kristian Holmgren (@defutura) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include "resources/audio_data.h" // Wave file exported with ExportWaveAsCode()
#include "resources/image_data.h" // Image file exported with ExportImageAsCode()
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [others] example - embedded files loading");
InitAudioDevice(); // Initialize audio device
// Loaded in CPU memory (RAM) from header file (audio_data.h)
// Same as: Wave wave = LoadWave("sound.wav");
Wave wave = {
.data = AUDIO_DATA,
.frameCount = AUDIO_FRAME_COUNT,
.sampleRate = AUDIO_SAMPLE_RATE,
.sampleSize = AUDIO_SAMPLE_SIZE,
.channels = AUDIO_CHANNELS
};
// Wave converted to Sound to be played
Sound sound = LoadSoundFromWave(wave);
// With a Wave loaded from file, after Sound is loaded, we can unload Wave
// but in our case, Wave is embedded in executable, in program .data segment
// we can not (and should not) try to free that private memory region
//UnloadWave(wave); // Do not unload wave data!
// Loaded in CPU memory (RAM) from header file (image_data.h)
// Same as: Image image = LoadImage("raylib_logo.png");
Image image = {
.data = IMAGE_DATA,
.width = IMAGE_WIDTH,
.height = IMAGE_HEIGHT,
.format = IMAGE_FORMAT,
.mipmaps = 1
};
// Image converted to Texture (VRAM) to be drawn
Texture2D texture = LoadTextureFromImage(image);
// With an Image loaded from file, after Texture is loaded, we can unload Image
// but in our case, Image is embedded in executable, in program .data segment
// we can not (and should not) try to free that private memory region
//UnloadImage(image); // Do not unload image data!
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)) PlaySound(sound); // Play sound
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
DrawTexture(texture, screenWidth/2 - texture.width/2, 40, WHITE);
DrawText("raylib logo and sound loaded from header files", 65, 320, 20, LIGHTGRAY);
DrawText("Press SPACE to PLAY the sound!", 200, 360, 20, LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadSound(sound); // Unload sound from VRAM
UnloadTexture(texture); // Unload texture from VRAM
CloseAudioDevice(); // Close audio device
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,572 @@
/*************************************************************************
* GLFW 3.3 - www.glfw.org
* A library for OpenGL, window and input
*------------------------------------------------------------------------
* Copyright (c) 2002-2006 Marcus Geelnard
* Copyright (c) 2006-2016 Camilla Löwy <elmindreda@glfw.org>
*
* 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.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would
* be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source
* distribution.
*
*************************************************************************/
#ifndef _glfw3_native_h_
#define _glfw3_native_h_
#ifdef __cplusplus
extern "C" {
#endif
/*************************************************************************
* Doxygen documentation
*************************************************************************/
/*! @file glfw3native.h
* @brief The header of the native access functions.
*
* This is the header file of the native access functions. See @ref native for
* more information.
*/
/*! @defgroup native Native access
* @brief Functions related to accessing native handles.
*
* **By using the native access functions you assert that you know what you're
* doing and how to fix problems caused by using them. If you don't, you
* shouldn't be using them.**
*
* Before the inclusion of @ref glfw3native.h, you may define zero or more
* window system API macro and zero or more context creation API macros.
*
* The chosen backends must match those the library was compiled for. Failure
* to do this will cause a link-time error.
*
* The available window API macros are:
* * `GLFW_EXPOSE_NATIVE_WIN32`
* * `GLFW_EXPOSE_NATIVE_COCOA`
* * `GLFW_EXPOSE_NATIVE_X11`
* * `GLFW_EXPOSE_NATIVE_WAYLAND`
* * `GLFW_EXPOSE_NATIVE_MIR`
*
* The available context API macros are:
* * `GLFW_EXPOSE_NATIVE_WGL`
* * `GLFW_EXPOSE_NATIVE_NSGL`
* * `GLFW_EXPOSE_NATIVE_GLX`
* * `GLFW_EXPOSE_NATIVE_EGL`
* * `GLFW_EXPOSE_NATIVE_OSMESA`
*
* These macros select which of the native access functions that are declared
* and which platform-specific headers to include. It is then up your (by
* definition platform-specific) code to handle which of these should be
* defined.
*/
/*************************************************************************
* System headers and types
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
// This is a workaround for the fact that glfw3.h needs to export APIENTRY (for
// example to allow applications to correctly declare a GL_ARB_debug_output
// callback) but windows.h assumes no one will define APIENTRY before it does
#if defined(GLFW_APIENTRY_DEFINED)
#undef APIENTRY
#undef GLFW_APIENTRY_DEFINED
#endif
#include <windows.h>
#elif defined(GLFW_EXPOSE_NATIVE_COCOA)
#include <ApplicationServices/ApplicationServices.h>
#if defined(__OBJC__)
#import <Cocoa/Cocoa.h>
#else
typedef void* id;
#endif
#elif defined(GLFW_EXPOSE_NATIVE_X11)
#include <X11/Xlib.h>
#include <X11/extensions/Xrandr.h>
#elif defined(GLFW_EXPOSE_NATIVE_WAYLAND)
#include <wayland-client.h>
#elif defined(GLFW_EXPOSE_NATIVE_MIR)
#include <mir_toolkit/mir_client_library.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/* WGL is declared by windows.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/* NSGL is declared by Cocoa.h */
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
#include <GL/glx.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
#include <EGL/egl.h>
#endif
#if defined(GLFW_EXPOSE_NATIVE_OSMESA)
#include <GL/osmesa.h>
#endif
/*************************************************************************
* Functions
*************************************************************************/
#if defined(GLFW_EXPOSE_NATIVE_WIN32)
/*! @brief Returns the adapter device name of the specified monitor.
*
* @return The UTF-8 encoded adapter device name (for example `\\.\DISPLAY1`)
* of the specified monitor, or `NULL` if an [error](@ref error_handling)
* occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Adapter(GLFWmonitor* monitor);
/*! @brief Returns the display device name of the specified monitor.
*
* @return The UTF-8 encoded display device name (for example
* `\\.\DISPLAY1\Monitor0`) of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetWin32Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `HWND` of the specified window.
*
* @return The `HWND` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HWND glfwGetWin32Window(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WGL)
/*! @brief Returns the `HGLRC` of the specified window.
*
* @return The `HGLRC` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI HGLRC glfwGetWGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_COCOA)
/*! @brief Returns the `CGDirectDisplayID` of the specified monitor.
*
* @return The `CGDirectDisplayID` of the specified monitor, or
* `kCGNullDirectDisplay` if an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI CGDirectDisplayID glfwGetCocoaMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `NSWindow` of the specified window.
*
* @return The `NSWindow` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetCocoaWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_NSGL)
/*! @brief Returns the `NSOpenGLContext` of the specified window.
*
* @return The `NSOpenGLContext` of the specified window, or `nil` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI id glfwGetNSGLContext(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_X11)
/*! @brief Returns the `Display` used by GLFW.
*
* @return The `Display` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Display* glfwGetX11Display(void);
/*! @brief Returns the `RRCrtc` of the specified monitor.
*
* @return The `RRCrtc` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RRCrtc glfwGetX11Adapter(GLFWmonitor* monitor);
/*! @brief Returns the `RROutput` of the specified monitor.
*
* @return The `RROutput` of the specified monitor, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.1.
*
* @ingroup native
*/
GLFWAPI RROutput glfwGetX11Monitor(GLFWmonitor* monitor);
/*! @brief Returns the `Window` of the specified window.
*
* @return The `Window` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI Window glfwGetX11Window(GLFWwindow* window);
/*! @brief Sets the current primary selection to the specified string.
*
* @param[in] string A UTF-8 encoded string.
*
* @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref
* GLFW_PLATFORM_ERROR.
*
* @pointer_lifetime The specified string is copied before this function
* returns.
*
* @thread_safety This function must only be called from the main thread.
*
* @sa @ref clipboard
* @sa glfwGetX11SelectionString
* @sa glfwSetClipboardString
*
* @since Added in version 3.3.
*
* @ingroup native
*/
GLFWAPI void glfwSetX11SelectionString(const char* string);
/*! @brief Returns the contents of the current primary selection as a string.
*
* If the selection is empty or if its contents cannot be converted, `NULL`
* is returned and a @ref GLFW_FORMAT_UNAVAILABLE error is generated.
*
* @return The contents of the selection as a UTF-8 encoded string, or `NULL`
* if an [error](@ref error_handling) occurred.
*
* @errors Possible errors include @ref GLFW_NOT_INITIALIZED and @ref
* GLFW_PLATFORM_ERROR.
*
* @pointer_lifetime The returned string is allocated and freed by GLFW. You
* should not free it yourself. It is valid until the next call to @ref
* glfwGetX11SelectionString or @ref glfwSetX11SelectionString, or until the
* library is terminated.
*
* @thread_safety This function must only be called from the main thread.
*
* @sa @ref clipboard
* @sa glfwSetX11SelectionString
* @sa glfwGetClipboardString
*
* @since Added in version 3.3.
*
* @ingroup native
*/
GLFWAPI const char* glfwGetX11SelectionString(void);
#endif
#if defined(GLFW_EXPOSE_NATIVE_GLX)
/*! @brief Returns the `GLXContext` of the specified window.
*
* @return The `GLXContext` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI GLXContext glfwGetGLXContext(GLFWwindow* window);
/*! @brief Returns the `GLXWindow` of the specified window.
*
* @return The `GLXWindow` of the specified window, or `None` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI GLXWindow glfwGetGLXWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_WAYLAND)
/*! @brief Returns the `struct wl_display*` used by GLFW.
*
* @return The `struct wl_display*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_display* glfwGetWaylandDisplay(void);
/*! @brief Returns the `struct wl_output*` of the specified monitor.
*
* @return The `struct wl_output*` of the specified monitor, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_output* glfwGetWaylandMonitor(GLFWmonitor* monitor);
/*! @brief Returns the main `struct wl_surface*` of the specified window.
*
* @return The main `struct wl_surface*` of the specified window, or `NULL` if
* an [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI struct wl_surface* glfwGetWaylandWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_MIR)
/*! @brief Returns the `MirConnection*` used by GLFW.
*
* @return The `MirConnection*` used by GLFW, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirConnection* glfwGetMirDisplay(void);
/*! @brief Returns the Mir output ID of the specified monitor.
*
* @return The Mir output ID of the specified monitor, or zero if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI int glfwGetMirMonitor(GLFWmonitor* monitor);
/*! @brief Returns the `MirWindow*` of the specified window.
*
* @return The `MirWindow*` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.2.
*
* @ingroup native
*/
GLFWAPI MirWindow* glfwGetMirWindow(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_EGL)
/*! @brief Returns the `EGLDisplay` used by GLFW.
*
* @return The `EGLDisplay` used by GLFW, or `EGL_NO_DISPLAY` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLDisplay glfwGetEGLDisplay(void);
/*! @brief Returns the `EGLContext` of the specified window.
*
* @return The `EGLContext` of the specified window, or `EGL_NO_CONTEXT` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLContext glfwGetEGLContext(GLFWwindow* window);
/*! @brief Returns the `EGLSurface` of the specified window.
*
* @return The `EGLSurface` of the specified window, or `EGL_NO_SURFACE` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.0.
*
* @ingroup native
*/
GLFWAPI EGLSurface glfwGetEGLSurface(GLFWwindow* window);
#endif
#if defined(GLFW_EXPOSE_NATIVE_OSMESA)
/*! @brief Retrieves the color buffer associated with the specified window.
*
* @param[in] window The window whose color buffer to retrieve.
* @param[out] width Where to store the width of the color buffer, or `NULL`.
* @param[out] height Where to store the height of the color buffer, or `NULL`.
* @param[out] format Where to store the OSMesa pixel format of the color
* buffer, or `NULL`.
* @param[out] buffer Where to store the address of the color buffer, or
* `NULL`.
* @return `GLFW_TRUE` if successful, or `GLFW_FALSE` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.3.
*
* @ingroup native
*/
GLFWAPI int glfwGetOSMesaColorBuffer(GLFWwindow* window, int* width, int* height, int* format, void** buffer);
/*! @brief Retrieves the depth buffer associated with the specified window.
*
* @param[in] window The window whose depth buffer to retrieve.
* @param[out] width Where to store the width of the depth buffer, or `NULL`.
* @param[out] height Where to store the height of the depth buffer, or `NULL`.
* @param[out] bytesPerValue Where to store the number of bytes per depth
* buffer element, or `NULL`.
* @param[out] buffer Where to store the address of the depth buffer, or
* `NULL`.
* @return `GLFW_TRUE` if successful, or `GLFW_FALSE` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.3.
*
* @ingroup native
*/
GLFWAPI int glfwGetOSMesaDepthBuffer(GLFWwindow* window, int* width, int* height, int* bytesPerValue, void** buffer);
/*! @brief Returns the `OSMesaContext` of the specified window.
*
* @return The `OSMesaContext` of the specified window, or `NULL` if an
* [error](@ref error_handling) occurred.
*
* @thread_safety This function may be called from any thread. Access is not
* synchronized.
*
* @since Added in version 3.3.
*
* @ingroup native
*/
GLFWAPI OSMesaContext glfwGetOSMesaContext(GLFWwindow* window);
#endif
#ifdef __cplusplus
}
#endif
#endif /* _glfw3_native_h_ */

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,152 @@
/*******************************************************************************************
*
* raylib [audio] example - Using raudio module as standalone module
*
* NOTE: This example does not require any graphic device, it can run directly on console.
*
* DEPENDENCIES:
* miniaudio.h - Audio device management lib (https://github.com/dr-soft/miniaudio)
* stb_vorbis.h - Ogg audio files loading (http://www.nothings.org/stb_vorbis/)
* dr_wav.h - WAV audio file loading (https://github.com/mackron/dr_libs)
* dr_mp3.h - MP3 audio file loading (https://github.com/mackron/dr_libs)
* dr_flac.h - FLAC audio file loading (https://github.com/mackron/dr_libs)
* jar_xm.h - XM module file loading
* jar_mod.h - MOD audio file loading
*
* COMPILATION:
* gcc -o raudio_standalone.exe raudio_standalone.c ..\..\src\raudio.c /
* -I..\..\src -I..\..\src\external -L. -Wall -std=c99 -DRAUDIO_STANDALONE /
* -DSUPPORT_FILEFORMAT_WAV -DSUPPORT_FILEFORMAT_OGG -DSUPPORT_FILEFORMAT_MP3
*
* LICENSE: zlib/libpng
*
* 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-2020 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.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
********************************************************************************************/
#include "raudio.h" // raylib audio library
#include <stdio.h> // Required for: printf()
#if defined(_WIN32)
#include <conio.h> // Windows only, no stardard library
#else
// Required for kbhit() function in non-Windows platforms
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#endif
#define KEY_ESCAPE 27
//----------------------------------------------------------------------------------
// Module Functions Declaration
//----------------------------------------------------------------------------------
#if !defined(_WIN32)
static int kbhit(void); // Check if a key has been pressed
static char getch(); // Get pressed character
#else
#define kbhit _kbhit
#define getch _getch
#endif
//------------------------------------------------------------------------------------
// Program main entry point
//------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// Initialization
//--------------------------------------------------------------------------------------
static unsigned char key = 0;
InitAudioDevice();
Sound fxWav = LoadSound("resources/audio/weird.wav"); // Load WAV audio file
Sound fxOgg = LoadSound("resources/audio/target.ogg"); // Load OGG audio file
Music music = LoadMusicStream("resources/audio/country.mp3");
PlayMusicStream(music);
printf("\nPress s or d to play sounds, ESC to stop...\n");
//--------------------------------------------------------------------------------------
// Main loop
while (key != KEY_ESCAPE)
{
if (kbhit()) key = getch();
if ((key == 's') || (key == 'S')) PlaySound(fxWav);
if ((key == 'd') || (key == 'D')) PlaySound(fxOgg);
key = 0;
UpdateMusicStream(music);
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadSound(fxWav); // Unload sound data
UnloadSound(fxOgg); // Unload sound data
UnloadMusicStream(music); // Unload music stream data
CloseAudioDevice();
//--------------------------------------------------------------------------------------
return 0;
}
//----------------------------------------------------------------------------------
// Module Functions Definition
//----------------------------------------------------------------------------------
#if !defined(_WIN32)
// Check if a key has been pressed
static int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if (ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
// Get pressed character
static char getch() { return getchar(); }
#endif

View file

@ -0,0 +1,152 @@
/*******************************************************************************************
*
* raylib [shaders] example - OpenGL point particle system
*
* This example has been created using raylib 3.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Stephan Soller (@arkanis - http://arkanis.de/)
* and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Stephan Soller (@arkanis) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* Mixes raylib and plain OpenGL code to draw a GL_POINTS based particle system. The
* primary point is to demonstrate raylib and OpenGL interop.
*
* rlgl batched draw operations internally so we have to flush the current batch before
* doing our own OpenGL work (rlDrawRenderBatchActive()).
*
* The example also demonstrates how to get the current model view projection matrix of
* raylib. That way raylib cameras and so on work as expected.
*
********************************************************************************************/
#include "raylib.h"
#include "rlgl.h" // Required for: rlDrawRenderBatchActive(), rlGetMatrixModelview(), rlGetMatrixProjection()
#if defined(__APPLE__)
#include <OpenGL/gl3.h> // OpenGL 3 library for OSX
#include <OpenGL/gl3ext.h> // OpenGL 3 extensions library for OSX
#else
#include "glad.h" // Required for: OpenGL functionality
#endif
#include "raymath.h" // Required for: MatrixMultiply(), MatrixToFloat()
#if defined(PLATFORM_DESKTOP)
#define GLSL_VERSION 330
#else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB
#define GLSL_VERSION 100
#endif
#define MAX_PARTICLES 1000
// Particle type
typedef struct Particle {
float x;
float y;
float period;
} Particle;
int main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - point particles");
Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/point_particle.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/point_particle.fs", GLSL_VERSION));
int currentTimeLoc = GetShaderLocation(shader, "currentTime");
int colorLoc = GetShaderLocation(shader, "color");
// Initialize the vertex buffer for the particles and assign each particle random values
Particle particles[MAX_PARTICLES] = { 0 };
for (int i = 0; i < MAX_PARTICLES; i++)
{
particles[i].x = (float)GetRandomValue(20, screenWidth - 20);
particles[i].y = (float)GetRandomValue(50, screenHeight - 20);
// Give each particle a slightly different period. But don't spread it to much.
// This way the particles line up every so often and you get a glimps of what is going on.
particles[i].period = (float)GetRandomValue(10, 30)/10.0f;
}
// Create a plain OpenGL vertex buffer with the data and an vertex array object
// that feeds the data from the buffer into the vertexPosition shader attribute.
GLuint vao = 0;
GLuint vbo = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, MAX_PARTICLES*sizeof(Particle), particles, GL_STATIC_DRAW);
// Note: LoadShader() automatically fetches the attribute index of "vertexPosition" and saves it in shader.locs[SHADER_LOC_VERTEX_POSITION]
glVertexAttribPointer(shader.locs[SHADER_LOC_VERTEX_POSITION], 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Allows the vertex shader to set the point size of each particle individually
glEnable(GL_PROGRAM_POINT_SIZE);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(WHITE);
DrawRectangle(10, 10, 210, 30, MAROON);
DrawText(TextFormat("%zu particles in one vertex buffer", MAX_PARTICLES), 20, 20, 10, RAYWHITE);
rlDrawRenderBatchActive(); // Draw iternal buffers data (previous draw calls)
// Switch to plain OpenGL
//------------------------------------------------------------------------------
glUseProgram(shader.id);
glUniform1f(currentTimeLoc, GetTime());
Vector4 color = ColorNormalize((Color){ 255, 0, 0, 128 });
glUniform4fv(colorLoc, 1, (float *)&color);
// Get the current modelview and projection matrix so the particle system is displayed and transformed
Matrix modelViewProjection = MatrixMultiply(rlGetMatrixModelview(), rlGetMatrixProjection());
glUniformMatrix4fv(shader.locs[SHADER_LOC_MATRIX_MVP], 1, false, MatrixToFloat(modelViewProjection));
glBindVertexArray(vao);
glDrawArrays(GL_POINTS, 0, MAX_PARTICLES);
glBindVertexArray(0);
glUseProgram(0);
//------------------------------------------------------------------------------
DrawFPS(screenWidth - 100, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
glDeleteBuffers(1, &vbo);
glDeleteVertexArrays(1, &vao);
UnloadShader(shader); // Unload shader
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 KiB

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,16 @@
#version 100
precision mediump float;
// Input uniform values
uniform vec4 color;
// NOTE: Add here your custom variables
void main()
{
// Each point is drawn as a screen space square of gl_PointSize size. gl_PointCoord contains where we are inside of
// it. (0, 0) is the top left, (1, 1) the bottom right corner.
// Draw each point as a colored circle with alpha 1.0 in the center and 0.0 at the outer edges.
gl_FragColor = vec4(color.rgb, color.a * (1.0 - length(gl_PointCoord.xy - vec2(0.5))*2.0));
}

View file

@ -0,0 +1,24 @@
#version 100
// Input vertex attributes
attribute vec3 vertexPosition;
// Input uniform values
uniform mat4 mvp;
uniform float currentTime;
// NOTE: Add here your custom variables
void main()
{
// Unpack data from vertexPosition
vec2 pos = vertexPosition.xy;
float period = vertexPosition.z;
// Calculate final vertex position (jiggle it around a bit horizontally)
pos += vec2(100.0, 0.0) * sin(period * currentTime);
gl_Position = mvp * vec4(pos.x, pos.y, 0.0, 1.0);
// Calculate the screen space size of this particle (also vary it over time)
gl_PointSize = 10.0 - 5.0 * abs(sin(period * currentTime));
}

View file

@ -0,0 +1,17 @@
#version 330
// Input uniform values
uniform vec4 color;
// Output fragment color
out vec4 finalColor;
// NOTE: Add here your custom variables
void main()
{
// Each point is drawn as a screen space square of gl_PointSize size. gl_PointCoord contains where we are inside of
// it. (0, 0) is the top left, (1, 1) the bottom right corner.
// Draw each point as a colored circle with alpha 1.0 in the center and 0.0 at the outer edges.
finalColor = vec4(color.rgb, color.a * (1 - length(gl_PointCoord.xy - vec2(0.5))*2));
}

View file

@ -0,0 +1,24 @@
#version 330
// Input vertex attributes
in vec3 vertexPosition;
// Input uniform values
uniform mat4 mvp;
uniform float currentTime;
// NOTE: Add here your custom variables
void main()
{
// Unpack data from vertexPosition
vec2 pos = vertexPosition.xy;
float period = vertexPosition.z;
// Calculate final vertex position (jiggle it around a bit horizontally)
pos += vec2(100, 0) * sin(period * currentTime);
gl_Position = mvp * vec4(pos, 0.0, 1.0);
// Calculate the screen space size of this particle (also vary it over time)
gl_PointSize = 10 - 5 * abs(sin(period * currentTime));
}

View file

@ -0,0 +1,41 @@
#version 430
// Game of Life logic shader
#define GOL_WIDTH 768
layout (local_size_x = 16, local_size_y = 16, local_size_z = 1) in;
layout(std430, binding = 1) readonly restrict buffer golLayout {
uint golBuffer[]; // golBuffer[x, y] = golBuffer[x + gl_NumWorkGroups.x * y]
};
layout(std430, binding = 2) writeonly restrict buffer golLayout2 {
uint golBufferDest[]; // golBufferDest[x, y] = golBufferDest[x + gl_NumWorkGroups.x * y]
};
#define fetchGol(x, y) ((((x) < 0) || ((y) < 0) || ((x) > GOL_WIDTH) || ((y) > GOL_WIDTH)) \
? (0) \
: golBuffer[(x) + GOL_WIDTH * (y)])
#define setGol(x, y, value) golBufferDest[(x) + GOL_WIDTH*(y)] = value
void main()
{
uint neighbourCount = 0;
uint x = gl_GlobalInvocationID.x;
uint y = gl_GlobalInvocationID.y;
neighbourCount += fetchGol(x - 1, y - 1); // Top left
neighbourCount += fetchGol(x, y - 1); // Top middle
neighbourCount += fetchGol(x + 1, y - 1); // Top right
neighbourCount += fetchGol(x - 1, y); // Left
neighbourCount += fetchGol(x + 1, y); // Right
neighbourCount += fetchGol(x - 1, y + 1); // Bottom left
neighbourCount += fetchGol(x, y + 1); // Bottom middle
neighbourCount += fetchGol(x + 1, y + 1); // Bottom right
if (neighbourCount == 3) setGol(x, y, 1);
else if (neighbourCount == 2) setGol(x, y, fetchGol(x, y));
else setGol(x, y, 0);
}

View file

@ -0,0 +1,29 @@
#version 430
// Game of Life rendering shader
// Just renders the content of the ssbo at binding 1 to screen
#define GOL_WIDTH 768
// Input vertex attributes (from vertex shader)
in vec2 fragTexCoord;
// Output fragment color
out vec4 finalColor;
// Input game of life grid.
layout(std430, binding = 1) readonly buffer golLayout
{
uint golBuffer[];
};
// Output resolution
uniform vec2 resolution;
void main()
{
ivec2 coords = ivec2(fragTexCoord*resolution);
if ((golBuffer[coords.x + coords.y*uvec2(resolution).x]) == 1) finalColor = vec4(1.0);
else finalColor = vec4(0.0, 0.0, 0.0, 1.0);
}

View file

@ -0,0 +1,51 @@
#version 430
// Game of life transfert shader
#define GOL_WIDTH 768
// Game Of Life Update Command
// NOTE: matches the structure defined on main program
struct GolUpdateCmd {
uint x; // x coordinate of the gol command
uint y; // y coordinate of the gol command
uint w; // width of the filled zone
uint enabled; // whether to enable or disable zone
};
// Local compute unit size
layout (local_size_x = 1, local_size_y = 1, local_size_z = 1) in;
// Output game of life grid buffer
layout(std430, binding = 1) buffer golBufferLayout
{
uint golBuffer[]; // golBuffer[x, y] = golBuffer[x + GOL_WIDTH * y]
};
// Command buffer
layout(std430, binding = 3) readonly restrict buffer golUpdateLayout
{
uint count;
GolUpdateCmd commands[];
};
#define isInside(x, y) (((x) >= 0) && ((y) >= 0) && ((x) < GOL_WIDTH) && ((y) < GOL_WIDTH))
#define getBufferIndex(x, y) ((x) + GOL_WIDTH * (y))
void main()
{
uint cmdIndex = gl_GlobalInvocationID.x;
GolUpdateCmd cmd = commands[cmdIndex];
for (uint x = cmd.x; x < (cmd.x + cmd.w); x++)
{
for (uint y = cmd.y; y < (cmd.y + cmd.w); y++)
{
if (isInside(x, y))
{
if (cmd.enabled != 0) atomicOr(golBuffer[getBufferIndex(x, y)], 1);
else atomicAnd(golBuffer[getBufferIndex(x, y)], 0);
}
}
}
}

View file

@ -0,0 +1,173 @@
/*******************************************************************************************
*
* raylib [rlgl] example - compute shader - Conway's Game of Life
*
* NOTE: This example requires raylib OpenGL 4.3 versions for compute shaders support,
* shaders used in this example are #version 430 (OpenGL 4.3)
*
* This example has been created using raylib 4.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Teddy Astie (@tsnake41) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Teddy Astie (@tsnake41)
*
********************************************************************************************/
#include "raylib.h"
#include "rlgl.h"
#include <stdlib.h>
// IMPORTANT: This must match gol*.glsl GOL_WIDTH constant.
// This must be a multiple of 16 (check golLogic compute dispatch).
#define GOL_WIDTH 768
// Maximum amount of queued draw commands (squares draw from mouse down events).
#define MAX_BUFFERED_TRANSFERTS 48
// Game Of Life Update Command
typedef struct GolUpdateCmd {
unsigned int x; // x coordinate of the gol command
unsigned int y; // y coordinate of the gol command
unsigned int w; // width of the filled zone
unsigned int enabled; // whether to enable or disable zone
} GolUpdateCmd;
// Game Of Life Update Commands SSBO
typedef struct GolUpdateSSBO {
unsigned int count;
GolUpdateCmd commands[MAX_BUFFERED_TRANSFERTS];
} GolUpdateSSBO;
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
InitWindow(GOL_WIDTH, GOL_WIDTH, "raylib [rlgl] example - compute shader - game of life");
const Vector2 resolution = { GOL_WIDTH, GOL_WIDTH };
unsigned int brushSize = 8;
// Game of Life logic compute shader
char *golLogicCode = LoadFileText("resources/shaders/glsl430/gol.glsl");
unsigned int golLogicShader = rlCompileShader(golLogicCode, RL_COMPUTE_SHADER);
unsigned int golLogicProgram = rlLoadComputeShaderProgram(golLogicShader);
UnloadFileText(golLogicCode);
// Game of Life logic compute shader
Shader golRenderShader = LoadShader(NULL, "resources/shaders/glsl430/gol_render.glsl");
int resUniformLoc = GetShaderLocation(golRenderShader, "resolution");
// Game of Life transfert shader
char *golTransfertCode = LoadFileText("resources/shaders/glsl430/gol_transfert.glsl");
unsigned int golTransfertShader = rlCompileShader(golTransfertCode, RL_COMPUTE_SHADER);
unsigned int golTransfertProgram = rlLoadComputeShaderProgram(golTransfertShader);
UnloadFileText(golTransfertCode);
// SSBOs
unsigned int ssboA = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*sizeof(unsigned int), NULL, RL_DYNAMIC_COPY);
unsigned int ssboB = rlLoadShaderBuffer(GOL_WIDTH*GOL_WIDTH*sizeof(unsigned int), NULL, RL_DYNAMIC_COPY);
struct GolUpdateSSBO transfertBuffer;
transfertBuffer.count = 0;
int transfertSSBO = rlLoadShaderBuffer(sizeof(struct GolUpdateSSBO), NULL, RL_DYNAMIC_COPY);
// Create a white texture of the size of the window to update
// each pixel of the window using the fragment shader
Image whiteImage = GenImageColor(GOL_WIDTH, GOL_WIDTH, WHITE);
Texture whiteTex = LoadTextureFromImage(whiteImage);
UnloadImage(whiteImage);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
brushSize += (int)GetMouseWheelMove();
if ((IsMouseButtonDown(MOUSE_BUTTON_LEFT) || IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
&& (transfertBuffer.count < MAX_BUFFERED_TRANSFERTS))
{
// Buffer a new command
transfertBuffer.commands[transfertBuffer.count].x = GetMouseX() - brushSize/2;
transfertBuffer.commands[transfertBuffer.count].y = GetMouseY() - brushSize/2;
transfertBuffer.commands[transfertBuffer.count].w = brushSize;
transfertBuffer.commands[transfertBuffer.count].enabled = IsMouseButtonDown(MOUSE_BUTTON_LEFT);
transfertBuffer.count++;
}
else if (transfertBuffer.count > 0)
{
// Process transfert buffer
// Send SSBO buffer to GPU
rlUpdateShaderBufferElements(transfertSSBO, &transfertBuffer, sizeof(struct GolUpdateSSBO), 0);
// Process ssbo command
rlEnableShader(golTransfertProgram);
rlBindShaderBuffer(ssboA, 1);
rlBindShaderBuffer(transfertSSBO, 3);
rlComputeShaderDispatch(transfertBuffer.count, 1, 1); // each GPU unit will process a command
rlDisableShader();
transfertBuffer.count = 0;
}
else
{
// Process game of life logic
rlEnableShader(golLogicProgram);
rlBindShaderBuffer(ssboA, 1);
rlBindShaderBuffer(ssboB, 2);
rlComputeShaderDispatch(GOL_WIDTH/16, GOL_WIDTH/16, 1);
rlDisableShader();
// ssboA <-> ssboB
int temp = ssboA;
ssboA = ssboB;
ssboB = temp;
}
rlBindShaderBuffer(ssboA, 1);
SetShaderValue(golRenderShader, resUniformLoc, &resolution, SHADER_UNIFORM_VEC2);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(BLANK);
BeginShaderMode(golRenderShader);
DrawTexture(whiteTex, 0, 0, WHITE);
EndShaderMode();
DrawRectangleLines(GetMouseX() - brushSize/2, GetMouseY() - brushSize/2, brushSize, brushSize, RED);
DrawText("Use Mouse wheel to increase/decrease brush size", 10, 10, 20, WHITE);
DrawFPS(GetScreenWidth() - 100, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
// Unload shader buffers objects.
rlUnloadShaderBuffer(ssboA);
rlUnloadShaderBuffer(ssboB);
rlUnloadShaderBuffer(transfertSSBO);
// Unload compute shader programs
rlUnloadShaderProgram(golTransfertProgram);
rlUnloadShaderProgram(golLogicProgram);
UnloadTexture(whiteTex); // Unload white texture
UnloadShader(golRenderShader); // Unload rendering fragment shader
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

View file

@ -0,0 +1,469 @@
/*******************************************************************************************
*
* raylib [rlgl] example - Using rlgl module as standalone module
*
* rlgl library is an abstraction layer for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0)
* that provides a pseudo-OpenGL 1.1 immediate-mode style API (rlVertex, rlTranslate, rlRotate...)
*
* NOTE: This example requires OpenGL 3.3 or OpenGL ES 2.0 for shaders support,
* OpenGL 1.1 does not support shaders but it can also be used.
*
* DEPENDENCIES:
* glfw3 - Windows and context initialization library
* rlgl.h - OpenGL abstraction layer to OpenGL 1.1, 3.3 or ES2
* glad.h - OpenGL extensions initialization library (required by rlgl)
* raymath.h - 3D math library
*
* WINDOWS COMPILATION:
* gcc -o rlgl_standalone.exe rlgl_standalone.c -s -Iexternal\include -I..\..\src \
* -L. -Lexternal\lib -lglfw3 -lopengl32 -lgdi32 -Wall -std=c99 -DGRAPHICS_API_OPENGL_33
*
* APPLE COMPILATION:
* gcc -o rlgl_standalone rlgl_standalone.c -I../../src -Iexternal/include -Lexternal/lib \
* -lglfw3 -framework CoreVideo -framework OpenGL -framework IOKit -framework Cocoa
* -Wno-deprecated-declarations -std=c99 -DGRAPHICS_API_OPENGL_33
*
*
* LICENSE: zlib/libpng
*
* 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-2021 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.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you
* wrote the original software. If you use this software in a product, an acknowledgment
* in the product documentation would be appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented
* as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*
********************************************************************************************/
// NOTE: rlgl can be configured just re-defining the following values:
//#define RL_DEFAULT_BATCH_BUFFER_ELEMENTS 8192 // Default internal render batch elements limits
//#define RL_DEFAULT_BATCH_BUFFERS 1 // Default number of batch buffers (multi-buffering)
//#define RL_DEFAULT_BATCH_DRAWCALLS 256 // Default number of batch draw calls (by state changes: mode, texture)
//#define RL_DEFAULT_BATCH_MAX_TEXTURE_UNITS 4 // Maximum number of textures units that can be activated on batch drawing (SetShaderValueTexture())
//#define RL_MAX_MATRIX_STACK_SIZE 32 // Maximum size of internal Matrix stack
//#define RL_MAX_SHADER_LOCATIONS 32 // Maximum number of shader locations supported
//#define RL_CULL_DISTANCE_NEAR 0.01 // Default projection matrix near cull distance
//#define RL_CULL_DISTANCE_FAR 1000.0 // Default projection matrix far cull distance
#define RLGL_IMPLEMENTATION
#include "rlgl.h" // OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2
#define RAYMATH_STATIC_INLINE
#include "raymath.h" // Vector2, Vector3, Quaternion and Matrix functionality
#if defined(__EMSCRIPTEN__)
#define GLFW_INCLUDE_ES2
#endif
#include "GLFW/glfw3.h" // Windows/Context and inputs management
#include <stdio.h> // Required for: printf()
#define RED (Color){ 230, 41, 55, 255 } // Red
#define RAYWHITE (Color){ 245, 245, 245, 255 } // My own White (raylib logo)
#define DARKGRAY (Color){ 80, 80, 80, 255 } // Dark Gray
//----------------------------------------------------------------------------------
// Structures Definition
//----------------------------------------------------------------------------------
// Color, 4 components, R8G8B8A8 (32bit)
typedef struct Color {
unsigned char r; // Color red value
unsigned char g; // Color green value
unsigned char b; // Color blue value
unsigned char a; // Color alpha value
} Color;
// Camera type, defines a camera position/orientation in 3d space
typedef struct Camera {
Vector3 position; // Camera position
Vector3 target; // Camera target it looks-at
Vector3 up; // Camera up vector (rotation over its axis)
float fovy; // Camera field-of-view apperture in Y (degrees) in perspective, used as near plane width in orthographic
int projection; // Camera projection: CAMERA_PERSPECTIVE or CAMERA_ORTHOGRAPHIC
} Camera;
//----------------------------------------------------------------------------------
// Module specific Functions Declaration
//----------------------------------------------------------------------------------
static void ErrorCallback(int error, const char *description);
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods);
// Drawing functions (uses rlgl functionality)
static void DrawGrid(int slices, float spacing);
static void DrawCube(Vector3 position, float width, float height, float length, Color color);
static void DrawCubeWires(Vector3 position, float width, float height, float length, Color color);
static void DrawRectangleV(Vector2 position, Vector2 size, Color color);
// NOTE: We use raymath to get this functionality but it could be implemented in this module
//static Matrix MatrixIdentity(void);
//static Matrix MatrixOrtho(double left, double right, double bottom, double top, double near, double far);
//static Matrix MatrixPerspective(double fovy, double aspect, double near, double far);
//static Matrix MatrixLookAt(Vector3 eye, Vector3 target, Vector3 up);
//----------------------------------------------------------------------------------
// Main Entry point
//----------------------------------------------------------------------------------
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// GLFW3 Initialization + OpenGL 3.3 Context + Extensions
//--------------------------------------------------------
glfwSetErrorCallback(ErrorCallback);
if (!glfwInit())
{
printf("GLFW3: Can not initialize GLFW\n");
return 1;
}
else printf("GLFW3: GLFW initialized successfully\n");
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_DEPTH_BITS, 16);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
//glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#if defined(__APPLE__)
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
#endif
GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "rlgl standalone", NULL, NULL);
if (!window)
{
glfwTerminate();
return 2;
}
else printf("GLFW3: Window created successfully\n");
glfwSetWindowPos(window, 200, 200);
glfwSetKeyCallback(window, KeyCallback);
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
// Load OpenGL 3.3 supported extensions
rlLoadExtensions(glfwGetProcAddress);
//--------------------------------------------------------
// Initialize OpenGL context (states and resources)
rlglInit(screenWidth, screenHeight);
// Initialize viewport and internal projection/modelview matrices
rlViewport(0, 0, screenWidth, screenHeight);
rlMatrixMode(RL_PROJECTION); // Switch to PROJECTION matrix
rlLoadIdentity(); // Reset current matrix (PROJECTION)
rlOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); // Orthographic projection with top-left corner at (0,0)
rlMatrixMode(RL_MODELVIEW); // Switch back to MODELVIEW matrix
rlLoadIdentity(); // Reset current matrix (MODELVIEW)
rlClearColor(245, 245, 245, 255); // Define clear color
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
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)
camera.fovy = 45.0f; // Camera field-of-view Y
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; // Cube default position (center)
//--------------------------------------------------------------------------------------
// Main game loop
while (!glfwWindowShouldClose(window))
{
// Update
//----------------------------------------------------------------------------------
//camera.position.x += 0.01f;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
rlClearScreenBuffers(); // Clear current framebuffer
// Draw '3D' elements in the scene
//-----------------------------------------------
// Calculate projection matrix (from perspective) and view matrix from camera look at
Matrix matProj = MatrixPerspective((double)(camera.fovy*DEG2RAD), (double)screenWidth/(double)screenHeight, 0.01, 1000.0);
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader)
rlSetMatrixProjection(matProj); // Set internal projection matrix (default shader)
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, RAYWHITE);
DrawGrid(10, 1.0f);
// Draw internal render batch buffers (3D data)
rlDrawRenderBatchActive();
//-----------------------------------------------
// Draw '2D' elements in the scene (GUI)
//-----------------------------------------------
#define RLGL_SET_MATRIX_MANUALLY
#if defined(RLGL_SET_MATRIX_MANUALLY)
matProj = MatrixOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0);
matView = MatrixIdentity();
rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader)
rlSetMatrixProjection(matProj); // Set internal projection matrix (default shader)
#else // Let rlgl generate and multiply matrix internally
rlMatrixMode(RL_PROJECTION); // Enable internal projection matrix
rlLoadIdentity(); // Reset internal projection matrix
rlOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0); // Recalculate internal projection matrix
rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix
rlLoadIdentity(); // Reset internal modelview matrix
#endif
DrawRectangleV((Vector2){ 10.0f, 10.0f }, (Vector2){ 780.0f, 20.0f }, DARKGRAY);
// Draw internal render batch buffers (2D data)
rlDrawRenderBatchActive();
//-----------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
rlglClose(); // Unload rlgl internal buffers and default shader/texture
glfwDestroyWindow(window); // Close window
glfwTerminate(); // Free GLFW3 resources
//--------------------------------------------------------------------------------------
return 0;
}
//----------------------------------------------------------------------------------
// Module specific Functions Definitions
//----------------------------------------------------------------------------------
// GLFW3: Error callback
static void ErrorCallback(int error, const char *description)
{
fprintf(stderr, "%s", description);
}
// GLFW3: Keyboard callback
static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
{
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
// Draw rectangle using rlgl OpenGL 1.1 style coding (translated to OpenGL 3.3 internally)
static void DrawRectangleV(Vector2 position, Vector2 size, Color color)
{
rlBegin(RL_TRIANGLES);
rlColor4ub(color.r, color.g, color.b, color.a);
rlVertex2f(position.x, position.y);
rlVertex2f(position.x, position.y + size.y);
rlVertex2f(position.x + size.x, position.y + size.y);
rlVertex2f(position.x, position.y);
rlVertex2f(position.x + size.x, position.y + size.y);
rlVertex2f(position.x + size.x, position.y);
rlEnd();
}
// Draw a grid centered at (0, 0, 0)
static void DrawGrid(int slices, float spacing)
{
int halfSlices = slices / 2;
rlBegin(RL_LINES);
for (int i = -halfSlices; i <= halfSlices; i++)
{
if (i == 0)
{
rlColor3f(0.5f, 0.5f, 0.5f);
rlColor3f(0.5f, 0.5f, 0.5f);
rlColor3f(0.5f, 0.5f, 0.5f);
rlColor3f(0.5f, 0.5f, 0.5f);
}
else
{
rlColor3f(0.75f, 0.75f, 0.75f);
rlColor3f(0.75f, 0.75f, 0.75f);
rlColor3f(0.75f, 0.75f, 0.75f);
rlColor3f(0.75f, 0.75f, 0.75f);
}
rlVertex3f((float)i*spacing, 0.0f, (float)-halfSlices*spacing);
rlVertex3f((float)i*spacing, 0.0f, (float)halfSlices*spacing);
rlVertex3f((float)-halfSlices*spacing, 0.0f, (float)i*spacing);
rlVertex3f((float)halfSlices*spacing, 0.0f, (float)i*spacing);
}
rlEnd();
}
// Draw cube
// NOTE: Cube position is the center position
static void DrawCube(Vector3 position, float width, float height, float length, Color color)
{
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
rlPushMatrix();
// NOTE: Be careful! Function order matters (rotate -> scale -> translate)
rlTranslatef(position.x, position.y, position.z);
//rlScalef(2.0f, 2.0f, 2.0f);
//rlRotatef(45, 0, 1, 0);
rlBegin(RL_TRIANGLES);
rlColor4ub(color.r, color.g, color.b, color.a);
// Front Face -----------------------------------------------------
rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
// Back Face ------------------------------------------------------
rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Left
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
// Top Face -------------------------------------------------------
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
rlVertex3f(x-width/2, y+height/2, z+length/2); // Bottom Left
rlVertex3f(x+width/2, y+height/2, z+length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
rlVertex3f(x+width/2, y+height/2, z+length/2); // Bottom Right
// Bottom Face ----------------------------------------------------
rlVertex3f(x-width/2, y-height/2, z-length/2); // Top Left
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left
rlVertex3f(x+width/2, y-height/2, z-length/2); // Top Right
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
rlVertex3f(x-width/2, y-height/2, z-length/2); // Top Left
// Right face -----------------------------------------------------
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Left
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Left
// Left Face ------------------------------------------------------
rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Right
rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Right
rlEnd();
rlPopMatrix();
}
// Draw cube wires
static void DrawCubeWires(Vector3 position, float width, float height, float length, Color color)
{
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
rlPushMatrix();
rlTranslatef(position.x, position.y, position.z);
//rlRotatef(45, 0, 1, 0);
rlBegin(RL_LINES);
rlColor4ub(color.r, color.g, color.b, color.a);
// Front Face -----------------------------------------------------
// Bottom Line
rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
// Left Line
rlVertex3f(x+width/2, y-height/2, z+length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right
// Top Line
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
// Right Line
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left
rlVertex3f(x-width/2, y-height/2, z+length/2); // Bottom Left
// Back Face ------------------------------------------------------
// Bottom Line
rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Left
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
// Left Line
rlVertex3f(x+width/2, y-height/2, z-length/2); // Bottom Right
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right
// Top Line
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
// Right Line
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left
rlVertex3f(x-width/2, y-height/2, z-length/2); // Bottom Left
// Top Face -------------------------------------------------------
// Left Line
rlVertex3f(x-width/2, y+height/2, z+length/2); // Top Left Front
rlVertex3f(x-width/2, y+height/2, z-length/2); // Top Left Back
// Right Line
rlVertex3f(x+width/2, y+height/2, z+length/2); // Top Right Front
rlVertex3f(x+width/2, y+height/2, z-length/2); // Top Right Back
// Bottom Face ---------------------------------------------------
// Left Line
rlVertex3f(x-width/2, y-height/2, z+length/2); // Top Left Front
rlVertex3f(x-width/2, y-height/2, z-length/2); // Top Left Back
// Right Line
rlVertex3f(x+width/2, y-height/2, z+length/2); // Top Right Front
rlVertex3f(x+width/2, y-height/2, z-length/2); // Top Right Back
rlEnd();
rlPopMatrix();
}