From 81897e77715c8d59382fe9d54641081c20e163ea Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 9 Mar 2017 13:13:13 +0100 Subject: Corrected bugs on RPI compilation --- src/core.c | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index a3b5f486..f955988a 100644 --- a/src/core.c +++ b/src/core.c @@ -583,12 +583,15 @@ void SetWindowIcon(Image image) // Set window position on screen (windowed mode) void SetWindowPosition(int x, int y) { +#if defined(PLATFORM_DESKTOP) glfwSetWindowPos(window, x, y); +#endif } // Set monitor for the current window (fullscreen mode) void SetWindowMonitor(int monitor) { +#if defined(PLATFORM_DESKTOP) int monitorCount; GLFWmonitor** monitors = glfwGetMonitors(&monitorCount); @@ -598,6 +601,7 @@ void SetWindowMonitor(int monitor) TraceLog(INFO, "Selected fullscreen monitor: [%i] %s", monitor, glfwGetMonitorName(monitors[monitor])); } else TraceLog(WARNING, "Selected monitor not found"); +#endif } // Get current screen width -- cgit v1.2.3 From 4ec65c0d25887c960583b996a7468a15712339f4 Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 9 Mar 2017 16:23:36 +0100 Subject: Corrected issue with reserved words: near, far --- src/core.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index f955988a..2b16d49e 100644 --- a/src/core.c +++ b/src/core.c @@ -291,7 +291,7 @@ static void InitTimer(void); // Initialize timer static double GetTime(void); // Returns time since InitTimer() was run static void Wait(float ms); // Wait for some milliseconds (stop program execution) static bool GetKeyStatus(int key); // Returns if a key has been pressed -static bool GetMouseButtonStatus(int button); // Returns if a mouse button has been pressed +static bool ButtonStatus(int button); // Returns if a mouse button has been pressed static void PollInputEvents(void); // Register user events static void SwapBuffers(void); // Copy back buffer to front buffers static void LogoAnimation(void); // Plays raylib logo appearing animation @@ -1129,16 +1129,16 @@ Ray GetMouseRay(Vector2 mousePosition, Camera camera) MatrixInvert(&matProjView); // Calculate far and near points - Quaternion near = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; - Quaternion far = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; + Quaternion nearPoint = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; + Quaternion farPoint = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; // Multiply points by unproject matrix - QuaternionTransform(&near, matProjView); - QuaternionTransform(&far, matProjView); + QuaternionTransform(&nearPoint, matProjView); + QuaternionTransform(&farPoint, matProjView); // Calculate normalized world points in vectors - Vector3 nearPoint = { near.x/near.w, near.y/near.w, near.z/near.w}; - Vector3 farPoint = { far.x/far.w, far.y/far.w, far.z/far.w}; + Vector3 nearPoint = { nearPoint.x/nearPoint.w, nearPoint.y/nearPoint.w, nearPoint.z/nearPoint.w}; + Vector3 farPoint = { farPoint.x/farPoint.w, farPoint.y/farPoint.w, farPoint.z/farPoint.w}; #endif // Calculate normalized direction vector -- cgit v1.2.3 From 7c888edba18c78e38829a752626b67c41e0c224a Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 9 Mar 2017 16:25:15 +0100 Subject: Corrected typo introduced in last commit --- src/core.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 2b16d49e..773bc15d 100644 --- a/src/core.c +++ b/src/core.c @@ -291,7 +291,7 @@ static void InitTimer(void); // Initialize timer static double GetTime(void); // Returns time since InitTimer() was run static void Wait(float ms); // Wait for some milliseconds (stop program execution) static bool GetKeyStatus(int key); // Returns if a key has been pressed -static bool ButtonStatus(int button); // Returns if a mouse button has been pressed +static bool GetMouseButtonStatus(int button); // Returns if a mouse button has been pressed static void PollInputEvents(void); // Register user events static void SwapBuffers(void); // Copy back buffer to front buffers static void LogoAnimation(void); // Plays raylib logo appearing animation -- cgit v1.2.3 From 7154b42f4885cea9cc2b7ef8f917fd063ee9fc47 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Thu, 9 Mar 2017 18:52:56 +0100 Subject: Corrected naming issue --- src/core.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 773bc15d..c0f5be83 100644 --- a/src/core.c +++ b/src/core.c @@ -1129,16 +1129,16 @@ Ray GetMouseRay(Vector2 mousePosition, Camera camera) MatrixInvert(&matProjView); // Calculate far and near points - Quaternion nearPoint = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; - Quaternion farPoint = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; + Quaternion qNear = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; + Quaternion qFar = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; // Multiply points by unproject matrix - QuaternionTransform(&nearPoint, matProjView); - QuaternionTransform(&farPoint, matProjView); + QuaternionTransform(&qNear, matProjView); + QuaternionTransform(&qFar, matProjView); // Calculate normalized world points in vectors - Vector3 nearPoint = { nearPoint.x/nearPoint.w, nearPoint.y/nearPoint.w, nearPoint.z/nearPoint.w}; - Vector3 farPoint = { farPoint.x/farPoint.w, farPoint.y/farPoint.w, farPoint.z/farPoint.w}; + Vector3 nearPoint = { qNear.x/qNear.w, qNear.y/qNear.w, qNear.z/qNear.w}; + Vector3 farPoint = { qFar.x/qFar.w, qFar.y/qFar.w, qFar.z/qFar.w}; #endif // Calculate normalized direction vector -- cgit v1.2.3 From 5d1f6616618d52f173a918f6a0378aeae1cb05ad Mon Sep 17 00:00:00 2001 From: raysan5 Date: Tue, 14 Mar 2017 01:05:22 +0100 Subject: Remove Oculus support from code Moved to custom example, now raylib only supports simulated VR rendering. Oculus code was too device dependant... waiting for OpenXR. --- examples/core_oculus_rift.c | 469 ++++++++++++++++++++++++++++- src/core.c | 7 +- src/raylib.h | 14 +- src/rlgl.c | 703 +++++++++----------------------------------- src/rlgl.h | 15 +- 5 files changed, 610 insertions(+), 598 deletions(-) (limited to 'src/core.c') diff --git a/examples/core_oculus_rift.c b/examples/core_oculus_rift.c index eb628cd7..f1b0bd3b 100644 --- a/examples/core_oculus_rift.c +++ b/examples/core_oculus_rift.c @@ -3,7 +3,12 @@ * raylib [core] example - Oculus Rift CV1 * * Compile example using: -* gcc -o $(NAME_PART).exe $(FILE_NAME) -L. -L..\src\external\OculusSDK\LibOVR -lLibOVRRT32_1 -lraylib -lglfw3 -lopengl32 -lgdi32 -std=c99 +* gcc -o $(NAME_PART).exe $(FILE_NAME) -I..\src\external -I..\src\external\OculusSDK\LibOVR\Include / +* -L. -L..\src\external\OculusSDK\LibOVR -lLibOVRRT32_1 -lraylib -lglfw3 -lopengl32 -lgdi32 -std=c99 / +* -Wl,-allow-multiple-definition +* +* #define SUPPORT_OCULUS_RIFT_CV1 / RLGL_OCULUS_SUPPORT +* Enable Oculus Rift CV1 functionality * * This example has been created using raylib 1.5 (www.raylib.com) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) @@ -14,6 +19,95 @@ #include "raylib.h" +#include "glad.h" // Required for: OpenGL types and functions declarations +#include "raymath.h" // Required for: Vector3, Quaternion and Matrix functionality + +#include // Required for: memset() +#include // Required for: exit() +#include // required for: vfprintf() +#include // Required for: va_list, va_start(), vfprintf(), va_end() + +#define RLGL_OCULUS_SUPPORT // Enable Oculus Rift code +#if defined(RLGL_OCULUS_SUPPORT) + #include "OVR_CAPI_GL.h" // Oculus SDK for OpenGL +#endif + +//---------------------------------------------------------------------------------- +// Defines and Macros +//---------------------------------------------------------------------------------- +// ... + +//---------------------------------------------------------------------------------- +// Types and Structures Definition +//---------------------------------------------------------------------------------- + +// TraceLog message types +typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; + +#if defined(RLGL_OCULUS_SUPPORT) +// Oculus buffer type +typedef struct OculusBuffer { + ovrTextureSwapChain textureChain; + GLuint depthId; + GLuint fboId; + int width; + int height; +} OculusBuffer; + +// Oculus mirror texture type +typedef struct OculusMirror { + ovrMirrorTexture texture; + GLuint fboId; + int width; + int height; +} OculusMirror; + +// Oculus layer type +typedef struct OculusLayer { + ovrViewScaleDesc viewScaleDesc; + ovrLayerEyeFov eyeLayer; // layer 0 + //ovrLayerQuad quadLayer; // TODO: layer 1: '2D' quad for GUI + Matrix eyeProjections[2]; + int width; + int height; +} OculusLayer; +#endif + +//---------------------------------------------------------------------------------- +// Global Variables Definition +//---------------------------------------------------------------------------------- +#if defined(RLGL_OCULUS_SUPPORT) +// OVR device variables +static ovrSession session; // Oculus session (pointer to ovrHmdStruct) +static ovrHmdDesc hmdDesc; // Oculus device descriptor parameters +static ovrGraphicsLuid luid; // Oculus locally unique identifier for the program (64 bit) +static OculusLayer layer; // Oculus drawing layer (similar to photoshop) +static OculusBuffer buffer; // Oculus internal buffers (texture chain and fbo) +static OculusMirror mirror; // Oculus mirror texture and fbo +static unsigned int frameIndex = 0; // Oculus frames counter, used to discard frames from chain +#endif + +//---------------------------------------------------------------------------------- +// Module specific Functions Declaration +//---------------------------------------------------------------------------------- +#if defined(RLGL_OCULUS_SUPPORT) +static bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) +static void CloseOculusDevice(void); // Close Oculus device +static void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking +static void BeginOculusDrawing(void); // Setup Oculus buffers for drawing +static void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror + +static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height); // Load Oculus required buffers +static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer); // Unload texture required buffers +static OculusMirror LoadOculusMirror(ovrSession session, int width, int height); // Load Oculus mirror buffers +static void UnloadOculusMirror(ovrSession session, OculusMirror mirror); // Unload Oculus mirror buffers +static void BlitOculusMirror(ovrSession session, OculusMirror mirror); // Copy Oculus screen buffer to mirror texture +static OculusLayer InitOculusLayer(ovrSession session); // Init Oculus layer (similar to photoshop) +static Matrix FromOvrMatrix(ovrMatrix4f ovrM); // Convert from Oculus ovrMatrix4f struct to raymath Matrix struct +#endif + +static void TraceLog(int msgType, const char *text, ...); + int main() { // Initialization @@ -25,8 +119,9 @@ int main() InitWindow(screenWidth, screenHeight, "raylib [core] example - oculus rift"); - // NOTE: If device is not available, it fallbacks to default device (simulator) - InitVrDevice(HMD_OCULUS_RIFT_CV1); // Init VR device (Oculus Rift CV1) + bool vrDeviceReady = InitOculusDevice(); // Init VR device Oculus Rift CV1 + + if (!vrDeviceReady) InitVrSimulator(HMD_OCULUS_RIFT_CV1); // Init VR simulator if device fails // Define the camera to look into our 3d world Camera camera; @@ -47,10 +142,10 @@ int main() { // Update //---------------------------------------------------------------------------------- - if (IsVrSimulator()) UpdateCamera(&camera); // Update camera (simulator mode) - else if (IsVrDeviceReady()) UpdateVrTracking(&camera); // Update camera with device tracking data - - if (IsKeyPressed(KEY_SPACE)) ToggleVrMode(); // Toggle VR mode + if (!vrDeviceReady) UpdateCamera(&camera); // Update camera (simulator mode) + else UpdateOculusTracking(&camera); // Update camera with device tracking data + + if (IsKeyPressed(KEY_SPACE)) ToggleVrMode(); // Toggle VR mode //---------------------------------------------------------------------------------- // Draw @@ -58,6 +153,9 @@ int main() BeginDrawing(); ClearBackground(RAYWHITE); + + if (vrDeviceReady) BeginOculusDrawing(); + else BeginVrDrawing(); Begin3dMode(camera); @@ -67,6 +165,9 @@ int main() DrawGrid(40, 1.0f); End3dMode(); + + if (vrDeviceReady) EndOculusDrawing(); + else EndVrDrawing(); DrawFPS(10, 10); @@ -76,10 +177,362 @@ int main() // De-Initialization //-------------------------------------------------------------------------------------- - CloseVrDevice(); // Close VR device + if (vrDeviceReady) CloseOculusDevice(); + else CloseVrSimulator(); CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- return 0; } + +//---------------------------------------------------------------------------------- +// Module specific Functions Definition +//---------------------------------------------------------------------------------- + +#if defined(RLGL_OCULUS_SUPPORT) +// Set internal projection and modelview matrix depending on eyes tracking data +static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) +{ + Matrix eyeProjection = matProjection; + Matrix eyeModelView = matModelView; + + glViewport(layer.eyeLayer.Viewport[eye].Pos.x, layer.eyeLayer.Viewport[eye].Pos.y, + layer.eyeLayer.Viewport[eye].Size.w, layer.eyeLayer.Viewport[eye].Size.h); + + Quaternion eyeRenderPose = (Quaternion){ layer.eyeLayer.RenderPose[eye].Orientation.x, + layer.eyeLayer.RenderPose[eye].Orientation.y, + layer.eyeLayer.RenderPose[eye].Orientation.z, + layer.eyeLayer.RenderPose[eye].Orientation.w }; + QuaternionInvert(&eyeRenderPose); + Matrix eyeOrientation = QuaternionToMatrix(eyeRenderPose); + Matrix eyeTranslation = MatrixTranslate(-layer.eyeLayer.RenderPose[eye].Position.x, + -layer.eyeLayer.RenderPose[eye].Position.y, + -layer.eyeLayer.RenderPose[eye].Position.z); + + Matrix eyeView = MatrixMultiply(eyeTranslation, eyeOrientation); // Matrix containing eye-head movement + eyeModelView = MatrixMultiply(matModelView, eyeView); // Combine internal camera matrix (modelview) wih eye-head movement + + eyeProjection = layer.eyeProjections[eye]; +} + +// Initialize Oculus device (returns true if success) +static bool InitOculusDevice(void) +{ + bool oculusReady = false; + + ovrResult result = ovr_Initialize(NULL); + + if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device"); + else + { + result = ovr_Create(&session, &luid); + if (OVR_FAILURE(result)) + { + TraceLog(WARNING, "OVR: Could not create Oculus session"); + ovr_Shutdown(); + } + else + { + hmdDesc = ovr_GetHmdDesc(session); + + TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName); + TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer); + TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId); + TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type); + //TraceLog(INFO, "OVR: Serial Number: %s", hmdDesc.SerialNumber); + TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h); + + // NOTE: Oculus mirror is set to defined screenWidth and screenHeight... + // ...ideally, it should be (hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2) + + // Initialize Oculus Buffers + layer = InitOculusLayer(session); + buffer = LoadOculusBuffer(session, layer.width, layer.height); + mirror = LoadOculusMirror(session, hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2); // NOTE: hardcoded... + layer.eyeLayer.ColorTexture[0] = buffer.textureChain; //SetOculusLayerTexture(eyeLayer, buffer.textureChain); + + // Recenter OVR tracking origin + ovr_RecenterTrackingOrigin(session); + + oculusReady = true; + } + } + + return oculusReady; +} + +// Close Oculus device (and unload buffers) +static void CloseOculusDevice(void) +{ + UnloadOculusMirror(session, mirror); // Unload Oculus mirror buffer + UnloadOculusBuffer(session, buffer); // Unload Oculus texture buffers + + ovr_Destroy(session); // Free Oculus session data + ovr_Shutdown(); // Close Oculus device connection +} + +// Update Oculus head position-orientation tracking +static void UpdateOculusTracking(Camera *camera) +{ + frameIndex++; + + ovrPosef eyePoses[2]; + ovr_GetEyePoses(session, frameIndex, ovrTrue, layer.viewScaleDesc.HmdToEyeOffset, eyePoses, &layer.eyeLayer.SensorSampleTime); + + layer.eyeLayer.RenderPose[0] = eyePoses[0]; + layer.eyeLayer.RenderPose[1] = eyePoses[1]; + + // TODO: Update external camera with eyePoses data (position, orientation) + // NOTE: We can simplify to simple camera if we consider IPD and HMD device configuration again later + // it will be useful for the user to draw, lets say, billboards oriented to camera + + // Get session status information + ovrSessionStatus sessionStatus; + ovr_GetSessionStatus(session, &sessionStatus); + + if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit..."); + if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session); + //if (sessionStatus.HmdPresent) // HMD is present. + //if (sessionStatus.DisplayLost) // HMD was unplugged or the display driver was manually disabled or encountered a TDR. + //if (sessionStatus.HmdMounted) // HMD is on the user's head. + //if (sessionStatus.IsVisible) // the game or experience has VR focus and is visible in the HMD. +} + +// Setup Oculus buffers for drawing +static void BeginOculusDrawing(void) +{ + GLuint currentTexId; + int currentIndex; + + ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, ¤tIndex); + ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, ¤tTexId); + + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, currentTexId, 0); + //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer.depthId, 0); // Already binded +} + +// Finish Oculus drawing and blit framebuffer to mirror +static void EndOculusDrawing(void) +{ + // Unbind current framebuffer (Oculus buffer) + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + + ovr_CommitTextureSwapChain(session, buffer.textureChain); + + ovrLayerHeader *layers = &layer.eyeLayer.Header; + ovr_SubmitFrame(session, frameIndex, &layer.viewScaleDesc, &layers, 1); + + // Blit mirror texture to back buffer + BlitOculusMirror(session, mirror); +} + +// Load Oculus required buffers: texture-swap-chain, fbo, texture-depth +static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height) +{ + OculusBuffer buffer; + buffer.width = width; + buffer.height = height; + + // Create OVR texture chain + ovrTextureSwapChainDesc desc = {}; + desc.Type = ovrTexture_2D; + desc.ArraySize = 1; + desc.Width = width; + desc.Height = height; + desc.MipLevels = 1; + desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; // Requires glEnable(GL_FRAMEBUFFER_SRGB); + desc.SampleCount = 1; + desc.StaticImage = ovrFalse; + + ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain); + + if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer"); + + int textureCount = 0; + ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount); + + if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures"); + + for (int i = 0; i < textureCount; ++i) + { + GLuint chainTexId; + ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, i, &chainTexId); + glBindTexture(GL_TEXTURE_2D, chainTexId); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + + glBindTexture(GL_TEXTURE_2D, 0); + + /* + // Setup framebuffer object (using depth texture) + glGenFramebuffers(1, &buffer.fboId); + glGenTextures(1, &buffer.depthId); + glBindTexture(GL_TEXTURE_2D, buffer.depthId); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, buffer.width, buffer.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); + */ + + // Setup framebuffer object (using depth renderbuffer) + glGenFramebuffers(1, &buffer.fboId); + glGenRenderbuffers(1, &buffer.depthId); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId); + glBindRenderbuffer(GL_RENDERBUFFER, buffer.depthId); + glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, buffer.width, buffer.height); + glBindRenderbuffer(GL_RENDERBUFFER, 0); + glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, buffer.depthId); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); + + return buffer; +} + +// Unload texture required buffers +static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer) +{ + if (buffer.textureChain) + { + ovr_DestroyTextureSwapChain(session, buffer.textureChain); + buffer.textureChain = NULL; + } + + if (buffer.depthId != 0) glDeleteTextures(1, &buffer.depthId); + if (buffer.fboId != 0) glDeleteFramebuffers(1, &buffer.fboId); +} + +// Load Oculus mirror buffers +static OculusMirror LoadOculusMirror(ovrSession session, int width, int height) +{ + OculusMirror mirror; + mirror.width = width; + mirror.height = height; + + ovrMirrorTextureDesc mirrorDesc; + memset(&mirrorDesc, 0, sizeof(mirrorDesc)); + mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; + mirrorDesc.Width = mirror.width; + mirrorDesc.Height = mirror.height; + + if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture"); + + glGenFramebuffers(1, &mirror.fboId); + + return mirror; +} + +// Unload Oculus mirror buffers +static void UnloadOculusMirror(ovrSession session, OculusMirror mirror) +{ + if (mirror.fboId != 0) glDeleteFramebuffers(1, &mirror.fboId); + if (mirror.texture) ovr_DestroyMirrorTexture(session, mirror.texture); +} + +// Copy Oculus screen buffer to mirror texture +static void BlitOculusMirror(ovrSession session, OculusMirror mirror) +{ + GLuint mirrorTextureId; + + ovr_GetMirrorTextureBufferGL(session, mirror.texture, &mirrorTextureId); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, mirror.fboId); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mirrorTextureId, 0); +#if defined(GRAPHICS_API_OPENGL_33) + // NOTE: glBlitFramebuffer() requires extension: GL_EXT_framebuffer_blit (not available in OpenGL ES 2.0) + glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST); +#endif + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); +} + +// Init Oculus layer (similar to photoshop) +static OculusLayer InitOculusLayer(ovrSession session) +{ + OculusLayer layer = { 0 }; + + layer.viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f; + + memset(&layer.eyeLayer, 0, sizeof(ovrLayerEyeFov)); + layer.eyeLayer.Header.Type = ovrLayerType_EyeFov; + layer.eyeLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; + + ovrEyeRenderDesc eyeRenderDescs[2]; + + for (int eye = 0; eye < 2; eye++) + { + eyeRenderDescs[eye] = ovr_GetRenderDesc(session, eye, hmdDesc.DefaultEyeFov[eye]); + ovrMatrix4f ovrPerspectiveProjection = ovrMatrix4f_Projection(eyeRenderDescs[eye].Fov, 0.01f, 10000.0f, ovrProjection_None); //ovrProjection_ClipRangeOpenGL); + layer.eyeProjections[eye] = FromOvrMatrix(ovrPerspectiveProjection); // NOTE: struct ovrMatrix4f { float M[4][4] } --> struct Matrix + + layer.viewScaleDesc.HmdToEyeOffset[eye] = eyeRenderDescs[eye].HmdToEyeOffset; + layer.eyeLayer.Fov[eye] = eyeRenderDescs[eye].Fov; + + ovrSizei eyeSize = ovr_GetFovTextureSize(session, eye, layer.eyeLayer.Fov[eye], 1.0f); + layer.eyeLayer.Viewport[eye].Size = eyeSize; + layer.eyeLayer.Viewport[eye].Pos.x = layer.width; + layer.eyeLayer.Viewport[eye].Pos.y = 0; + + layer.height = eyeSize.h; //std::max(renderTargetSize.y, (uint32_t)eyeSize.h); + layer.width += eyeSize.w; + } + + return layer; +} + +// Convert from Oculus ovrMatrix4f struct to raymath Matrix struct +static Matrix FromOvrMatrix(ovrMatrix4f ovrmat) +{ + Matrix rmat; + + rmat.m0 = ovrmat.M[0][0]; + rmat.m1 = ovrmat.M[1][0]; + rmat.m2 = ovrmat.M[2][0]; + rmat.m3 = ovrmat.M[3][0]; + rmat.m4 = ovrmat.M[0][1]; + rmat.m5 = ovrmat.M[1][1]; + rmat.m6 = ovrmat.M[2][1]; + rmat.m7 = ovrmat.M[3][1]; + rmat.m8 = ovrmat.M[0][2]; + rmat.m9 = ovrmat.M[1][2]; + rmat.m10 = ovrmat.M[2][2]; + rmat.m11 = ovrmat.M[3][2]; + rmat.m12 = ovrmat.M[0][3]; + rmat.m13 = ovrmat.M[1][3]; + rmat.m14 = ovrmat.M[2][3]; + rmat.m15 = ovrmat.M[3][3]; + + MatrixTranspose(&rmat); + + return rmat; +} +#endif + +// Output a trace log message +// NOTE: Expected msgType: (0)Info, (1)Error, (2)Warning +static void TraceLog(int msgType, const char *text, ...) +{ + va_list args; + va_start(args, text); + + switch (msgType) + { + case INFO: fprintf(stdout, "INFO: "); break; + case ERROR: fprintf(stdout, "ERROR: "); break; + case WARNING: fprintf(stdout, "WARNING: "); break; + case DEBUG: fprintf(stdout, "DEBUG: "); break; + default: break; + } + + vfprintf(stdout, text, args); + fprintf(stdout, "\n"); + + va_end(args); + + if (msgType == ERROR) exit(1); +} + diff --git a/src/core.c b/src/core.c index c0f5be83..38549354 100644 --- a/src/core.c +++ b/src/core.c @@ -755,11 +755,8 @@ void End2dMode(void) void Begin3dMode(Camera camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) - - if (IsVrDeviceReady() || IsVrSimulator()) BeginVrDrawing(); - + rlMatrixMode(RL_PROJECTION); // Switch to projection matrix - rlPushMatrix(); // Save previous matrix, which contains the settings for the 2d ortho projection rlLoadIdentity(); // Reset current matrix (PROJECTION) @@ -786,8 +783,6 @@ void End3dMode(void) { rlglDraw(); // Process internal buffers (update + draw) - if (IsVrDeviceReady() || IsVrSimulator()) EndVrDrawing(); - rlMatrixMode(RL_PROJECTION); // Switch to projection matrix rlPopMatrix(); // Restore previous matrix (PROJECTION) from matrix stack diff --git a/src/raylib.h b/src/raylib.h index 85689378..e679e011 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -687,6 +687,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) +//RLAPI void TraceLog(int logType, const char *text, ...); // Trace log messages showing (INFO, WARNING, ERROR, DEBUG) RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window @@ -944,12 +945,13 @@ RLAPI void EndBlendMode(void); // End // VR experience Functions (Module: rlgl) // NOTE: This functions are useless when using OpenGL 1.1 //------------------------------------------------------------------------------------ -RLAPI void InitVrDevice(int vdDevice); // Init VR device -RLAPI void CloseVrDevice(void); // Close VR device -RLAPI bool IsVrDeviceReady(void); // Detect if VR device is ready -RLAPI bool IsVrSimulator(void); // Detect if VR simulator is running -RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera -RLAPI void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) +RLAPI void InitVrSimulator(int vrDevice); // Init VR simulator for selected device +RLAPI void CloseVrSimulator(void); // Close VR simulator for current device +RLAPI bool IsVrSimulatorReady(void); // Detect if VR device is ready +RLAPI void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera +RLAPI void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) +RLAPI void BeginVrDrawing(void); // Begin VR simulator stereo rendering +RLAPI void EndVrDrawing(void); // End VR simulator stereo rendering //------------------------------------------------------------------------------------ // Audio Loading and Playing Functions (Module: audio) diff --git a/src/rlgl.c b/src/rlgl.c index ffc9d741..00998624 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -37,9 +37,7 @@ * * #define SUPPORT_SHADER_DISTORTION * -* -* #define SUPPORT_OCULUS_RIFT_CV1 / RLGL_OCULUS_SUPPORT -* Enable Oculus Rift CV1 functionality +* #define SUPPORT_VR_SIMULATION * * #define SUPPORT_STEREO_RENDERING * @@ -121,17 +119,6 @@ #include "shader_distortion.h" // Distortion shader to be embedded #endif -//#define RLGL_OCULUS_SUPPORT // Enable Oculus Rift code -#if defined(RLGL_OCULUS_SUPPORT) - #include "external/OculusSDK/LibOVR/Include/OVR_CAPI_GL.h" // Oculus SDK for OpenGL -#endif - -#if defined(RLGL_STANDALONE) - #define OCULUSAPI -#else - #define OCULUSAPI static -#endif - //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- @@ -187,15 +174,15 @@ #endif #if defined(GRAPHICS_API_OPENGL_11) - #define GL_UNSIGNED_SHORT_5_6_5 0x8363 - #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 - #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 + #define GL_UNSIGNED_SHORT_5_6_5 0x8363 + #define GL_UNSIGNED_SHORT_5_5_5_1 0x8034 + #define GL_UNSIGNED_SHORT_4_4_4_4 0x8033 #endif #if defined(GRAPHICS_API_OPENGL_ES2) - #define glClearDepth glClearDepthf - #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER - #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER + #define glClearDepth glClearDepthf + #define GL_READ_FRAMEBUFFER GL_FRAMEBUFFER + #define GL_DRAW_FRAMEBUFFER GL_FRAMEBUFFER #endif // Default vertex attribute names on shader to set location points @@ -267,32 +254,6 @@ typedef struct VrStereoConfig { Matrix eyesViewOffset[2]; // VR stereo rendering eyes view offset matrices } VrStereoConfig; -#if defined(RLGL_OCULUS_SUPPORT) -typedef struct OculusBuffer { - ovrTextureSwapChain textureChain; - GLuint depthId; - GLuint fboId; - int width; - int height; -} OculusBuffer; - -typedef struct OculusMirror { - ovrMirrorTexture texture; - GLuint fboId; - int width; - int height; -} OculusMirror; - -typedef struct OculusLayer { - ovrViewScaleDesc viewScaleDesc; - ovrLayerEyeFov eyeLayer; // layer 0 - //ovrLayerQuad quadLayer; // TODO: layer 1: '2D' quad for GUI - Matrix eyeProjections[2]; - int width; - int height; -} OculusLayer; -#endif - //---------------------------------------------------------------------------------- // Global Variables Definition //---------------------------------------------------------------------------------- @@ -343,24 +304,11 @@ static float maxAnisotropicLevel = 0.0f; // Maximum anisotropy level supp // Extension supported flag: Clamp mirror wrap mode static bool texClampMirrorSupported = false; // Clamp mirror wrap mode supported -#if defined(RLGL_OCULUS_SUPPORT) -// OVR device variables -static ovrSession session; // Oculus session (pointer to ovrHmdStruct) -static ovrHmdDesc hmdDesc; // Oculus device descriptor parameters -static ovrGraphicsLuid luid; // Oculus locally unique identifier for the program (64 bit) -static OculusLayer layer; // Oculus drawing layer (similar to photoshop) -static OculusBuffer buffer; // Oculus internal buffers (texture chain and fbo) -static OculusMirror mirror; // Oculus mirror texture and fbo -static unsigned int frameIndex = 0; // Oculus frames counter, used to discard frames from chain -#endif - // VR global variables static VrDeviceInfo hmd; // Current VR device info static VrStereoConfig vrConfig; // VR stereo configuration for simulator -static bool vrDeviceReady = false; // VR device ready flag -static bool vrSimulator = false; // VR simulator enabled flag -static bool vrEnabled = false; // VR experience enabled (device or simulator) -static bool vrRendering = true; // VR stereo rendering enabled/disabled flag +static bool vrSimulatorReady = false; // VR simulator ready flag +static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag // NOTE: This flag is useful to render data over stereo image (i.e. FPS) #if defined(GRAPHICS_API_OPENGL_ES2) @@ -380,7 +328,7 @@ static int blendMode = 0; // Track current blending mode // White texture useful for plain color polys (required by shader) static unsigned int whiteTexture; -// Default framebuffer size (required by Oculus device) +// Default framebuffer size static int screenWidth; // Default framebuffer width static int screenHeight; // Default framebuffer height @@ -397,7 +345,7 @@ static void UnloadDefaultShader(void); // Unload default shader static void LoadDefaultBuffers(void); // Load default internal buffers (lines, triangles, quads) static void UpdateDefaultBuffers(void); // Update default internal buffers (VAOs/VBOs) with vertex data -static void DrawDefaultBuffers(int eyesCount); // Draw default internal buffers vertex data +static void DrawDefaultBuffers(void); // Draw default internal buffers vertex data static void UnloadDefaultBuffers(void); // Unload default internal buffers vertex data from CPU and GPU // Configure stereo rendering (including distortion shader) with HMD device parameters @@ -407,26 +355,6 @@ static void SetStereoConfig(VrDeviceInfo info); static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView); #endif -#if defined(RLGL_OCULUS_SUPPORT) -#if !defined(RLGL_STANDALONE) -static bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) -static void CloseOculusDevice(void); // Close Oculus device -static void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking -static void BeginOculusDrawing(void); // Setup Oculus buffers for drawing -static void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror -#endif - -static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height); // Load Oculus required buffers -static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer); // Unload texture required buffers -static OculusMirror LoadOculusMirror(ovrSession session, int width, int height); // Load Oculus mirror buffers -static void UnloadOculusMirror(ovrSession session, OculusMirror mirror); // Unload Oculus mirror buffers -static void BlitOculusMirror(ovrSession session, OculusMirror mirror); // Copy Oculus screen buffer to mirror texture -static OculusLayer InitOculusLayer(ovrSession session); // Init Oculus layer (similar to photoshop) -static Matrix FromOvrMatrix(ovrMatrix4f ovrM); // Convert from Oculus ovrMatrix4f struct to raymath Matrix struct -#endif - - - #if defined(GRAPHICS_API_OPENGL_11) static int GenerateMipmaps(unsigned char *data, int baseWidth, int baseHeight); static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight); @@ -1352,9 +1280,7 @@ void rlglDraw(void) // NOTE: Default buffers upload and draw UpdateDefaultBuffers(); - - if (vrEnabled && vrRendering) DrawDefaultBuffers(2); - else DrawDefaultBuffers(1); + DrawDefaultBuffers(); // NOTE: Stereo rendering is checked inside #endif } @@ -2018,9 +1944,6 @@ void rlglDrawMesh(Mesh mesh, Material material, Matrix transform) #endif #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - int eyesCount = 1; - if (vrEnabled) eyesCount = 2; - glUseProgram(material.shader.id); // Upload to shader material.colDiffuse @@ -2153,6 +2076,9 @@ void rlglDrawMesh(Mesh mesh, Material material, Matrix transform) if (mesh.indices != NULL) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, quads.vboId[3]); } + int eyesCount = 1; + if (vrStereoRender) eyesCount = 2; + for (int eye = 0; eye < eyesCount; eye++) { if (eyesCount == 2) SetStereoView(eye, matProjection, matModelView); @@ -2617,146 +2543,119 @@ void EndBlendMode(void) BeginBlendMode(BLEND_ALPHA); } -// Init VR device (or simulator) -// NOTE: If device is not available, it fallbacks to default device (simulator) +// Init VR simulator for selected device // NOTE: It modifies the global variable: VrDeviceInfo hmd -void InitVrDevice(int vrDevice) +void InitVrSimulator(int vrDevice) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - switch (vrDevice) - { - case HMD_DEFAULT_DEVICE: TraceLog(INFO, "Initializing default VR Device (Oculus Rift CV1)"); - case HMD_OCULUS_RIFT_DK2: - case HMD_OCULUS_RIFT_CV1: - { -#if defined(RLGL_OCULUS_SUPPORT) - vrDeviceReady = InitOculusDevice(); -#else - TraceLog(WARNING, "Oculus Rift not supported by default, recompile raylib with Oculus support"); -#endif - } break; - case HMD_VALVE_HTC_VIVE: - case HMD_SAMSUNG_GEAR_VR: - case HMD_GOOGLE_CARDBOARD: - case HMD_SONY_PLAYSTATION_VR: - case HMD_RAZER_OSVR: - case HMD_FOVE_VR: TraceLog(WARNING, "VR Device not supported"); - default: break; - } - - if (!vrDeviceReady) - { - TraceLog(WARNING, "VR Device not found: Initializing VR Simulator (Oculus Rift CV1)"); - - if (vrDevice == HMD_OCULUS_RIFT_DK2) - { - // Oculus Rift DK2 parameters - hmd.hResolution = 1280; // HMD horizontal resolution in pixels - hmd.vResolution = 800; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters - hmd.vScreenSize = 0.09356f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters - hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters - hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters - hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - 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 - } - else if ((vrDevice == HMD_DEFAULT_DEVICE) || (vrDevice == HMD_OCULUS_RIFT_CV1)) - { - // Oculus Rift CV1 parameters - // NOTE: CV1 represents a complete HMD redesign compared to previous versions, - // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, - // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. - // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering - // but result is not the same obtained with Oculus PC SDK. - hmd.hResolution = 2160; // HMD horizontal resolution in pixels - hmd.vResolution = 1200; // HMD vertical resolution in pixels - hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters - hmd.vScreenSize = 0.0669f; // HMD vertical size in meters - hmd.vScreenCenter = 0.04678f; // HMD screen center in meters - 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 - hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 - hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 - hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 - hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 - hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 - 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 - } - - // Initialize framebuffer and textures for stereo rendering - // NOTE: screen size should match HMD aspect ratio - vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); - - // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) - vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); - if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); - - SetStereoConfig(hmd); - - vrSimulator = true; - vrEnabled = true; - } + if (vrDevice == HMD_OCULUS_RIFT_DK2) + { + // Oculus Rift DK2 parameters + hmd.hResolution = 1280; // HMD horizontal resolution in pixels + hmd.vResolution = 800; // HMD vertical resolution in pixels + hmd.hScreenSize = 0.14976f; // HMD horizontal size in meters + hmd.vScreenSize = 0.09356f; // HMD vertical size in meters + hmd.vScreenCenter = 0.04678f; // HMD screen center in meters + hmd.eyeToScreenDistance = 0.041f; // HMD distance between eye and display in meters + hmd.lensSeparationDistance = 0.0635f; // HMD lens separation distance in meters + hmd.interpupillaryDistance = 0.064f; // HMD IPD (distance between pupils) in meters + hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 + hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 + hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 + hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 + hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 + 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 + + TraceLog(WARNING, "Initializing VR Simulator (Oculus Rift DK2)"); + } + else if ((vrDevice == HMD_DEFAULT_DEVICE) || (vrDevice == HMD_OCULUS_RIFT_CV1)) + { + // Oculus Rift CV1 parameters + // NOTE: CV1 represents a complete HMD redesign compared to previous versions, + // new Fresnel-hybrid-asymmetric lenses have been added and, consequently, + // previous parameters (DK2) and distortion shader (DK2) doesn't work any more. + // I just defined a set of parameters for simulator that approximate to CV1 stereo rendering + // but result is not the same obtained with Oculus PC SDK. + hmd.hResolution = 2160; // HMD horizontal resolution in pixels + hmd.vResolution = 1200; // HMD vertical resolution in pixels + hmd.hScreenSize = 0.133793f; // HMD horizontal size in meters + hmd.vScreenSize = 0.0669f; // HMD vertical size in meters + hmd.vScreenCenter = 0.04678f; // HMD screen center in meters + 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 + hmd.distortionK[0] = 1.0f; // HMD lens distortion constant parameter 0 + hmd.distortionK[1] = 0.22f; // HMD lens distortion constant parameter 1 + hmd.distortionK[2] = 0.24f; // HMD lens distortion constant parameter 2 + hmd.distortionK[3] = 0.0f; // HMD lens distortion constant parameter 3 + hmd.chromaAbCorrection[0] = 0.996f; // HMD chromatic aberration correction parameter 0 + 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 + + TraceLog(WARNING, "Initializing VR Simulator (Oculus Rift CV1)"); + } + else + { + TraceLog(WARNING, "VR Simulator doesn't support current device yet,"); + TraceLog(WARNING, "using default VR Simulator parameters"); + } + + // Initialize framebuffer and textures for stereo rendering + // NOTE: screen size should match HMD aspect ratio + vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); + + // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) + vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); + if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); + + SetStereoConfig(hmd); + + vrSimulatorReady = true; #endif #if defined(GRAPHICS_API_OPENGL_11) - TraceLog(WARNING, "VR device or simulator not supported on OpenGL 1.1"); + TraceLog(WARNING, "VR Simulator not supported on OpenGL 1.1"); #endif } -// Close VR device (or simulator) -void CloseVrDevice(void) +// Close VR simulator for current device +void CloseVrSimulator(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) CloseOculusDevice(); - else -#endif + if (vrSimulatorReady) { rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture UnloadShader(vrConfig.distortionShader); // Unload distortion shader } #endif - vrDeviceReady = false; -} - -// Detect if VR device is available -bool IsVrDeviceReady(void) -{ - return (vrDeviceReady && vrEnabled); } // Detect if VR simulator is running -bool IsVrSimulator(void) +bool IsVrSimulatorReady(void) { - return (vrSimulator && vrEnabled); + return vrSimulatorReady; } // Enable/Disable VR experience (device or simulator) void ToggleVrMode(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) - if (vrDeviceReady || vrSimulator) vrEnabled = !vrEnabled; - else vrEnabled = false; + vrSimulatorReady = !vrSimulatorReady; - if (!vrEnabled) + if (!vrSimulatorReady) { + vrStereoRender = false; + // Reset viewport and default projection-modelview matrices rlViewport(0, 0, screenWidth, screenHeight); projection = MatrixOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); MatrixTranspose(&projection); modelview = MatrixIdentity(); } + else vrStereoRender = true; #endif } @@ -2764,37 +2663,29 @@ void ToggleVrMode(void) // NOTE: Camera (position, target, up) gets update with head tracking information void UpdateVrTracking(Camera *camera) { -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) UpdateOculusTracking(camera); -#endif + // TODO: Simulate 1st person camera system } // Begin Oculus drawing configuration void BeginVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - BeginOculusDrawing(); - } - else -#endif + if (vrSimulatorReady) { // Setup framebuffer for stereo rendering rlEnableRenderTexture(vrConfig.stereoFbo.id); - } - // NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA) - // and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then: - // - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB - // - Do NOT enable GL_FRAMEBUFFER_SRGB - //glEnable(GL_FRAMEBUFFER_SRGB); + // NOTE: If your application is configured to treat the texture as a linear format (e.g. GL_RGBA) + // and performs linear-to-gamma conversion in GLSL or does not care about gamma-correction, then: + // - Require OculusBuffer format to be OVR_FORMAT_R8G8B8A8_UNORM_SRGB + // - Do NOT enable GL_FRAMEBUFFER_SRGB + //glEnable(GL_FRAMEBUFFER_SRGB); - //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) - rlClearScreenBuffers(); // Clear current framebuffer(s) - - vrRendering = true; + //glViewport(0, 0, buffer.width, buffer.height); // Useful if rendering to separate framebuffers (every eye) + rlClearScreenBuffers(); // Clear current framebuffer(s) + + vrStereoRender = true; + } #endif } @@ -2802,18 +2693,13 @@ void BeginVrDrawing(void) void EndVrDrawing(void) { #if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - EndOculusDrawing(); - } - else -#endif + if (vrSimulatorReady) { - // Unbind current framebuffer - rlDisableRenderTexture(); + vrStereoRender = false; // Disable stereo render + + rlDisableRenderTexture(); // Unbind current framebuffer - rlClearScreenBuffers(); // Clear current framebuffer + rlClearScreenBuffers(); // Clear current framebuffer // Set viewport to default framebuffer size (screen size) rlViewport(0, 0, screenWidth, screenHeight); @@ -2855,15 +2741,21 @@ void EndVrDrawing(void) rlDisableTexture(); + // Update and draw render texture fbo with distortion to backbuffer UpdateDefaultBuffers(); - DrawDefaultBuffers(1); - + DrawDefaultBuffers(); + + // Restore defaultShader currentShader = defaultShader; - } - - rlDisableDepthTest(); - vrRendering = false; + // Reset viewport and default projection-modelview matrices + rlViewport(0, 0, screenWidth, screenHeight); + projection = MatrixOrtho(0, screenWidth, screenHeight, 0, 0.0f, 1.0f); + MatrixTranspose(&projection); + modelview = MatrixIdentity(); + + rlDisableDepthTest(); + } #endif } @@ -3405,10 +3297,13 @@ static void UpdateDefaultBuffers(void) // Draw default internal buffers vertex data // NOTE: We draw in this order: lines, triangles, quads -static void DrawDefaultBuffers(int eyesCount) +static void DrawDefaultBuffers() { Matrix matProjection = projection; Matrix matModelView = modelview; + + int eyesCount = 1; + if (vrStereoRender) eyesCount = 2; for (int eye = 0; eye < eyesCount; eye++) { @@ -3693,47 +3588,19 @@ static void SetStereoConfig(VrDeviceInfo hmd) // Set internal projection and modelview matrix depending on eyes tracking data static void SetStereoView(int eye, Matrix matProjection, Matrix matModelView) { - if (vrEnabled) - { - Matrix eyeProjection = matProjection; - Matrix eyeModelView = matModelView; + Matrix eyeProjection = matProjection; + Matrix eyeModelView = matModelView; -#if defined(RLGL_OCULUS_SUPPORT) - if (vrDeviceReady) - { - rlViewport(layer.eyeLayer.Viewport[eye].Pos.x, layer.eyeLayer.Viewport[eye].Pos.y, - layer.eyeLayer.Viewport[eye].Size.w, layer.eyeLayer.Viewport[eye].Size.h); - - Quaternion eyeRenderPose = (Quaternion){ layer.eyeLayer.RenderPose[eye].Orientation.x, - layer.eyeLayer.RenderPose[eye].Orientation.y, - layer.eyeLayer.RenderPose[eye].Orientation.z, - layer.eyeLayer.RenderPose[eye].Orientation.w }; - QuaternionInvert(&eyeRenderPose); - Matrix eyeOrientation = QuaternionToMatrix(eyeRenderPose); - Matrix eyeTranslation = MatrixTranslate(-layer.eyeLayer.RenderPose[eye].Position.x, - -layer.eyeLayer.RenderPose[eye].Position.y, - -layer.eyeLayer.RenderPose[eye].Position.z); - - Matrix eyeView = MatrixMultiply(eyeTranslation, eyeOrientation); // Matrix containing eye-head movement - eyeModelView = MatrixMultiply(matModelView, eyeView); // Combine internal camera matrix (modelview) wih eye-head movement - - eyeProjection = layer.eyeProjections[eye]; - } - else -#endif - { - // Setup viewport and projection/modelview matrices using tracking data - rlViewport(eye*screenWidth/2, 0, screenWidth/2, screenHeight); + // Setup viewport and projection/modelview matrices using tracking data + rlViewport(eye*screenWidth/2, 0, screenWidth/2, screenHeight); - // Apply view offset to modelview matrix - eyeModelView = MatrixMultiply(matModelView, vrConfig.eyesViewOffset[eye]); + // Apply view offset to modelview matrix + eyeModelView = MatrixMultiply(matModelView, vrConfig.eyesViewOffset[eye]); - eyeProjection = vrConfig.eyesProjection[eye]; - } + eyeProjection = vrConfig.eyesProjection[eye]; - SetMatrixModelview(eyeModelView); - SetMatrixProjection(eyeProjection); - } + SetMatrixModelview(eyeModelView); + SetMatrixProjection(eyeProjection); } #endif //defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) @@ -3864,304 +3731,6 @@ static Color *GenNextMipmap(Color *srcData, int srcWidth, int srcHeight) } #endif -#if defined(RLGL_OCULUS_SUPPORT) -// Initialize Oculus device (returns true if success) -OCULUSAPI bool InitOculusDevice(void) -{ - bool oculusReady = false; - - ovrResult result = ovr_Initialize(NULL); - - if (OVR_FAILURE(result)) TraceLog(WARNING, "OVR: Could not initialize Oculus device"); - else - { - result = ovr_Create(&session, &luid); - if (OVR_FAILURE(result)) - { - TraceLog(WARNING, "OVR: Could not create Oculus session"); - ovr_Shutdown(); - } - else - { - hmdDesc = ovr_GetHmdDesc(session); - - TraceLog(INFO, "OVR: Product Name: %s", hmdDesc.ProductName); - TraceLog(INFO, "OVR: Manufacturer: %s", hmdDesc.Manufacturer); - TraceLog(INFO, "OVR: Product ID: %i", hmdDesc.ProductId); - TraceLog(INFO, "OVR: Product Type: %i", hmdDesc.Type); - //TraceLog(INFO, "OVR: Serial Number: %s", hmdDesc.SerialNumber); - TraceLog(INFO, "OVR: Resolution: %ix%i", hmdDesc.Resolution.w, hmdDesc.Resolution.h); - - // NOTE: Oculus mirror is set to defined screenWidth and screenHeight... - // ...ideally, it should be (hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2) - - // Initialize Oculus Buffers - layer = InitOculusLayer(session); - buffer = LoadOculusBuffer(session, layer.width, layer.height); - mirror = LoadOculusMirror(session, hmdDesc.Resolution.w/2, hmdDesc.Resolution.h/2); // NOTE: hardcoded... - layer.eyeLayer.ColorTexture[0] = buffer.textureChain; //SetOculusLayerTexture(eyeLayer, buffer.textureChain); - - // Recenter OVR tracking origin - ovr_RecenterTrackingOrigin(session); - - oculusReady = true; - vrEnabled = true; - } - } - - return oculusReady; -} - -// Close Oculus device (and unload buffers) -OCULUSAPI void CloseOculusDevice(void) -{ - UnloadOculusMirror(session, mirror); // Unload Oculus mirror buffer - UnloadOculusBuffer(session, buffer); // Unload Oculus texture buffers - - ovr_Destroy(session); // Free Oculus session data - ovr_Shutdown(); // Close Oculus device connection -} - -// Update Oculus head position-orientation tracking -OCULUSAPI void UpdateOculusTracking(Camera *camera) -{ - frameIndex++; - - ovrPosef eyePoses[2]; - ovr_GetEyePoses(session, frameIndex, ovrTrue, layer.viewScaleDesc.HmdToEyeOffset, eyePoses, &layer.eyeLayer.SensorSampleTime); - - layer.eyeLayer.RenderPose[0] = eyePoses[0]; - layer.eyeLayer.RenderPose[1] = eyePoses[1]; - - // TODO: Update external camera with eyePoses data (position, orientation) - // NOTE: We can simplify to simple camera if we consider IPD and HMD device configuration again later - // it will be useful for the user to draw, lets say, billboards oriented to camera - - // Get session status information - ovrSessionStatus sessionStatus; - ovr_GetSessionStatus(session, &sessionStatus); - - if (sessionStatus.ShouldQuit) TraceLog(WARNING, "OVR: Session should quit..."); - if (sessionStatus.ShouldRecenter) ovr_RecenterTrackingOrigin(session); - //if (sessionStatus.HmdPresent) // HMD is present. - //if (sessionStatus.DisplayLost) // HMD was unplugged or the display driver was manually disabled or encountered a TDR. - //if (sessionStatus.HmdMounted) // HMD is on the user's head. - //if (sessionStatus.IsVisible) // the game or experience has VR focus and is visible in the HMD. -} - -// Setup Oculus buffers for drawing -OCULUSAPI void BeginOculusDrawing(void) -{ - GLuint currentTexId; - int currentIndex; - - ovr_GetTextureSwapChainCurrentIndex(session, buffer.textureChain, ¤tIndex); - ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, currentIndex, ¤tTexId); - - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId); - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, currentTexId, 0); - //glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, buffer.depthId, 0); // Already binded -} - -// Finish Oculus drawing and blit framebuffer to mirror -OCULUSAPI void EndOculusDrawing(void) -{ - // Unbind current framebuffer (Oculus buffer) - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - - ovr_CommitTextureSwapChain(session, buffer.textureChain); - - ovrLayerHeader *layers = &layer.eyeLayer.Header; - ovr_SubmitFrame(session, frameIndex, &layer.viewScaleDesc, &layers, 1); - - // Blit mirror texture to back buffer - BlitOculusMirror(session, mirror); -} - -// Load Oculus required buffers: texture-swap-chain, fbo, texture-depth -static OculusBuffer LoadOculusBuffer(ovrSession session, int width, int height) -{ - OculusBuffer buffer; - buffer.width = width; - buffer.height = height; - - // Create OVR texture chain - ovrTextureSwapChainDesc desc = {}; - desc.Type = ovrTexture_2D; - desc.ArraySize = 1; - desc.Width = width; - desc.Height = height; - desc.MipLevels = 1; - desc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; // Requires glEnable(GL_FRAMEBUFFER_SRGB); - desc.SampleCount = 1; - desc.StaticImage = ovrFalse; - - ovrResult result = ovr_CreateTextureSwapChainGL(session, &desc, &buffer.textureChain); - - if (!OVR_SUCCESS(result)) TraceLog(WARNING, "OVR: Failed to create swap textures buffer"); - - int textureCount = 0; - ovr_GetTextureSwapChainLength(session, buffer.textureChain, &textureCount); - - if (!OVR_SUCCESS(result) || !textureCount) TraceLog(WARNING, "OVR: Unable to count swap chain textures"); - - for (int i = 0; i < textureCount; ++i) - { - GLuint chainTexId; - ovr_GetTextureSwapChainBufferGL(session, buffer.textureChain, i, &chainTexId); - glBindTexture(GL_TEXTURE_2D, chainTexId); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - } - - glBindTexture(GL_TEXTURE_2D, 0); - - /* - // Setup framebuffer object (using depth texture) - glGenFramebuffers(1, &buffer.fboId); - glGenTextures(1, &buffer.depthId); - glBindTexture(GL_TEXTURE_2D, buffer.depthId); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, buffer.width, buffer.height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_INT, NULL); - */ - - // Setup framebuffer object (using depth renderbuffer) - glGenFramebuffers(1, &buffer.fboId); - glGenRenderbuffers(1, &buffer.depthId); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, buffer.fboId); - glBindRenderbuffer(GL_RENDERBUFFER, buffer.depthId); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, buffer.width, buffer.height); - glBindRenderbuffer(GL_RENDERBUFFER, 0); - glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, buffer.depthId); - glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0); - - return buffer; -} - -// Unload texture required buffers -static void UnloadOculusBuffer(ovrSession session, OculusBuffer buffer) -{ - if (buffer.textureChain) - { - ovr_DestroyTextureSwapChain(session, buffer.textureChain); - buffer.textureChain = NULL; - } - - if (buffer.depthId != 0) glDeleteTextures(1, &buffer.depthId); - if (buffer.fboId != 0) glDeleteFramebuffers(1, &buffer.fboId); -} - -// Load Oculus mirror buffers -static OculusMirror LoadOculusMirror(ovrSession session, int width, int height) -{ - OculusMirror mirror; - mirror.width = width; - mirror.height = height; - - ovrMirrorTextureDesc mirrorDesc; - memset(&mirrorDesc, 0, sizeof(mirrorDesc)); - mirrorDesc.Format = OVR_FORMAT_R8G8B8A8_UNORM_SRGB; - mirrorDesc.Width = mirror.width; - mirrorDesc.Height = mirror.height; - - if (!OVR_SUCCESS(ovr_CreateMirrorTextureGL(session, &mirrorDesc, &mirror.texture))) TraceLog(WARNING, "Could not create mirror texture"); - - glGenFramebuffers(1, &mirror.fboId); - - return mirror; -} - -// Unload Oculus mirror buffers -static void UnloadOculusMirror(ovrSession session, OculusMirror mirror) -{ - if (mirror.fboId != 0) glDeleteFramebuffers(1, &mirror.fboId); - if (mirror.texture) ovr_DestroyMirrorTexture(session, mirror.texture); -} - -// Copy Oculus screen buffer to mirror texture -static void BlitOculusMirror(ovrSession session, OculusMirror mirror) -{ - GLuint mirrorTextureId; - - ovr_GetMirrorTextureBufferGL(session, mirror.texture, &mirrorTextureId); - - glBindFramebuffer(GL_READ_FRAMEBUFFER, mirror.fboId); - glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mirrorTextureId, 0); -#if defined(GRAPHICS_API_OPENGL_33) - // NOTE: glBlitFramebuffer() requires extension: GL_EXT_framebuffer_blit (not available in OpenGL ES 2.0) - glBlitFramebuffer(0, 0, mirror.width, mirror.height, 0, mirror.height, mirror.width, 0, GL_COLOR_BUFFER_BIT, GL_NEAREST); -#endif - glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); -} - -// Init Oculus layer (similar to photoshop) -static OculusLayer InitOculusLayer(ovrSession session) -{ - OculusLayer layer = { 0 }; - - layer.viewScaleDesc.HmdSpaceToWorldScaleInMeters = 1.0f; - - memset(&layer.eyeLayer, 0, sizeof(ovrLayerEyeFov)); - layer.eyeLayer.Header.Type = ovrLayerType_EyeFov; - layer.eyeLayer.Header.Flags = ovrLayerFlag_TextureOriginAtBottomLeft; - - ovrEyeRenderDesc eyeRenderDescs[2]; - - for (int eye = 0; eye < 2; eye++) - { - eyeRenderDescs[eye] = ovr_GetRenderDesc(session, eye, hmdDesc.DefaultEyeFov[eye]); - ovrMatrix4f ovrPerspectiveProjection = ovrMatrix4f_Projection(eyeRenderDescs[eye].Fov, 0.01f, 10000.0f, ovrProjection_None); //ovrProjection_ClipRangeOpenGL); - layer.eyeProjections[eye] = FromOvrMatrix(ovrPerspectiveProjection); // NOTE: struct ovrMatrix4f { float M[4][4] } --> struct Matrix - - layer.viewScaleDesc.HmdToEyeOffset[eye] = eyeRenderDescs[eye].HmdToEyeOffset; - layer.eyeLayer.Fov[eye] = eyeRenderDescs[eye].Fov; - - ovrSizei eyeSize = ovr_GetFovTextureSize(session, eye, layer.eyeLayer.Fov[eye], 1.0f); - layer.eyeLayer.Viewport[eye].Size = eyeSize; - layer.eyeLayer.Viewport[eye].Pos.x = layer.width; - layer.eyeLayer.Viewport[eye].Pos.y = 0; - - layer.height = eyeSize.h; //std::max(renderTargetSize.y, (uint32_t)eyeSize.h); - layer.width += eyeSize.w; - } - - return layer; -} - -// Convert from Oculus ovrMatrix4f struct to raymath Matrix struct -static Matrix FromOvrMatrix(ovrMatrix4f ovrmat) -{ - Matrix rmat; - - rmat.m0 = ovrmat.M[0][0]; - rmat.m1 = ovrmat.M[1][0]; - rmat.m2 = ovrmat.M[2][0]; - rmat.m3 = ovrmat.M[3][0]; - rmat.m4 = ovrmat.M[0][1]; - rmat.m5 = ovrmat.M[1][1]; - rmat.m6 = ovrmat.M[2][1]; - rmat.m7 = ovrmat.M[3][1]; - rmat.m8 = ovrmat.M[0][2]; - rmat.m9 = ovrmat.M[1][2]; - rmat.m10 = ovrmat.M[2][2]; - rmat.m11 = ovrmat.M[3][2]; - rmat.m12 = ovrmat.M[0][3]; - rmat.m13 = ovrmat.M[1][3]; - rmat.m14 = ovrmat.M[2][3]; - rmat.m15 = ovrmat.M[3][3]; - - MatrixTranspose(&rmat); - - return rmat; -} -#endif - #if defined(RLGL_STANDALONE) // Output a trace log message // NOTE: Expected msgType: (0)Info, (1)Error, (2)Warning diff --git a/src/rlgl.h b/src/rlgl.h index 41f671e6..344da987 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -399,19 +399,12 @@ void EndBlendMode(void); // End blend void TraceLog(int msgType, const char *text, ...); float *MatrixToFloat(Matrix mat); -void InitVrDevice(int vrDevice); // Init VR device -void CloseVrDevice(void); // Close VR device -bool IsVrDeviceReady(void); // Detect if VR device is ready -bool IsVrSimulator(void); // Detect if VR simulator is running +void InitVrSimulator(int vrDevice); // Init VR simulator for selected device +void CloseVrSimulator(void); // Close VR simulator for current device void UpdateVrTracking(Camera *camera); // Update VR tracking (position and orientation) and camera void ToggleVrMode(void); // Enable/Disable VR experience (device or simulator) - -// Oculus Rift API for direct access the device (no simulator) -bool InitOculusDevice(void); // Initialize Oculus device (returns true if success) -void CloseOculusDevice(void); // Close Oculus device -void UpdateOculusTracking(Camera *camera); // Update Oculus head position-orientation tracking (and camera) -void BeginOculusDrawing(void); // Setup Oculus buffers for drawing -void EndOculusDrawing(void); // Finish Oculus drawing and blit framebuffer to mirror +void BeginVrDrawing(void); // Begin VR stereo rendering +void EndVrDrawing(void); // End VR stereo rendering #endif #ifdef __cplusplus -- cgit v1.2.3 From 8f5ff64420dda659583c156b9c5e42e60384e247 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 19 Mar 2017 12:52:58 +0100 Subject: Working on file header comments... --- src/audio.c | 41 ++++++++++++++++++++------------------ src/audio.h | 28 +++++++++++++++----------- src/core.c | 11 ++++++++-- src/easings.h | 2 +- src/models.c | 4 +++- src/raylib.h | 64 ++++++++++++++++++++++++++++++----------------------------- src/utils.c | 19 ++++++++++++++---- src/utils.h | 6 ++++++ 8 files changed, 105 insertions(+), 70 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index 659ead0f..e0964e02 100644 --- a/src/audio.c +++ b/src/audio.c @@ -1,26 +1,24 @@ /********************************************************************************************** * -* raylib.audio +* raylib.audio - Basic funtionality to work with audio * -* This module provides basic functionality to work with audio: -* Manage audio device (init/close) -* Load and Unload audio files (WAV, OGG, FLAC, XM, MOD) -* Play/Stop/Pause/Resume loaded audio -* Manage mixing channels -* Manage raw audio context +* DESCRIPTION: * -* NOTES: -* -* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) -* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) +* This module provides basic functionality to: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * CONFIGURATION: * * #define AUDIO_STANDALONE -* If defined, the module can be used as standalone library (independently of raylib). +* Define to use the module as standalone library (independently of raylib). * Required types and functions are defined in the same module. * -* #define SUPPORT_FILEFORMAT_WAV / SUPPORT_LOAD_WAV / ENABLE_LOAD_WAV +* #define SUPPORT_FILEFORMAT_WAV / SUPPORT_LOAD_WAV * #define SUPPORT_FILEFORMAT_OGG * #define SUPPORT_FILEFORMAT_XM * #define SUPPORT_FILEFORMAT_MOD @@ -29,6 +27,12 @@ * supported by default, to remove support, just comment unrequired #define in this module * * #define SUPPORT_RAW_AUDIO_BUFFERS +* Support creating raw audio buffers to send raw data. Buffers must be managed by the user, +* it means initialization, refilling and cleaning. +* +* LIMITATIONS: +* Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) +* Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) * * DEPENDENCIES: * OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) @@ -38,12 +42,11 @@ * dr_flac - FLAC audio file loading * * CONTRIBUTORS: -* -* Many thanks to Joshua Reisenauer (github: @kd7tck) for the following additions: -* XM audio module support (jar_xm) -* MOD audio module support (jar_mod) -* Mixing channels support -* Raw audio context support +* Joshua Reisenauer (github: @kd7tck): +* - XM audio module support (jar_xm) +* - MOD audio module support (jar_mod) +* - Mixing channels support +* - Raw audio context support * * * LICENSE: zlib/libpng diff --git a/src/audio.h b/src/audio.h index 01ed9f72..a0279e3a 100644 --- a/src/audio.h +++ b/src/audio.h @@ -1,13 +1,16 @@ /********************************************************************************************** * -* raylib.audio +* raylib.audio - Basic funtionality to work with audio * -* This module provides basic functionality to work with audio: -* Manage audio device (init/close) -* Load and Unload audio files (WAV, OGG, FLAC, XM, MOD) -* Play/Stop/Pause/Resume loaded audio -* Manage mixing channels -* Manage raw audio context +* DESCRIPTION: +* +* This module provides basic functionality to: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * DEPENDENCIES: * OpenAL Soft - Audio device management (http://kcat.strangesoft.net/openal.html) @@ -16,11 +19,12 @@ * jar_mod - MOD audio file loading * dr_flac - FLAC audio file loading * -* Many thanks to Joshua Reisenauer (github: @kd7tck) for the following additions: -* XM audio module support (jar_xm) -* MOD audio module support (jar_mod) -* Mixing channels support -* Raw audio context support +* CONTRIBUTORS: +* Joshua Reisenauer (github: @kd7tck): +* - XM audio module support (jar_xm) +* - MOD audio module support (jar_mod) +* - Mixing channels support +* - Raw audio context support * * * LICENSE: zlib/libpng diff --git a/src/core.c b/src/core.c index 38549354..f55a70db 100644 --- a/src/core.c +++ b/src/core.c @@ -2,7 +2,14 @@ * * raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms * -* The following platforms are supported: Windows, Linux, Mac (OSX), Android, Raspberry Pi, HTML5, Oculus Rift CV1 +* The following platforms are supported: +* Windows (win32/Win64) +* Linux (tested on Ubuntu) +* Mac (OSX) +* Android (API Level 9 or greater) +* Raspberry Pi (Raspbian) +* HTML5 (Chrome, Firefox) +* Oculus Rift CV1 * * CONFIGURATION: * @@ -2006,7 +2013,7 @@ static double GetTime(void) // Wait for some milliseconds (stop program execution) static void Wait(float ms) { -#define SUPPORT_BUSY_WAIT_LOOP +//#define SUPPORT_BUSY_WAIT_LOOP #if defined(SUPPORT_BUSY_WAIT_LOOP) double prevTime = GetTime(); double nextTime = 0.0; diff --git a/src/easings.h b/src/easings.h index 527970ab..9ad27313 100644 --- a/src/easings.h +++ b/src/easings.h @@ -122,7 +122,7 @@ EASEDEF float EaseCubicOut(float t, float b, float c, float d) { return (c*((t=t EASEDEF float EaseCubicInOut(float t, float b, float c, float d) { if ((t/=d/2) < 1) return (c/2*t*t*t + b); - return (c/2*((t-=2)*t*t + 2) + b); + return (c/2*((t-=2)*t*t + 2) + b); } // Quadratic Easing functions diff --git a/src/models.c b/src/models.c index bef19e10..8297358b 100644 --- a/src/models.c +++ b/src/models.c @@ -1,12 +1,14 @@ /********************************************************************************************** * -* raylib.models - Basic functions to draw 3d shapes and 3d models +* raylib.models - Basic functions to deal with 3d shapes and 3d models * * CONFIGURATION: * * #define SUPPORT_FILEFORMAT_OBJ / SUPPORT_LOAD_OBJ +* Selected desired fileformats to be supported for loading. * * #define SUPPORT_FILEFORMAT_MTL +* Selected desired fileformats to be supported for loading. * * * LICENSE: zlib/libpng diff --git a/src/raylib.h b/src/raylib.h index e679e011..4fd4b5df 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -1,43 +1,45 @@ /********************************************************************************************** * -* raylib v1.7.0 (www.raylib.com) +* raylib v1.7.0 * -* A simple and easy-to-use library to learn videogames programming +* A simple and easy-to-use library to learn videogames programming (www.raylib.com) * * FEATURES: -* Library written in plain C code (C99) -* Uses PascalCase/camelCase notation -* Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) -* Unique OpenGL abstraction layer (usable as standalone module): [rlgl] -* Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) -* Multiple textures support, including compressed formats and mipmaps generation -* Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps -* Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* Audio loading and playing with streaming support and mixing channels [audio] -* VR stereo rendering support with configurable HMD device parameters -* Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 -* Custom color palette for fancy visuals on raywhite background -* Minimal external dependencies (GLFW3, OpenGL, OpenAL) -* Complete binding for Lua [rlua] +* - Library written in plain C code (C99) +* - Uses PascalCase/camelCase notation +* - Hardware accelerated with OpenGL (1.1, 2.1, 3.3 or ES 2.0) +* - Unique OpenGL abstraction layer (usable as standalone module): [rlgl] +* - Powerful fonts module with SpriteFonts support (XNA bitmap fonts, AngelCode fonts, TTF) +* - Multiple textures support, including compressed formats and mipmaps generation +* - Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps +* - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] +* - Audio loading and playing with streaming support and mixing channels [audio] +* - VR stereo rendering support with configurable HMD device parameters +* - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 +* - Custom color palette for fancy visuals on raywhite background +* - Minimal external dependencies (GLFW3, OpenGL, OpenAL) +* - Complete bindings for Lua, Go and Pascal * * NOTES: -* 32bit Colors - All defined color are always RGBA (struct Color is 4 byte) -* One custom default font could be loaded automatically when InitWindow() [core] -* If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads -* If using OpenGL 3.3 or ES2, two default shaders could be loaded automatically (internally defined) +* 32bit Colors - All defined color are always RGBA (struct Color is 4 byte) +* One custom default font could be loaded automatically when InitWindow() [core] +* If using OpenGL 3.3 or ES2, several vertex buffers (VAO/VBO) are created to manage lines-triangles-quads +* If using OpenGL 3.3 or ES2, two default shaders could be loaded automatically (internally defined) * * DEPENDENCIES: -* GLFW3 (www.glfw.org) for window/context management and input [core] -* GLAD for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] -* stb_image (Sean Barret) for images loading (JPEG, PNG, BMP, TGA) [textures] -* stb_image_write (Sean Barret) for image writting (PNG) [utils] -* stb_truetype (Sean Barret) for ttf fonts loading [text] -* stb_vorbis (Sean Barret) for ogg audio loading [audio] -* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] -* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] -* dr_flac (David Reid) for FLAC audio file loading [audio] -* OpenAL Soft for audio device/context management [audio] -* tinfl for data decompression (DEFLATE algorithm) [utils] +* GLFW3 (www.glfw.org) for window/context management and input [core] +* GLAD for OpenGL extensions loading (3.3 Core profile, only PLATFORM_DESKTOP) [rlgl] +* OpenAL Soft for audio device/context management [audio] +* +* OPTIONAL DEPENDENCIES: +* stb_image (Sean Barret) for images loading (JPEG, PNG, BMP, TGA) [textures] +* stb_image_write (Sean Barret) for image writting (PNG) [utils] +* stb_truetype (Sean Barret) for ttf fonts loading [text] +* stb_vorbis (Sean Barret) for ogg audio loading [audio] +* jar_xm (Joshua Reisenauer) for XM audio module loading [audio] +* jar_mod (Joshua Reisenauer) for MOD audio module loading [audio] +* dr_flac (David Reid) for FLAC audio file loading [audio] +* tinfl for data decompression (DEFLATE algorithm) [rres] * * * LICENSE: zlib/libpng diff --git a/src/utils.c b/src/utils.c index 9a2a723a..54923e34 100644 --- a/src/utils.c +++ b/src/utils.c @@ -4,14 +4,20 @@ * * CONFIGURATION: * -* #define SUPPORT_SAVE_PNG -* Enable saving PNG fileformat +* #define SUPPORT_SAVE_PNG (defined by default) +* Support saving image data as PNG fileformat * NOTE: Requires stb_image_write library * * #define SUPPORT_SAVE_BMP +* Support saving image data as BMP fileformat +* NOTE: Requires stb_image_write library +* +* #define SUPPORT_TRACELOG +* Show TraceLog() output messages +* NOTE: By default DEBUG traces not shown * -* #define DO_NOT_TRACE_DEBUG_MSGS -* Avoid showing DEBUG TraceLog() messages +* #define SUPPORT_TRACELOG_DEBUG +* Show TraceLog() DEBUG messages * * DEPENDENCIES: * stb_image_write - PNG writting functions @@ -129,18 +135,23 @@ void TraceLog(int msgType, const char *text, ...) } #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) + +#if defined(SUPPORT_SAVE_BMP) // Creates a BMP image file from an array of pixel data void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize) { stbi_write_bmp(fileName, width, height, compSize, imgData); } +#endif +#if defined(SUPPORT_SAVE_PNG) // Creates a PNG image file from an array of pixel data void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize) { stbi_write_png(fileName, width, height, compSize, imgData, width*compSize); } #endif +#endif #if defined(PLATFORM_ANDROID) // Initialize asset manager from android app diff --git a/src/utils.h b/src/utils.h index 3ffd025c..037d7e94 100644 --- a/src/utils.h +++ b/src/utils.h @@ -33,6 +33,8 @@ #include "rres.h" +#define SUPPORT_SAVE_PNG + //---------------------------------------------------------------------------------- // Some basic Defines //---------------------------------------------------------------------------------- @@ -61,9 +63,13 @@ void TraceLog(int msgType, const char *text, ...); // Outputs a trace log messa const char *GetExtension(const char *fileName); // Returns extension of a filename #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) +#if defined(SUPPORT_SAVE_BMP) void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize); +#endif +#if defined(SUPPORT_SAVE_PNG) void SavePNG(const char *fileName, unsigned char *imgData, int width, int height, int compSize); #endif +#endif #if defined(PLATFORM_ANDROID) void InitAssetManager(AAssetManager *manager); // Initialize asset manager from android app -- cgit v1.2.3 From 59652c75b43d0437217c0000b03428545905801e Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 20 Mar 2017 20:34:44 +0100 Subject: Review some comments --- src/audio.c | 18 ++++++++---------- src/audio.h | 2 +- src/camera.h | 4 ++-- src/core.c | 18 +++++++++--------- src/gestures.h | 4 ++-- src/models.c | 2 +- src/raylib.h | 2 +- src/raymath.h | 2 +- src/rlgl.c | 47 ++++++++++++++++++----------------------------- src/rlgl.h | 45 +++++++++++++++++++++++++++++++-------------- src/rres.h | 4 +--- src/shapes.c | 2 +- src/text.c | 2 +- src/textures.c | 2 +- src/utils.c | 2 +- src/utils.h | 7 ++++--- 16 files changed, 83 insertions(+), 80 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index e0964e02..68bd88e9 100644 --- a/src/audio.c +++ b/src/audio.c @@ -2,15 +2,13 @@ * * raylib.audio - Basic funtionality to work with audio * -* DESCRIPTION: -* -* This module provides basic functionality to: -* - Manage audio device (init/close) -* - Load and unload audio files -* - Format wave data (sample rate, size, channels) -* - Play/Stop/Pause/Resume loaded audio -* - Manage mixing channels -* - Manage raw audio context +* FEATURES: +* - Manage audio device (init/close) +* - Load and unload audio files +* - Format wave data (sample rate, size, channels) +* - Play/Stop/Pause/Resume loaded audio +* - Manage mixing channels +* - Manage raw audio context * * CONFIGURATION: * @@ -51,7 +49,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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/audio.h b/src/audio.h index a0279e3a..8047d9bb 100644 --- a/src/audio.h +++ b/src/audio.h @@ -29,7 +29,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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/camera.h b/src/camera.h index 87ba1942..e1b00ac2 100644 --- a/src/camera.h +++ b/src/camera.h @@ -1,6 +1,6 @@ /******************************************************************************************* * -* raylib Camera System - Camera Modes Setup and Control Functions +* raylib.camera - Camera system with multiple modes support * * NOTE: Memory footprint of this library is aproximately 52 bytes (global variables) * @@ -22,7 +22,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2015-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2015-2017 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/core.c b/src/core.c index f55a70db..5b892cdf 100644 --- a/src/core.c +++ b/src/core.c @@ -2,14 +2,14 @@ * * raylib.core - Basic functions to manage windows, OpenGL context and input on multiple platforms * -* The following platforms are supported: -* Windows (win32/Win64) -* Linux (tested on Ubuntu) -* Mac (OSX) -* Android (API Level 9 or greater) -* Raspberry Pi (Raspbian) -* HTML5 (Chrome, Firefox) -* Oculus Rift CV1 +* PLATFORMS SUPPORTED: +* - Windows (win32/Win64) +* - Linux (tested on Ubuntu) +* - Mac (OSX) +* - Android (API Level 9 or greater) +* - Raspberry Pi (Raspbian) +* - HTML5 (Chrome, Firefox) +* - Oculus Rift CV1 * * CONFIGURATION: * @@ -49,7 +49,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 99f49d2a..42ced889 100644 --- a/src/gestures.h +++ b/src/gestures.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raylib Gestures System - Gestures Processing based on input gesture events (touch/mouse) +* raylib.gestures - Gestures system, gestures processing based on input events (touch/mouse) * * NOTE: Memory footprint of this library is aproximately 128 bytes (global variables) * @@ -24,7 +24,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 8297358b..67e1693c 100644 --- a/src/models.c +++ b/src/models.c @@ -13,7 +13,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 4fd4b5df..cdefceb2 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -47,7 +47,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-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2013-2017 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/raymath.h b/src/raymath.h index a2263f19..7e760957 100644 --- a/src/raymath.h +++ b/src/raymath.h @@ -1,6 +1,6 @@ /********************************************************************************************** * -* raymath v1.0 - Some useful functions to work with Vector3, Matrix and Quaternions +* raymath v1.0 - Math functions to work with Vector3, Matrix and Quaternions * * CONFIGURATION: * diff --git a/src/rlgl.c b/src/rlgl.c index 00998624..d76f90bb 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -2,10 +2,8 @@ * * rlgl - raylib OpenGL abstraction layer * -* DESCRIPTION: -* -* rlgl allows usage of OpenGL 1.1 style functions (rlVertex) that are internally mapped to -* selected OpenGL version (1.1, 2.1, 3.3 Core, ES 2.0). +* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to +* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). * * When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal * VBO buffers (and VAOs if available). It requires calling 3 functions: @@ -16,32 +14,19 @@ * CONFIGURATION: * * #define GRAPHICS_API_OPENGL_11 -* Use OpenGL 1.1 backend -* * #define GRAPHICS_API_OPENGL_21 -* Use OpenGL 2.1 backend -* * #define GRAPHICS_API_OPENGL_33 -* Use OpenGL 3.3 Core profile backend -* * #define GRAPHICS_API_OPENGL_ES2 -* Use OpenGL ES 2.0 backend +* Use selected OpenGL backend * * #define RLGL_STANDALONE * Use rlgl as standalone library (no raylib dependency) * -* #define RLGL_NO_DISTORTION_SHADER -* Avoid stereo rendering distortion sahder (shader_distortion.h) inclusion -* -* #define SUPPORT_SHADER_DEFAULT / ENABLE_SHADER_DEFAULT +* #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING +* Support VR simulation functionality (stereo rendering) * * #define SUPPORT_SHADER_DISTORTION -* -* #define SUPPORT_VR_SIMULATION -* -* #define SUPPORT_STEREO_RENDERING -* -* #define RLGL_NO_DEFAULT_SHADER +* Include stereo rendering distortion shader (shader_distortion.h) * * DEPENDENCIES: * raymath - 3D math functionality (Vector3, Matrix, Quaternion) @@ -50,7 +35,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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. @@ -295,6 +280,13 @@ static bool texCompETC1Supported = false; // ETC1 texture compression support static bool texCompETC2Supported = false; // ETC2/EAC texture compression support static bool texCompPVRTSupported = false; // PVR texture compression support static bool texCompASTCSupported = false; // ASTC texture compression support + +// VR global variables +static VrDeviceInfo hmd; // Current VR device info +static VrStereoConfig vrConfig; // VR stereo configuration for simulator +static bool vrSimulatorReady = false; // VR simulator ready flag +static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag + // NOTE: This flag is useful to render data over stereo image (i.e. FPS) #endif // Extension supported flag: Anisotropic filtering @@ -304,13 +296,6 @@ static float maxAnisotropicLevel = 0.0f; // Maximum anisotropy level supp // Extension supported flag: Clamp mirror wrap mode static bool texClampMirrorSupported = false; // Clamp mirror wrap mode supported -// VR global variables -static VrDeviceInfo hmd; // Current VR device info -static VrStereoConfig vrConfig; // VR stereo configuration for simulator -static bool vrSimulatorReady = false; // VR simulator ready flag -static bool vrStereoRender = false; // VR stereo rendering enabled/disabled flag - // NOTE: This flag is useful to render data over stereo image (i.e. FPS) - #if defined(GRAPHICS_API_OPENGL_ES2) // NOTE: VAO functionality is exposed through extensions (OES) static PFNGLGENVERTEXARRAYSOESPROC glGenVertexArrays; @@ -2636,7 +2621,11 @@ void CloseVrSimulator(void) // Detect if VR simulator is running bool IsVrSimulatorReady(void) { +#if defined(GRAPHICS_API_OPENGL_33) || defined(GRAPHICS_API_OPENGL_ES2) return vrSimulatorReady; +#else + return false; +#endif } // Enable/Disable VR experience (device or simulator) diff --git a/src/rlgl.h b/src/rlgl.h index 344da987..a870a907 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -2,8 +2,8 @@ * * rlgl - raylib OpenGL abstraction layer * -* rlgl allows usage of OpenGL 1.1 style functions (rlVertex) that are internally mapped to -* selected OpenGL version (1.1, 2.1, 3.3 Core, ES 2.0). +* rlgl is a wrapper for multiple OpenGL versions (1.1, 2.1, 3.3 Core, ES 2.0) to +* pseudo-OpenGL 1.1 style functions (rlVertex, rlTranslate, rlRotate...). * * When chosing an OpenGL version greater than OpenGL 1.1, rlgl stores vertex data on internal * VBO buffers (and VAOs if available). It requires calling 3 functions: @@ -11,18 +11,29 @@ * rlglDraw() - Process internal buffers and send required draw calls * rlglClose() - De-initialize internal buffers data and other auxiliar resources * -* External libs: +* CONFIGURATION: +* +* #define GRAPHICS_API_OPENGL_11 +* #define GRAPHICS_API_OPENGL_21 +* #define GRAPHICS_API_OPENGL_33 +* #define GRAPHICS_API_OPENGL_ES2 +* Use selected OpenGL backend +* +* #define RLGL_STANDALONE +* Use rlgl as standalone library (no raylib dependency) +* +* #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING +* Support VR simulation functionality (stereo rendering) +* +* #define SUPPORT_SHADER_DISTORTION +* Include stereo rendering distortion shader (shader_distortion.h) +* +* DEPENDENCIES: * raymath - 3D math functionality (Vector3, Matrix, Quaternion) * GLAD - OpenGL extensions loading (OpenGL 3.3 Core only) * -* Module Configuration Flags: -* GRAPHICS_API_OPENGL_11 - Use OpenGL 1.1 backend -* GRAPHICS_API_OPENGL_21 - Use OpenGL 2.1 backend -* GRAPHICS_API_OPENGL_33 - Use OpenGL 3.3 Core profile backend -* GRAPHICS_API_OPENGL_ES2 - Use OpenGL ES 2.0 backend -* -* RLGL_STANDALONE - Use rlgl as standalone library (no raylib dependency) * +* LICENSE: zlib/libpng * * Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) * @@ -124,15 +135,21 @@ #define RL_WRAP_CLAMP 0x812F // GL_CLAMP_TO_EDGE #define RL_WRAP_CLAMP_MIRROR 0x8742 // GL_MIRROR_CLAMP_EXT +// Matrix modes (equivalent to OpenGL) +#define RL_MODELVIEW 0x1700 // GL_MODELVIEW +#define RL_PROJECTION 0x1701 // GL_PROJECTION +#define RL_TEXTURE 0x1702 // GL_TEXTURE + +// Primitive assembly draw modes +#define RL_LINES 0x0001 // GL_LINES +#define RL_TRIANGLES 0x0004 // GL_TRIANGLES +#define RL_QUADS 0x0007 // GL_QUADS + //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- typedef enum { OPENGL_11 = 1, OPENGL_21, OPENGL_33, OPENGL_ES_20 } GlVersion; -typedef enum { RL_PROJECTION, RL_MODELVIEW, RL_TEXTURE } MatrixMode; - -typedef enum { RL_LINES, RL_TRIANGLES, RL_QUADS } DrawMode; - typedef unsigned char byte; #if defined(RLGL_STANDALONE) diff --git a/src/rres.h b/src/rres.h index 362da10d..65ebdbba 100644 --- a/src/rres.h +++ b/src/rres.h @@ -1,8 +1,6 @@ /********************************************************************************************** * -* rres - raylib Resource custom format management functions -* -* Basic functions to load/save rRES resource files +* rres v1.0 - raylib resource (rRES) custom fileformat management functions * * CONFIGURATION: * diff --git a/src/shapes.c b/src/shapes.c index 5ed633f6..2a924476 100644 --- a/src/shapes.c +++ b/src/shapes.c @@ -13,7 +13,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 18ebf482..2d249b6d 100644 --- a/src/text.c +++ b/src/text.c @@ -18,7 +18,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 7db3bf56..f323f352 100644 --- a/src/textures.c +++ b/src/textures.c @@ -31,7 +31,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 54923e34..4d30cbc7 100644 --- a/src/utils.c +++ b/src/utils.c @@ -25,7 +25,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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 037d7e94..45ffcf81 100644 --- a/src/utils.h +++ b/src/utils.h @@ -1,10 +1,11 @@ /********************************************************************************************** * -* raylib.utils +* raylib.utils - Some common utility functions * -* Some utility functions * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* LICENSE: zlib/libpng +* +* Copyright (c) 2014-2017 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. -- cgit v1.2.3 From 004117a05c1a3766c88ab3662308a4a995abed3c Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 21 Mar 2017 13:22:59 +0100 Subject: core: configuration flags --- src/core.c | 47 ++++++++++++++++++++++++++++++----------------- 1 file changed, 30 insertions(+), 17 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 5b892cdf..1423cf7c 100644 --- a/src/core.c +++ b/src/core.c @@ -29,13 +29,15 @@ * Windowing and input system configured for HTML5 (run on browser), code converted from C to asm.js * using emscripten compiler. OpenGL ES 2.0 required for direct translation to WebGL equivalent code. * -* #define LOAD_DEFAULT_FONT (defined by default) +* #define SUPPORT_DEFAULT_FONT (default) * Default font is loaded on window initialization to be available for the user to render simple text. * NOTE: If enabled, uses external module functions to load default raylib font (module: text) * -* #define INCLUDE_CAMERA_SYSTEM / SUPPORT_CAMERA_SYSTEM +* #define SUPPORT_CAMERA_SYSTEM +* Camera module is included (camera.h) and multiple predefined cameras are available: free, 1st/3rd person, orbital * -* #define INCLUDE_GESTURES_SYSTEM / SUPPORT_GESTURES_SYSTEM +* #define SUPPORT_GESTURES_SYSTEM +* Gestures module is included (gestures.h) to support gestures detection: tap, hold, swipe, drag * * #define SUPPORT_MOUSE_GESTURES * Mouse gestures are directly mapped like touches and processed by gestures system. @@ -68,6 +70,14 @@ * **********************************************************************************************/ +// Default supported features +//------------------------------------- +#define SUPPORT_DEFAULT_FONT +#define SUPPORT_MOUSE_GESTURES +#define SUPPORT_CAMERA_SYSTEM +#define SUPPORT_GESTURES_SYSTEM +//------------------------------------- + #include "raylib.h" #include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2 @@ -77,10 +87,12 @@ #define RAYMATH_EXTERN_INLINE // Compile raymath functions as static inline (remember, it's a compiler hint) #include "raymath.h" // Required for: Vector3 and Matrix functions -#define GESTURES_IMPLEMENTATION -#include "gestures.h" // Gestures detection functionality +#if defined(SUPPORT_GESTURES_SYSTEM) + #define GESTURES_IMPLEMENTATION + #include "gestures.h" // Gestures detection functionality +#endif -#if !defined(PLATFORM_ANDROID) +#if defined(SUPPORT_CAMERA_SYSTEM) && !defined(PLATFORM_ANDROID) #define CAMERA_IMPLEMENTATION #include "camera.h" // Camera system functionality #endif @@ -147,8 +159,6 @@ //---------------------------------------------------------------------------------- // Defines and Macros //---------------------------------------------------------------------------------- -#define STORAGE_FILENAME "storage.data" - #if defined(PLATFORM_RPI) // Old device inputs system #define DEFAULT_KEYBOARD_DEV STDIN_FILENO // Standard input @@ -168,7 +178,7 @@ #define MAX_GAMEPAD_BUTTONS 32 // Max bumber of buttons supported (per gamepad) #define MAX_GAMEPAD_AXIS 8 // Max number of axis supported (per gamepad) -#define LOAD_DEFAULT_FONT // Load default font on window initialization (module: text) +#define STORAGE_FILENAME "storage.data" //---------------------------------------------------------------------------------- // Types and Structures Definition @@ -266,7 +276,10 @@ static int lastGamepadButtonPressed = -1; // Register last gamepad button pres static int gamepadAxisCount = 0; // Register number of available gamepad axis static Vector2 mousePosition; // Mouse position on screen + +#if defined(SUPPORT_GESTURES_SYSTEM) static Vector2 touchPosition[MAX_TOUCH_POINTS]; // Touch position on screen +#endif #if defined(PLATFORM_DESKTOP) static char **dropFilesPath; // Store dropped files paths as strings @@ -284,7 +297,7 @@ static bool showLogo = false; // Track if showing logo at init is //---------------------------------------------------------------------------------- // Other Modules Functions Declaration (required by core) //---------------------------------------------------------------------------------- -#if defined(LOAD_DEFAULT_FONT) +#if defined(SUPPORT_DEFAULT_FONT) extern void LoadDefaultFont(void); // [Module: text] Loads default font on InitWindow() extern void UnloadDefaultFont(void); // [Module: text] Unloads default font from GPU memory #endif @@ -366,7 +379,7 @@ void InitWindow(int width, int height, const char *title) // Init graphics device (display device and OpenGL context) InitGraphicsDevice(width, height); -#if defined(LOAD_DEFAULT_FONT) +#if defined(SUPPORT_DEFAULT_FONT) // Load default font // NOTE: External function (defined in module: text) LoadDefaultFont(); @@ -478,7 +491,7 @@ void InitWindow(int width, int height, void *state) // Close Window and Terminate Context void CloseWindow(void) { -#if defined(LOAD_DEFAULT_FONT) +#if defined(SUPPORT_DEFAULT_FONT) UnloadDefaultFont(); #endif @@ -2071,9 +2084,11 @@ static bool GetMouseButtonStatus(int button) // Poll (store) all input events static void PollInputEvents(void) { +#if defined(SUPPORT_GESTURES_SYSTEM) // NOTE: Gestures update must be called every frame to reset gestures correctly // because ProcessGestureEvent() is just called on an event, not every frame UpdateGestures(); +#endif // Reset last key pressed registered lastKeyPressed = -1; @@ -2303,8 +2318,7 @@ static void MouseButtonCallback(GLFWwindow *window, int button, int action, int { currentMouseState[button] = action; -#define ENABLE_MOUSE_GESTURES -#if defined(ENABLE_MOUSE_GESTURES) +#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES) // Process mouse events as touches to be able to use mouse-gestures GestureEvent gestureEvent; @@ -2335,8 +2349,7 @@ static void MouseButtonCallback(GLFWwindow *window, int button, int action, int // GLFW3 Cursor Position Callback, runs on mouse move static void MouseCursorPosCallback(GLFWwindow *window, double x, double y) { -#define ENABLE_MOUSE_GESTURES -#if defined(ENABLE_MOUSE_GESTURES) +#if defined(SUPPORT_GESTURES_SYSTEM) && defined(SUPPORT_MOUSE_GESTURES) // Process mouse events as touches to be able to use mouse-gestures GestureEvent gestureEvent; @@ -2466,7 +2479,7 @@ static void AndroidCommandCallback(struct android_app *app, int32_t cmd) // Init graphics device (display device and OpenGL context) InitGraphicsDevice(screenWidth, screenHeight); - #if defined(LOAD_DEFAULT_FONT) + #if defined(SUPPORT_DEFAULT_FONT) // Load default font // NOTE: External function (defined in module: text) LoadDefaultFont(); -- cgit v1.2.3 From 9875198a56263b5e282c016c67221ddfcfb51d31 Mon Sep 17 00:00:00 2001 From: RDR8 Date: Fri, 24 Mar 2017 01:20:24 -0500 Subject: c99 fix, some linux housekeeping --- examples/Makefile | 31 +++++++++++++++---------------- src/Makefile | 16 ++++++++++------ src/core.c | 10 +++++----- src/gestures.h | 4 ++-- src/physac.h | 6 +++--- 5 files changed, 35 insertions(+), 32 deletions(-) (limited to 'src/core.c') diff --git a/examples/Makefile b/examples/Makefile index 98129990..e271355d 100644 --- a/examples/Makefile +++ b/examples/Makefile @@ -40,7 +40,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) else UNAMEOS:=$(shell uname) ifeq ($(UNAMEOS),Linux) - PLATFORM_OS=LINUX + PLATFORM_OS=linux LIBPATH=linux else ifeq ($(UNAMEOS),Darwin) @@ -73,7 +73,9 @@ endif ifeq ($(PLATFORM),PLATFORM_RPI) CFLAGS = -O2 -s -Wall -std=gnu99 -fgnu89-inline else - CFLAGS = -O2 -s -Wall -std=c99 + ifeq ($(PLATFORM_OS),LINUX) + CFLAGS = -O2 -s -Wall -std=c99 --D_DEFAULT_SOURCE + endif endif ifeq ($(PLATFORM),PLATFORM_WEB) CFLAGS = -O1 -Wall -std=c99 -s USE_GLFW=3 -s ASSERTIONS=1 --preload-file resources @@ -88,7 +90,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),WINDOWS) RAYLIB_PATH = ../release/win32/mingw32 endif - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) RAYLIB_PATH = ../release/linux endif ifeq ($(PLATFORM_OS),OSX) @@ -110,7 +112,7 @@ ifeq ($(PLATFORM),PLATFORM_RPI) endif ifeq ($(PLATFORM),PLATFORM_DESKTOP) # add standard directories for GNU/Linux - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) INCLUDES += -I/usr/local/include/raylib/ else ifeq ($(PLATFORM_OS),WINDOWS) # external libraries headers @@ -141,7 +143,7 @@ endif # define any libraries to link into executable # if you want to link libraries (libname.so or libname.a), use the -lname ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) # libraries for Debian GNU/Linux desktop compiling # requires the following packages: # libglfw3-dev libopenal-dev libegl1-mesa-dev @@ -185,6 +187,11 @@ ifeq ($(PLATFORM_OS),WINDOWS) WINFLAGS = ../src/resources -Wl,--subsystem,windows endif +# Linux Fix to timespect from +ifeq ($(PLATFORM_OS),linux) + CFLAGS += -D_DEFAULT_SOURCE + endif + ifeq ($(PLATFORM),PLATFORM_WEB) EXT = .html endif @@ -207,7 +214,6 @@ EXAMPLES = \ core_3d_camera_first_person \ core_2d_camera \ core_world_screen \ - core_oculus_rift \ shapes_logo_raylib \ shapes_basic_shapes \ shapes_colors_palette \ @@ -338,8 +344,8 @@ core_world_screen: core_world_screen.c $(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDES) $(LFLAGS) $(LIBS) -D$(PLATFORM) $(WINFLAGS) # compile [core] example - oculus rift -core_oculus_rift: core_oculus_rift.c - $(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDES) $(LFLAGS) $(LIBS) -D$(PLATFORM) $(WINFLAGS) +#core_oculus_rift: core_oculus_rift.c +# $(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDES) $(LFLAGS) $(LIBS) -D$(PLATFORM) $(WINFLAGS) # compile [shapes] example - raylib logo (with basic shapes) shapes_logo_raylib: shapes_logo_raylib.c @@ -497,13 +503,6 @@ audio_module_playing: audio_module_playing.c audio_raw_stream: audio_raw_stream.c $(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDES) $(LFLAGS) $(LIBS) -D$(PLATFORM) $(WINFLAGS) -# Linux Fix to timespect from -ifeq ($(PLATFORM),PLATFORM_DESKTOP) - ifeq ($(PLATFORM_OS),LINUX) - CFLAGS += -D_POSIX_C_SOURCE=199309L - endif -endif - # compile [physac] example - physics demo physics_demo: physics_demo.c $(CC) -o $@$(EXT) $< $(CFLAGS) $(INCLUDES) $(LFLAGS) $(LIBS) -lpthread -D$(PLATFORM) $(WINFLAGS) @@ -537,7 +536,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) find . -type f -perm +ugo+x -delete rm -f *.o else - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) find -type f -executable | xargs file -i | grep -E 'x-object|x-archive|x-sharedlib|x-executable' | rev | cut -d ':' -f 2- | rev | xargs rm -f else del *.o *.exe diff --git a/src/Makefile b/src/Makefile index 4c2278f5..eeb0ce35 100644 --- a/src/Makefile +++ b/src/Makefile @@ -60,7 +60,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) else UNAMEOS:=$(shell uname) ifeq ($(UNAMEOS),Linux) - PLATFORM_OS=LINUX + PLATFORM_OS=linux else ifeq ($(UNAMEOS),Darwin) PLATFORM_OS=OSX @@ -153,12 +153,16 @@ endif # define compiler flags: # -O1 defines optimization level +# -Og enable debugging # -Wall turns on most, but not all, compiler warnings # -std=c99 defines C language mode (standard C from 1999 revision) # -std=gnu99 defines C language mode (GNU C from 1999 revision) # -fgnu89-inline declaring inline functions support (GCC optimized) # -Wno-missing-braces ignore invalid warning (GCC bug 53119) -CFLAGS = -O1 -Wall -std=gnu99 -fgnu89-inline -Wno-missing-braces +# -D_DEFAULT_SOURCE use with -std=c99 on Linux to enable timespec and audio +#CFLAGS = -O1 -Wall -std=gnu99 -fgnu89-inline -Wno-missing-braces +CFLAGS = -O1 -Wall -std=c99 -D_DEFAULT_SOURCE + # if shared library required, make sure code is compiled as position independent ifeq ($(SHARED),YES) @@ -213,7 +217,7 @@ ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM_OS),WINDOWS) OUTPUT_PATH = ../release/win32/mingw32 endif - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) OUTPUT_PATH = ../release/linux endif ifeq ($(PLATFORM_OS),OSX) @@ -264,7 +268,7 @@ ifeq ($(PLATFORM),PLATFORM_WEB) @echo "libraylib.bc generated (web version)!" else ifeq ($(SHARED),YES) - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) # compile raylib to shared library version for GNU/Linux. # WARNING: you should type "make clean" before doing this target $(CC) -shared -o $(OUTPUT_PATH)/libraylib.so $(OBJS) @@ -333,7 +337,7 @@ utils.o : utils.c utils.h # TODO: add other platforms. install : ifeq ($(ROOT),root) - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) # On GNU/Linux there are some standard directories that contain # libraries and header files. These directory (/usr/local/lib and # /usr/local/include/) are for libraries that are installed @@ -356,7 +360,7 @@ endif # TODO: see 'install' target. unistall : ifeq ($(ROOT),root) - ifeq ($(PLATFORM_OS),LINUX) + ifeq ($(PLATFORM_OS),linux) rm --force /usr/local/include/raylib.h ifeq ($(SHARED),YES) rm --force /usr/local/lib/libraylib.so diff --git a/src/core.c b/src/core.c index 1423cf7c..1a0e5a66 100644 --- a/src/core.c +++ b/src/core.c @@ -105,7 +105,7 @@ #include // Required for: strcmp() //#include // Macros for reporting and retrieving error conditions through error codes -#if defined __linux || defined(PLATFORM_WEB) +#if defined __linux__ || defined(PLATFORM_WEB) #include // Required for: timespec, nanosleep(), select() - POSIX #elif defined __APPLE__ #include // Required for: usleep() @@ -115,7 +115,7 @@ //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 #include // GLFW3 library: Windows, OpenGL context and Input management - #ifdef __linux + #ifdef __linux__ #define GLFW_EXPOSE_NATIVE_X11 // Linux specific definitions for getting #define GLFW_EXPOSE_NATIVE_GLX // native functions like glfwGetX11Window #include // which are required for hiding mouse @@ -641,7 +641,7 @@ int GetScreenHeight(void) void ShowCursor() { #if defined(PLATFORM_DESKTOP) - #ifdef __linux + #ifdef __linux__ XUndefineCursor(glfwGetX11Display(), glfwGetX11Window(window)); #else glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); @@ -654,7 +654,7 @@ void ShowCursor() void HideCursor() { #if defined(PLATFORM_DESKTOP) - #ifdef __linux + #ifdef __linux__ XColor col; const char nil[] = {0}; @@ -2036,7 +2036,7 @@ static void Wait(float ms) #else #if defined _WIN32 Sleep(ms); - #elif defined __linux || defined(PLATFORM_WEB) + #elif defined __linux__ || defined(PLATFORM_WEB) struct timespec req = { 0 }; time_t sec = (int)(ms/1000.0f); ms -= (sec*1000); diff --git a/src/gestures.h b/src/gestures.h index 42ced889..c97871e5 100644 --- a/src/gestures.h +++ b/src/gestures.h @@ -147,7 +147,7 @@ float GetGesturePinchAngle(void); // Get gesture pinch ang // Functions required to query time on Windows int __stdcall QueryPerformanceCounter(unsigned long long int *lpPerformanceCount); int __stdcall QueryPerformanceFrequency(unsigned long long int *lpFrequency); -#elif defined(__linux) +#elif defined(__linux__) #include // Required for: timespec #include // Required for: clock_gettime() #endif @@ -517,7 +517,7 @@ static double GetCurrentTime(void) time = (double)currentTime/clockFrequency*1000.0f; // Time in miliseconds #endif -#if defined(__linux) +#if defined(__linux__) // NOTE: Only for Linux-based systems struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); diff --git a/src/physac.h b/src/physac.h index ff56615d..1aa0adee 100644 --- a/src/physac.h +++ b/src/physac.h @@ -249,7 +249,7 @@ PHYSACDEF void ClosePhysics(void); // Functions required to query time on Windows int __stdcall QueryPerformanceCounter(unsigned long long int *lpPerformanceCount); int __stdcall QueryPerformanceFrequency(unsigned long long int *lpFrequency); -#elif defined(__linux) || defined(PLATFORM_WEB) +#elif defined(__linux__) || defined(PLATFORM_WEB) #include // Required for: timespec #include // Required for: clock_gettime() #include @@ -277,7 +277,7 @@ PHYSACDEF void ClosePhysics(void); static unsigned int usedMemory = 0; // Total allocated dynamic memory static bool physicsThreadEnabled = false; // Physics thread enabled state static double currentTime = 0; // Current time in milliseconds -#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux) || defined(PLATFORM_WEB) +#if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux__) || defined(PLATFORM_WEB) static double baseTime = 0; // Android and RPI platforms base time #endif static double startTime = 0; // Start time in milliseconds @@ -1906,7 +1906,7 @@ static double GetCurrentTime(void) time = (double)((double)currentTime/clockFrequency)*1000; #endif - #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux) || defined(PLATFORM_WEB) + #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) || defined(__linux__) || defined(PLATFORM_WEB) struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); uint64_t temp = (uint64_t)ts.tv_sec*1000000000LLU + (uint64_t)ts.tv_nsec; -- cgit v1.2.3 From 5387b4543175bee9d195b24e250a0ef863a63555 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 25 Mar 2017 12:01:01 +0100 Subject: Working on configuration flags --- src/core.c | 6 +- src/raylib.h | 2 +- src/rlgl.c | 21 +++- src/textures.c | 345 ++++++++++++++++++++++++++++++++++----------------------- src/utils.c | 2 +- 5 files changed, 228 insertions(+), 148 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 1a0e5a66..5a1ab77f 100644 --- a/src/core.c +++ b/src/core.c @@ -70,13 +70,13 @@ * **********************************************************************************************/ -// Default supported features -//------------------------------------- +// Default configuration flags (supported features) +//------------------------------------------------- #define SUPPORT_DEFAULT_FONT #define SUPPORT_MOUSE_GESTURES #define SUPPORT_CAMERA_SYSTEM #define SUPPORT_GESTURES_SYSTEM -//------------------------------------- +//------------------------------------------------- #include "raylib.h" diff --git a/src/raylib.h b/src/raylib.h index cdefceb2..24d6e1fd 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -13,7 +13,7 @@ * - Multiple textures support, including compressed formats and mipmaps generation * - Basic 3d support for Shapes, Models, Billboards, Heightmaps and Cubicmaps * - Powerful math module for Vector, Matrix and Quaternion operations: [raymath] -* - Audio loading and playing with streaming support and mixing channels [audio] +* - Audio loading and playing with streaming support and mixing channels: [audio] * - VR stereo rendering support with configurable HMD device parameters * - Multiple platforms support: Windows, Linux, Mac, Android, Raspberry Pi, HTML5 and Oculus Rift CV1 * - Custom color palette for fancy visuals on raywhite background diff --git a/src/rlgl.c b/src/rlgl.c index a937bdec..546fbe6e 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -25,7 +25,7 @@ * #define SUPPORT_VR_SIMULATION / SUPPORT_STEREO_RENDERING * Support VR simulation functionality (stereo rendering) * -* #define SUPPORT_SHADER_DISTORTION +* #define SUPPORT_DISTORTION_SHADER * Include stereo rendering distortion shader (shader_distortion.h) * * DEPENDENCIES: @@ -54,6 +54,11 @@ * **********************************************************************************************/ +// Default configuration flags (supported features) +//------------------------------------------------- +#define SUPPORT_VR_SIMULATION +//------------------------------------------------- + #include "rlgl.h" #include // Required for: fopen(), fclose(), fread()... [Used only on LoadText()] @@ -100,7 +105,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() [Used only on TraceLog()] #endif -#if !defined(GRAPHICS_API_OPENGL_11) && !defined(RLGL_NO_DISTORTION_SHADER) +#if !defined(GRAPHICS_API_OPENGL_11) && defined(SUPPORT_DISTORTION_SHADER) #include "shader_distortion.h" // Distortion shader to be embedded #endif @@ -2591,10 +2596,12 @@ void InitVrSimulator(int vrDevice) // Initialize framebuffer and textures for stereo rendering // NOTE: screen size should match HMD aspect ratio vrConfig.stereoFbo = rlglLoadRenderTexture(screenWidth, screenHeight); - + +#if defined(SUPPORT_DISTORTION_SHADER) // Load distortion shader (initialized by default with Oculus Rift CV1 parameters) vrConfig.distortionShader.id = LoadShaderProgram(vDistortionShaderStr, fDistortionShaderStr); if (vrConfig.distortionShader.id != 0) LoadDefaultShaderLocations(&vrConfig.distortionShader); +#endif SetStereoConfig(hmd); @@ -2613,7 +2620,9 @@ void CloseVrSimulator(void) if (vrSimulatorReady) { rlDeleteRenderTextures(vrConfig.stereoFbo); // Unload stereo framebuffer and texture + #if defined(SUPPORT_DISTORTION_SHADER) UnloadShader(vrConfig.distortionShader); // Unload distortion shader + #endif } #endif } @@ -2700,8 +2709,12 @@ void EndVrDrawing(void) rlMatrixMode(RL_MODELVIEW); // Enable internal modelview matrix rlLoadIdentity(); // Reset internal modelview matrix +#if defined(SUPPORT_DISTORTION_SHADER) // Draw RenderTexture (stereoFbo) using distortion shader currentShader = vrConfig.distortionShader; +#else + currentShader = GetDefaultShader(); +#endif rlEnableTexture(vrConfig.stereoFbo.texture.id); @@ -3536,6 +3549,7 @@ static void SetStereoConfig(VrDeviceInfo hmd) TraceLog(DEBUG, "VR: Distortion Shader: Scale = { %f, %f }", scale[0], scale[1]); TraceLog(DEBUG, "VR: Distortion Shader: ScaleIn = { %f, %f }", scaleIn[0], scaleIn[1]); +#if defined(SUPPORT_DISTORTION_SHADER) // Update distortion shader with lens and distortion-scale parameters SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "leftLensCenter"), leftLensCenter, 2); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "rightLensCenter"), rightLensCenter, 2); @@ -3546,6 +3560,7 @@ static void SetStereoConfig(VrDeviceInfo hmd) SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "scaleIn"), scaleIn, 2); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "hmdWarpParam"), hmd.distortionK, 4); SetShaderValue(vrConfig.distortionShader, GetShaderLocation(vrConfig.distortionShader, "chromaAbParam"), hmd.chromaAbCorrection, 4); +#endif // Fovy is normally computed with: 2*atan2(hmd.vScreenSize, 2*hmd.eyeToScreenDistance)*RAD2DEG // ...but with lens distortion it is increased (see Oculus SDK Documentation) diff --git a/src/textures.c b/src/textures.c index f323f352..6fff8e75 100644 --- a/src/textures.c +++ b/src/textures.c @@ -4,24 +4,24 @@ * * CONFIGURATION: * -* #define SUPPORT_STB_IMAGE / INCLUDE_STB_IMAGE -* -* #define SUPPORT_FILEFORMAT_BMP / SUPPORT_LOAD_BMP -* #define SUPPORT_FILEFORMAT_PNG / SUPPORT_LOAD_PNG +* #define SUPPORT_FILEFORMAT_BMP +* #define SUPPORT_FILEFORMAT_PNG * #define SUPPORT_FILEFORMAT_TGA -* #define SUPPORT_FILEFORMAT_JPG / ENABLE_LOAD_JPG +* #define SUPPORT_FILEFORMAT_JPG * #define SUPPORT_FILEFORMAT_GIF +* #define SUPPORT_FILEFORMAT_PSD * #define SUPPORT_FILEFORMAT_HDR -* #define SUPPORT_FILEFORMAT_DDS / ENABLE_LOAD_DDS +* #define SUPPORT_FILEFORMAT_DDS * #define SUPPORT_FILEFORMAT_PKM * #define SUPPORT_FILEFORMAT_KTX * #define SUPPORT_FILEFORMAT_PVR * #define SUPPORT_FILEFORMAT_ASTC -* Selected desired fileformats to be supported for loading. Some of those formats are +* Selecte desired fileformats to be supported for image data loading. Some of those formats are * supported by default, to remove support, just comment unrequired #define in this module * -* #define SUPPORT_IMAGE_RESIZE / INCLUDE_STB_IMAGE_RESIZE * #define SUPPORT_IMAGE_MANIPULATION +* Support multiple image editing functions to scale, adjust colors, flip, draw on images, crop... +* If not defined only three image editing functions supported: ImageFormat(), ImageAlphaMask(), ImageToPOT() * * DEPENDENCIES: * stb_image - Multiple image formats loading (JPEG, PNG, BMP, TGA, PSD, GIF, PIC) @@ -50,6 +50,12 @@ * **********************************************************************************************/ +// Default configuration flags (supported features) +//------------------------------------------------- +#define SUPPORT_FILEFORMAT_PNG +#define SUPPORT_IMAGE_MANIPULATION +//------------------------------------------------- + #include "raylib.h" #include // Required for: malloc(), free() @@ -61,23 +67,46 @@ #include "utils.h" // Required for: fopen() Android mapping, TraceLog() -// Support only desired texture formats, by default: JPEG, PNG, BMP, TGA -//#define STBI_NO_JPEG // Image format .jpg and .jpeg -//#define STBI_NO_PNG -//#define STBI_NO_BMP -//#define STBI_NO_TGA -#define STBI_NO_PSD -#define STBI_NO_GIF -#define STBI_NO_HDR +// Support only desired texture formats on stb_image +#if !defined(SUPPORT_FILEFORMAT_BMP) + #define STBI_NO_BMP +#endif +#if !defined(SUPPORT_FILEFORMAT_PNG) + #define STBI_NO_PNG +#endif +#if !defined(SUPPORT_FILEFORMAT_TGA) + #define STBI_NO_TGA +#endif +#if !defined(SUPPORT_FILEFORMAT_JPG) + #define STBI_NO_JPEG // Image format .jpg and .jpeg +#endif +#if !defined(SUPPORT_FILEFORMAT_PSD) + #define STBI_NO_PSD +#endif +#if !defined(SUPPORT_FILEFORMAT_GIF) + #define STBI_NO_GIF +#endif +#if !defined(SUPPORT_FILEFORMAT_HDR) + #define STBI_NO_HDR +#endif + +// Image fileformats not supported by default #define STBI_NO_PIC #define STBI_NO_PNM // Image format .ppm and .pgm -#define STB_IMAGE_IMPLEMENTATION -#include "external/stb_image.h" // Required for: stbi_load() - // NOTE: Used to read image data (multiple formats support) -#define STB_IMAGE_RESIZE_IMPLEMENTATION -#include "external/stb_image_resize.h" // Required for: stbir_resize_uint8() - // NOTE: Used for image scaling on ImageResize() +#if (defined(SUPPORT_FILEFORMAT_BMP) || defined(SUPPORT_FILEFORMAT_PNG) || defined(SUPPORT_FILEFORMAT_TGA) || \ + defined(SUPPORT_FILEFORMAT_JPG) || defined(SUPPORT_FILEFORMAT_PSD) || defined(SUPPORT_FILEFORMAT_GIF) || \ + defined(SUPPORT_FILEFORMAT_HDR)) + #define STB_IMAGE_IMPLEMENTATION + #include "external/stb_image.h" // Required for: stbi_load() + // NOTE: Used to read image data (multiple formats support) +#endif + +#if defined(SUPPORT_IMAGE_MANIPULATION) + #define STB_IMAGE_RESIZE_IMPLEMENTATION + #include "external/stb_image_resize.h" // Required for: stbir_resize_uint8() + // NOTE: Used for image scaling on ImageResize() +#endif //---------------------------------------------------------------------------------- // Defines and Macros @@ -102,11 +131,21 @@ //---------------------------------------------------------------------------------- // Module specific Functions Declaration //---------------------------------------------------------------------------------- +#if defined(SUPPORT_FILEFORMAT_DDS) static Image LoadDDS(const char *fileName); // Load DDS file +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) static Image LoadPKM(const char *fileName); // Load PKM file +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) static Image LoadKTX(const char *fileName); // Load KTX file +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) static Image LoadPVR(const char *fileName); // Load PVR file +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) static Image LoadASTC(const char *fileName); // Load ASTC file +#endif //---------------------------------------------------------------------------------- // Module Functions Definition @@ -124,18 +163,21 @@ Image LoadImage(const char *fileName) image.mipmaps = 0; image.format = 0; - if ((strcmp(GetExtension(fileName),"png") == 0) || - (strcmp(GetExtension(fileName),"bmp") == 0) || - (strcmp(GetExtension(fileName),"tga") == 0) || - (strcmp(GetExtension(fileName),"jpg") == 0) -#ifndef STBI_NO_GIF + if ((strcmp(GetExtension(fileName),"png") == 0) +#if defined(SUPPORT_FILEFORMAT_BMP) + || (strcmp(GetExtension(fileName),"bmp") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_TGA) + || (strcmp(GetExtension(fileName),"tga") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_JPG) + || (strcmp(GetExtension(fileName),"jpg") == 0) +#endif +#if defined(SUPPORT_FILEFORMAT_DDS) || (strcmp(GetExtension(fileName),"gif") == 0) #endif -#ifndef STBI_NO_PSD +#if defined(SUPPORT_FILEFORMAT_PSD) || (strcmp(GetExtension(fileName),"psd") == 0) -#endif -#ifndef STBI_NO_PIC - || (strcmp(GetExtension(fileName),"pic") == 0) #endif ) { @@ -155,11 +197,21 @@ Image LoadImage(const char *fileName) else if (imgBpp == 3) image.format = UNCOMPRESSED_R8G8B8; else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } +#if defined(SUPPORT_FILEFORMAT_DDS) else if (strcmp(GetExtension(fileName),"dds") == 0) image = LoadDDS(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) else if (strcmp(GetExtension(fileName),"pkm") == 0) image = LoadPKM(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) else if (strcmp(GetExtension(fileName),"ktx") == 0) image = LoadKTX(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) else if (strcmp(GetExtension(fileName),"pvr") == 0) image = LoadPVR(fileName); +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) else if (strcmp(GetExtension(fileName),"astc") == 0) image = LoadASTC(fileName); +#endif else if (strcmp(GetExtension(fileName),"rres") == 0) { RRES rres = LoadResource(fileName, 0); @@ -171,6 +223,7 @@ Image LoadImage(const char *fileName) UnloadResource(rres); } + else TraceLog("[%s] Image fileformat not supported", fileName); if (image.data != NULL) TraceLog(INFO, "[%s] Image loaded successfully (%ix%i)", fileName, image.width, image.height); else TraceLog(WARNING, "[%s] Image could not be loaded", fileName); @@ -664,115 +717,6 @@ void ImageAlphaMask(Image *image, Image alphaMask) } } -// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) -// NOTE: In case selected bpp do not represent an known 16bit format, -// dithered data is stored in the LSB part of the unsigned short -void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) -{ - if (image->format >= COMPRESSED_DXT1_RGB) - { - TraceLog(WARNING, "Compressed data formats can not be dithered"); - return; - } - - if ((rBpp+gBpp+bBpp+aBpp) > 16) - { - TraceLog(WARNING, "Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp)); - } - else - { - Color *pixels = GetImageData(*image); - - free(image->data); // free old image data - - if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) - { - TraceLog(WARNING, "Image format is already 16bpp or lower, dithering could have no effect"); - } - - // Define new image format, check if desired bpp match internal known format - if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = UNCOMPRESSED_R5G6B5; - else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = UNCOMPRESSED_R5G5B5A1; - else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = UNCOMPRESSED_R4G4B4A4; - else - { - image->format = 0; - TraceLog(WARNING, "Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp); - } - - // NOTE: We will store the dithered data as unsigned short (16bpp) - image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); - - Color oldPixel = WHITE; - Color newPixel = WHITE; - - int rError, gError, bError; - unsigned short rPixel, gPixel, bPixel, aPixel; // Used for 16bit pixel composition - - #define MIN(a,b) (((a)<(b))?(a):(b)) - - for (int y = 0; y < image->height; y++) - { - for (int x = 0; x < image->width; x++) - { - oldPixel = pixels[y*image->width + x]; - - // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat()) - newPixel.r = oldPixel.r >> (8 - rBpp); // R bits - newPixel.g = oldPixel.g >> (8 - gBpp); // G bits - newPixel.b = oldPixel.b >> (8 - bBpp); // B bits - newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering) - - // NOTE: Error must be computed between new and old pixel but using same number of bits! - // We want to know how much color precision we have lost... - rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp)); - gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp)); - bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp)); - - pixels[y*image->width + x] = newPixel; - - // NOTE: Some cases are out of the array and should be ignored - if (x < (image->width - 1)) - { - pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff); - pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff); - pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff); - } - - if ((x > 0) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff); - pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff); - } - - if (y < (image->height - 1)) - { - pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff); - pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff); - } - - if ((x < (image->width - 1)) && (y < (image->height - 1))) - { - pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff); - pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff); - } - - rPixel = (unsigned short)newPixel.r; - gPixel = (unsigned short)newPixel.g; - bPixel = (unsigned short)newPixel.b; - aPixel = (unsigned short)newPixel.a; - - ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel; - } - } - - free(pixels); - } -} - // Convert image to POT (power-of-two) // NOTE: It could be useful on OpenGL ES 2.0 (RPI, HTML5) void ImageToPOT(Image *image, Color fillColor) @@ -818,6 +762,7 @@ void ImageToPOT(Image *image, Color fillColor) } } +#if defined(SUPPORT_IMAGE_MANIPULATION) // Copy an image to a new image Image ImageCopy(Image image) { @@ -1203,6 +1148,115 @@ void ImageFlipHorizontal(Image *image) image->data = processed.data; } +// Dither image data to 16bpp or lower (Floyd-Steinberg dithering) +// NOTE: In case selected bpp do not represent an known 16bit format, +// dithered data is stored in the LSB part of the unsigned short +void ImageDither(Image *image, int rBpp, int gBpp, int bBpp, int aBpp) +{ + if (image->format >= COMPRESSED_DXT1_RGB) + { + TraceLog(WARNING, "Compressed data formats can not be dithered"); + return; + } + + if ((rBpp+gBpp+bBpp+aBpp) > 16) + { + TraceLog(WARNING, "Unsupported dithering bpps (%ibpp), only 16bpp or lower modes supported", (rBpp+gBpp+bBpp+aBpp)); + } + else + { + Color *pixels = GetImageData(*image); + + free(image->data); // free old image data + + if ((image->format != UNCOMPRESSED_R8G8B8) && (image->format != UNCOMPRESSED_R8G8B8A8)) + { + TraceLog(WARNING, "Image format is already 16bpp or lower, dithering could have no effect"); + } + + // Define new image format, check if desired bpp match internal known format + if ((rBpp == 5) && (gBpp == 6) && (bBpp == 5) && (aBpp == 0)) image->format = UNCOMPRESSED_R5G6B5; + else if ((rBpp == 5) && (gBpp == 5) && (bBpp == 5) && (aBpp == 1)) image->format = UNCOMPRESSED_R5G5B5A1; + else if ((rBpp == 4) && (gBpp == 4) && (bBpp == 4) && (aBpp == 4)) image->format = UNCOMPRESSED_R4G4B4A4; + else + { + image->format = 0; + TraceLog(WARNING, "Unsupported dithered OpenGL internal format: %ibpp (R%iG%iB%iA%i)", (rBpp+gBpp+bBpp+aBpp), rBpp, gBpp, bBpp, aBpp); + } + + // NOTE: We will store the dithered data as unsigned short (16bpp) + image->data = (unsigned short *)malloc(image->width*image->height*sizeof(unsigned short)); + + Color oldPixel = WHITE; + Color newPixel = WHITE; + + int rError, gError, bError; + unsigned short rPixel, gPixel, bPixel, aPixel; // Used for 16bit pixel composition + + #define MIN(a,b) (((a)<(b))?(a):(b)) + + for (int y = 0; y < image->height; y++) + { + for (int x = 0; x < image->width; x++) + { + oldPixel = pixels[y*image->width + x]; + + // NOTE: New pixel obtained by bits truncate, it would be better to round values (check ImageFormat()) + newPixel.r = oldPixel.r >> (8 - rBpp); // R bits + newPixel.g = oldPixel.g >> (8 - gBpp); // G bits + newPixel.b = oldPixel.b >> (8 - bBpp); // B bits + newPixel.a = oldPixel.a >> (8 - aBpp); // A bits (not used on dithering) + + // NOTE: Error must be computed between new and old pixel but using same number of bits! + // We want to know how much color precision we have lost... + rError = (int)oldPixel.r - (int)(newPixel.r << (8 - rBpp)); + gError = (int)oldPixel.g - (int)(newPixel.g << (8 - gBpp)); + bError = (int)oldPixel.b - (int)(newPixel.b << (8 - bBpp)); + + pixels[y*image->width + x] = newPixel; + + // NOTE: Some cases are out of the array and should be ignored + if (x < (image->width - 1)) + { + pixels[y*image->width + x+1].r = MIN((int)pixels[y*image->width + x+1].r + (int)((float)rError*7.0f/16), 0xff); + pixels[y*image->width + x+1].g = MIN((int)pixels[y*image->width + x+1].g + (int)((float)gError*7.0f/16), 0xff); + pixels[y*image->width + x+1].b = MIN((int)pixels[y*image->width + x+1].b + (int)((float)bError*7.0f/16), 0xff); + } + + if ((x > 0) && (y < (image->height - 1))) + { + pixels[(y+1)*image->width + x-1].r = MIN((int)pixels[(y+1)*image->width + x-1].r + (int)((float)rError*3.0f/16), 0xff); + pixels[(y+1)*image->width + x-1].g = MIN((int)pixels[(y+1)*image->width + x-1].g + (int)((float)gError*3.0f/16), 0xff); + pixels[(y+1)*image->width + x-1].b = MIN((int)pixels[(y+1)*image->width + x-1].b + (int)((float)bError*3.0f/16), 0xff); + } + + if (y < (image->height - 1)) + { + pixels[(y+1)*image->width + x].r = MIN((int)pixels[(y+1)*image->width + x].r + (int)((float)rError*5.0f/16), 0xff); + pixels[(y+1)*image->width + x].g = MIN((int)pixels[(y+1)*image->width + x].g + (int)((float)gError*5.0f/16), 0xff); + pixels[(y+1)*image->width + x].b = MIN((int)pixels[(y+1)*image->width + x].b + (int)((float)bError*5.0f/16), 0xff); + } + + if ((x < (image->width - 1)) && (y < (image->height - 1))) + { + pixels[(y+1)*image->width + x+1].r = MIN((int)pixels[(y+1)*image->width + x+1].r + (int)((float)rError*1.0f/16), 0xff); + pixels[(y+1)*image->width + x+1].g = MIN((int)pixels[(y+1)*image->width + x+1].g + (int)((float)gError*1.0f/16), 0xff); + pixels[(y+1)*image->width + x+1].b = MIN((int)pixels[(y+1)*image->width + x+1].b + (int)((float)bError*1.0f/16), 0xff); + } + + rPixel = (unsigned short)newPixel.r; + gPixel = (unsigned short)newPixel.g; + bPixel = (unsigned short)newPixel.b; + aPixel = (unsigned short)newPixel.a; + + ((unsigned short *)image->data)[y*image->width + x] = (rPixel << (gBpp + bBpp + aBpp)) | (gPixel << (bBpp + aBpp)) | (bPixel << aBpp) | aPixel; + } + } + + free(pixels); + } +} + // Modify image color: tint void ImageColorTint(Image *image, Color color) { @@ -1359,6 +1413,7 @@ void ImageColorBrightness(Image *image, int brightness) image->data = processed.data; } +#endif // SUPPORT_IMAGE_MANIPULATION // Generate GPU mipmaps for a texture void GenTextureMipmaps(Texture2D *texture) @@ -1547,6 +1602,7 @@ void DrawTexturePro(Texture2D texture, Rectangle sourceRec, Rectangle destRec, V // Module specific Functions Definition //---------------------------------------------------------------------------------- +#if defined(SUPPORT_FILEFORMAT_DDS) // Loading DDS image data (compressed or uncompressed) static Image LoadDDS(const char *fileName) { @@ -1744,7 +1800,9 @@ static Image LoadDDS(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_PKM) // Loading PKM image data (ETC1/ETC2 compression) // NOTE: KTX is the standard Khronos Group compression format (ETC1/ETC2, mipmaps) // PKM is a much simpler file format used mainly to contain a single ETC1/ETC2 compressed image (no mipmaps) @@ -1836,7 +1894,9 @@ static Image LoadPKM(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_KTX) // Load KTX compressed image data (ETC1/ETC2 compression) static Image LoadKTX(const char *fileName) { @@ -1929,7 +1989,9 @@ static Image LoadKTX(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_PVR) // Loading PVR image data (uncompressed or PVRT compression) // NOTE: PVR v2 not supported, use PVR v3 instead static Image LoadPVR(const char *fileName) @@ -2087,7 +2149,9 @@ static Image LoadPVR(const char *fileName) return image; } +#endif +#if defined(SUPPORT_FILEFORMAT_ASTC) // Load ASTC compressed image data (ASTC compression) static Image LoadASTC(const char *fileName) { @@ -2170,3 +2234,4 @@ static Image LoadASTC(const char *fileName) return image; } +#endif \ No newline at end of file diff --git a/src/utils.c b/src/utils.c index 4d30cbc7..b6b309cc 100644 --- a/src/utils.c +++ b/src/utils.c @@ -20,7 +20,7 @@ * Show TraceLog() DEBUG messages * * DEPENDENCIES: -* stb_image_write - PNG writting functions +* stb_image_write - BMP/PNG writting functions * * * LICENSE: zlib/libpng -- cgit v1.2.3 From b5dd18a70c6c660c727fd1c18b13222678974a74 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 28 Mar 2017 19:15:27 +0200 Subject: Review Sleep() usage, return to busy-wait-loop --- src/core.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 5a1ab77f..b8d822a8 100644 --- a/src/core.c +++ b/src/core.c @@ -2024,9 +2024,12 @@ static double GetTime(void) } // Wait for some milliseconds (stop program execution) +// NOTE: Sleep() granularity could be around 10 ms, it means, Sleep() could +// take longer than expected... for that reason we use the busy wait loop +// http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected static void Wait(float ms) { -//#define SUPPORT_BUSY_WAIT_LOOP +#define SUPPORT_BUSY_WAIT_LOOP #if defined(SUPPORT_BUSY_WAIT_LOOP) double prevTime = GetTime(); double nextTime = 0.0; @@ -2035,7 +2038,7 @@ static void Wait(float ms) while ((nextTime - prevTime) < ms/1000.0f) nextTime = GetTime(); #else #if defined _WIN32 - Sleep(ms); + Sleep((unsigned int)ms); #elif defined __linux__ || defined(PLATFORM_WEB) struct timespec req = { 0 }; time_t sec = (int)(ms/1000.0f); -- cgit v1.2.3 From 080a79f0b03bd40a4ac6dfb8c6f90a3a7379d7ad Mon Sep 17 00:00:00 2001 From: Ray Date: Wed, 29 Mar 2017 00:35:42 +0200 Subject: Added IsFileExtension() Replaced old GetExtension() function Make IsFileExtension() public to the API --- src/audio.c | 39 +++++++++++++++++++++------------------ src/audio.h | 7 ++++--- src/core.c | 22 ++++++++++++++++++---- src/models.c | 4 ++-- src/raylib.h | 5 +++-- src/text.c | 10 +++++----- src/textures.c | 46 +++++++++++++++++++++++----------------------- src/utils.c | 22 +++++----------------- src/utils.h | 5 ++--- 9 files changed, 83 insertions(+), 77 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index 5edabf41..34be4789 100644 --- a/src/audio.c +++ b/src/audio.c @@ -24,7 +24,6 @@ * Selected desired fileformats to be supported for loading. Some of those formats are * supported by default, to remove support, just comment unrequired #define in this module * -* * LIMITATIONS: * Only up to two channels supported: MONO and STEREO (for additional channels, use AL_EXT_MCFORMATS) * Only the following sample sizes supported: 8bit PCM, 16bit PCM, 32-bit float PCM (using AL_EXT_FLOAT32) @@ -65,8 +64,6 @@ * **********************************************************************************************/ -//#define AUDIO_STANDALONE // NOTE: To use the audio module as standalone lib, just uncomment this line - // Default configuration flags (supported features) //------------------------------------------------- #define SUPPORT_FILEFORMAT_WAV @@ -194,8 +191,8 @@ static Wave LoadFLAC(const char *fileName); // Load FLAC file #endif #if defined(AUDIO_STANDALONE) -const char *GetExtension(const char *fileName); // Get the extension for a filename -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message (INFO, ERROR, WARNING) +bool IsFileExtension(const char *fileName, const char *ext); // Check file extension +void TraceLog(int msgType, const char *text, ...); // Outputs trace log message (INFO, ERROR, WARNING) #endif //---------------------------------------------------------------------------------- @@ -285,15 +282,15 @@ Wave LoadWave(const char *fileName) { Wave wave = { 0 }; - if (strcmp(GetExtension(fileName), "wav") == 0) wave = LoadWAV(fileName); + if (IsFileExtension(fileName, ".wav")) wave = LoadWAV(fileName); #if defined(SUPPORT_FILEFORMAT_OGG) - else if (strcmp(GetExtension(fileName), "ogg") == 0) wave = LoadOGG(fileName); + else if (IsFileExtension(fileName, ".ogg")) wave = LoadOGG(fileName); #endif #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (strcmp(GetExtension(fileName), "flac") == 0) wave = LoadFLAC(fileName); + else if (IsFileExtension(fileName, ".flac")) wave = LoadFLAC(fileName); #endif #if !defined(AUDIO_STANDALONE) - else if (strcmp(GetExtension(fileName),"rres") == 0) + else if (IsFileExtension(fileName, ".rres")) { RRES rres = LoadResource(fileName, 0); @@ -672,7 +669,7 @@ Music LoadMusicStream(const char *fileName) { Music music = (MusicData *)malloc(sizeof(MusicData)); - if (strcmp(GetExtension(fileName), "ogg") == 0) + if (IsFileExtension(fileName, ".ogg")) { // Open ogg audio stream music->ctxOgg = stb_vorbis_open_filename(fileName, NULL, NULL); @@ -696,7 +693,7 @@ Music LoadMusicStream(const char *fileName) } } #if defined(SUPPORT_FILEFORMAT_FLAC) - else if (strcmp(GetExtension(fileName), "flac") == 0) + else if (IsFileExtension(fileName, ".flac")) { music->ctxFlac = drflac_open_file(fileName); @@ -717,7 +714,7 @@ Music LoadMusicStream(const char *fileName) } #endif #if defined(SUPPORT_FILEFORMAT_XM) - else if (strcmp(GetExtension(fileName), "xm") == 0) + else if (IsFileExtension(fileName, ".xm")) { int result = jar_xm_create_context_from_file(&music->ctxXm, 48000, fileName); @@ -739,7 +736,7 @@ Music LoadMusicStream(const char *fileName) } #endif #if defined(SUPPORT_FILEFORMAT_MOD) - else if (strcmp(GetExtension(fileName), "mod") == 0) + else if (IsFileExtension(fileName, ".mod")) { jar_mod_init(&music->ctxMod); @@ -1310,12 +1307,18 @@ static Wave LoadFLAC(const char *fileName) // Some required functions for audio standalone module version #if defined(AUDIO_STANDALONE) -// Get the extension for a filename -const char *GetExtension(const char *fileName) +// Check file extension +bool IsFileExtension(const char *fileName, const char *ext) { - const char *dot = strrchr(fileName, '.'); - if (!dot || dot == fileName) return ""; - return (dot + 1); + bool result = false; + const char *fileExt; + + if ((fileExt = strrchr(fileName, '.')) != NULL) + { + if (strcmp(fileExt, ext) == 0) result = true; + } + + return result; } // Outputs a trace log message (INFO, ERROR, WARNING) diff --git a/src/audio.h b/src/audio.h index 51f858da..48ef7403 100644 --- a/src/audio.h +++ b/src/audio.h @@ -123,7 +123,7 @@ Wave LoadWave(const char *fileName); // Load wave dat Wave LoadWaveEx(void *data, int sampleCount, int sampleRate, int sampleSize, int channels); // Load wave data from raw array data Sound LoadSound(const char *fileName); // Load sound from file Sound LoadSoundFromWave(Wave wave); // Load sound from wave data -void UpdateSound(Sound sound, const void *data, int samplesCount); // Update sound buffer with new data +void UpdateSound(Sound sound, const void *data, int samplesCount);// Update sound buffer with new data void UnloadWave(Wave wave); // Unload wave data void UnloadSound(Sound sound); // Unload sound void PlaySound(Sound sound); // Play a sound @@ -151,9 +151,10 @@ void SetMusicLoopCount(Music music, float count); // Set music loo float GetMusicTimeLength(Music music); // Get music time length (in seconds) float GetMusicTimePlayed(Music music); // Get current music time played (in seconds) +// Raw audio stream functions AudioStream InitAudioStream(unsigned int sampleRate, - unsigned int sampleSize, - unsigned int channels); // Init audio stream (to stream raw audio pcm data) + unsigned int sampleSize, + unsigned int channels); // Init audio stream (to stream raw audio pcm data) void UpdateAudioStream(AudioStream stream, const void *data, int samplesCount); // Update audio stream buffers with data void CloseAudioStream(AudioStream stream); // Close audio stream and free memory bool IsAudioBufferProcessed(AudioStream stream); // Check if any audio stream buffers requires refill diff --git a/src/core.c b/src/core.c index b8d822a8..b9ea9315 100644 --- a/src/core.c +++ b/src/core.c @@ -102,7 +102,7 @@ #include // Required for: typedef unsigned long long int uint64_t, used by hi-res timer #include // Required for: time() - Android/RPI hi-res timer (NOTE: Linux only!) #include // Required for: tan() [Used in Begin3dMode() to set perspective] -#include // Required for: strcmp() +#include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes #if defined __linux__ || defined(PLATFORM_WEB) @@ -978,6 +978,12 @@ Color Fade(Color color, float alpha) return (Color){color.r, color.g, color.b, (unsigned char)colorAlpha}; } +// Activates raylib logo at startup +void ShowLogo(void) +{ + showLogo = true; +} + // Enable some window/system configurations void SetConfigFlags(char flags) { @@ -987,10 +993,18 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } -// Activates raylib logo at startup -void ShowLogo(void) +// Check file extension +bool IsFileExtension(const char *fileName, const char *ext) { - showLogo = true; + bool result = false; + const char *fileExt; + + if ((fileExt = strrchr(fileName, '.')) != NULL) + { + if (strcmp(fileExt, ext) == 0) result = true; + } + + return result; } #if defined(PLATFORM_DESKTOP) diff --git a/src/models.c b/src/models.c index 6aff59c4..47220af8 100644 --- a/src/models.c +++ b/src/models.c @@ -593,7 +593,7 @@ Mesh LoadMesh(const char *fileName) Mesh mesh = { 0 }; #if defined(SUPPORT_FILEFORMAT_OBJ) - if (strcmp(GetExtension(fileName), "obj") == 0) mesh = LoadOBJ(fileName); + if (IsFileExtension(fileName, ".obj")) mesh = LoadOBJ(fileName); #else TraceLog(WARNING, "[%s] Mesh fileformat not supported, it can't be loaded", fileName); #endif @@ -706,7 +706,7 @@ Material LoadMaterial(const char *fileName) Material material = { 0 }; #if defined(SUPPORT_FILEFORMAT_MTL) - if (strcmp(GetExtension(fileName), "mtl") == 0) material = LoadMTL(fileName); + if (IsFileExtension(fileName, ".mtl")) material = LoadMTL(fileName); #else TraceLog(WARNING, "[%s] Material fileformat not supported, it can't be loaded", fileName); #endif diff --git a/src/raylib.h b/src/raylib.h index 24d6e1fd..3e6c68ff 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -687,9 +687,10 @@ RLAPI float *MatrixToFloat(Matrix mat); // Converts Ma RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) -//RLAPI void TraceLog(int logType, const char *text, ...); // Trace log messages showing (INFO, WARNING, ERROR, DEBUG) +RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags +//RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window diff --git a/src/text.c b/src/text.c index c736d5ad..09f69ff6 100644 --- a/src/text.c +++ b/src/text.c @@ -48,7 +48,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() -#include "utils.h" // Required for: GetExtension() +#include "utils.h" // Required for: IsFileExtension() #if defined(SUPPORT_FILEFORMAT_TTF) // Following libs are used on LoadTTF() @@ -287,7 +287,7 @@ SpriteFont LoadSpriteFont(const char *fileName) SpriteFont spriteFont = { 0 }; // Check file extension - if (strcmp(GetExtension(fileName),"rres") == 0) + if (IsFileExtension(fileName, ".rres")) { // TODO: Read multiple resource blocks from file (RRES_FONT_IMAGE, RRES_FONT_CHARDATA) RRES rres = LoadResource(fileName, 0); @@ -314,10 +314,10 @@ SpriteFont LoadSpriteFont(const char *fileName) //UnloadResource(rres[0]); } #if defined(SUPPORT_FILEFORMAT_TTF) - else if (strcmp(GetExtension(fileName),"ttf") == 0) spriteFont = LoadSpriteFontTTF(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); + else if (IsFileExtension(fileName, ".ttf")) spriteFont = LoadSpriteFontTTF(fileName, DEFAULT_TTF_FONTSIZE, 0, NULL); #endif #if defined(SUPPORT_FILEFORMAT_FNT) - else if (strcmp(GetExtension(fileName),"fnt") == 0) spriteFont = LoadBMFont(fileName); + else if (IsFileExtension(fileName, ".fnt")) spriteFont = LoadBMFont(fileName); #endif else { @@ -344,7 +344,7 @@ SpriteFont LoadSpriteFontTTF(const char *fileName, int fontSize, int charsCount, SpriteFont spriteFont = { 0 }; #if defined(SUPPORT_FILEFORMAT_TTF) - if (strcmp(GetExtension(fileName),"ttf") == 0) + if (IsFileExtension(fileName, ".ttf")) { if ((fontChars == NULL) || (charsCount == 0)) { diff --git a/src/textures.c b/src/textures.c index 6fff8e75..fff0e4e9 100644 --- a/src/textures.c +++ b/src/textures.c @@ -163,21 +163,32 @@ Image LoadImage(const char *fileName) image.mipmaps = 0; image.format = 0; - if ((strcmp(GetExtension(fileName),"png") == 0) + if (IsFileExtension(fileName, ".rres")) + { + RRES rres = LoadResource(fileName, 0); + + // NOTE: Parameters for RRES_TYPE_IMAGE are: width, height, format, mipmaps + + if (rres[0].type == RRES_TYPE_IMAGE) image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); + else TraceLog(WARNING, "[%s] Resource file does not contain image data", fileName); + + UnloadResource(rres); + } + else if ((IsFileExtension(fileName, ".png")) #if defined(SUPPORT_FILEFORMAT_BMP) - || (strcmp(GetExtension(fileName),"bmp") == 0) + || (IsFileExtension(fileName, ".bmp")) #endif #if defined(SUPPORT_FILEFORMAT_TGA) - || (strcmp(GetExtension(fileName),"tga") == 0) + || (IsFileExtension(fileName, ".tga")) #endif #if defined(SUPPORT_FILEFORMAT_JPG) - || (strcmp(GetExtension(fileName),"jpg") == 0) + || (IsFileExtension(fileName, ".jpg")) #endif #if defined(SUPPORT_FILEFORMAT_DDS) - || (strcmp(GetExtension(fileName),"gif") == 0) + || (IsFileExtension(fileName, ".gif")) #endif #if defined(SUPPORT_FILEFORMAT_PSD) - || (strcmp(GetExtension(fileName),"psd") == 0) + || (IsFileExtension(fileName, ".psd")) #endif ) { @@ -198,32 +209,21 @@ Image LoadImage(const char *fileName) else if (imgBpp == 4) image.format = UNCOMPRESSED_R8G8B8A8; } #if defined(SUPPORT_FILEFORMAT_DDS) - else if (strcmp(GetExtension(fileName),"dds") == 0) image = LoadDDS(fileName); + else if (IsFileExtension(fileName, ".dds")) image = LoadDDS(fileName); #endif #if defined(SUPPORT_FILEFORMAT_PKM) - else if (strcmp(GetExtension(fileName),"pkm") == 0) image = LoadPKM(fileName); + else if (IsFileExtension(fileName, ".pkm")) image = LoadPKM(fileName); #endif #if defined(SUPPORT_FILEFORMAT_KTX) - else if (strcmp(GetExtension(fileName),"ktx") == 0) image = LoadKTX(fileName); + else if (IsFileExtension(fileName, ".ktx")) image = LoadKTX(fileName); #endif #if defined(SUPPORT_FILEFORMAT_PVR) - else if (strcmp(GetExtension(fileName),"pvr") == 0) image = LoadPVR(fileName); + else if (IsFileExtension(fileName, ".pvr")) image = LoadPVR(fileName); #endif #if defined(SUPPORT_FILEFORMAT_ASTC) - else if (strcmp(GetExtension(fileName),"astc") == 0) image = LoadASTC(fileName); + else if (IsFileExtension(fileName, ".astc")) image = LoadASTC(fileName); #endif - else if (strcmp(GetExtension(fileName),"rres") == 0) - { - RRES rres = LoadResource(fileName, 0); - - // NOTE: Parameters for RRES_TYPE_IMAGE are: width, height, format, mipmaps - - if (rres[0].type == RRES_TYPE_IMAGE) image = LoadImagePro(rres[0].data, rres[0].param1, rres[0].param2, rres[0].param3); - else TraceLog(WARNING, "[%s] Resource file does not contain image data", fileName); - - UnloadResource(rres); - } - else TraceLog("[%s] Image fileformat not supported", fileName); + else TraceLog(WARNING, "[%s] Image fileformat not supported", fileName); if (image.data != NULL) TraceLog(INFO, "[%s] Image loaded successfully (%ix%i)", fileName, image.width, image.height); else TraceLog(WARNING, "[%s] Image could not be loaded", fileName); diff --git a/src/utils.c b/src/utils.c index 6a07f301..649fda4f 100644 --- a/src/utils.c +++ b/src/utils.c @@ -88,14 +88,15 @@ static int android_close(void *cookie); //---------------------------------------------------------------------------------- // Module Functions Definition - Utilities //---------------------------------------------------------------------------------- -// Outputs a trace log message + +// Output trace log messages void TraceLog(int msgType, const char *text, ...) { -#if !defined(NO_TRACELOG) +#if defined(SUPPORT_TRACELOG) static char buffer[128]; int traceDebugMsgs = 1; -#ifdef DO_NOT_TRACE_DEBUG_MSGS +#if defined(SUPPORT_TRACELOG_DEBUG) traceDebugMsgs = 0; #endif @@ -131,7 +132,7 @@ void TraceLog(int msgType, const char *text, ...) if (msgType == ERROR) exit(1); // If ERROR message, exit program -#endif // NO_TRACELOG +#endif // SUPPORT_TRACELOG } #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) @@ -163,19 +164,6 @@ void RecordMalloc(int mallocType, int mallocSize, const char *msg) } */ -bool IsFileExtension(const char *fileName, const char *ext) -{ - return (strcmp(GetExtension(fileName), ext) == 0); -} - -// Get the extension for a filename -const char *GetExtension(const char *fileName) -{ - const char *dot = strrchr(fileName, '.'); - if (!dot || dot == fileName) return ""; - return (dot + 1); -} - #if defined(PLATFORM_ANDROID) // Initialize asset manager from android app void InitAssetManager(AAssetManager *manager) diff --git a/src/utils.h b/src/utils.h index 45ffcf81..2b4d838b 100644 --- a/src/utils.h +++ b/src/utils.h @@ -60,8 +60,7 @@ extern "C" { // Prevents name mangling of functions //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message -const char *GetExtension(const char *fileName); // Returns extension of a filename +void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) #if defined(SUPPORT_SAVE_BMP) @@ -74,7 +73,7 @@ void SavePNG(const char *fileName, unsigned char *imgData, int width, int height #if defined(PLATFORM_ANDROID) void InitAssetManager(AAssetManager *manager); // Initialize asset manager from android app -FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() +FILE *android_fopen(const char *fileName, const char *mode); // Replacement for fopen() #endif #ifdef __cplusplus -- cgit v1.2.3 From d2d4b17633d623999eb2509ff24f741b5d669b35 Mon Sep 17 00:00:00 2001 From: Ray Date: Sat, 8 Apr 2017 00:16:03 +0200 Subject: Web: Support pointer lock --- src/core.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 9 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index b9ea9315..c73a9418 100644 --- a/src/core.c +++ b/src/core.c @@ -343,7 +343,9 @@ static int32_t AndroidInputCallback(struct android_app *app, AInputEvent *event) #if defined(PLATFORM_WEB) static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const EmscriptenFullscreenChangeEvent *e, void *userData); -static EM_BOOL EmscriptenInputCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); +static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData); +static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData); +static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData); static EM_BOOL EmscriptenGamepadCallback(int eventType, const EmscriptenGamepadEvent *gamepadEvent, void *userData); #endif @@ -398,16 +400,22 @@ void InitWindow(int width, int height, const char *title) #if defined(PLATFORM_WEB) emscripten_set_fullscreenchange_callback(0, 0, 1, EmscriptenFullscreenChangeCallback); - - // NOTE: Some code examples + + // Support keyboard events + emscripten_set_keypress_callback("#canvas", NULL, 1, EmscriptenKeyboardCallback); + + // Support mouse events + emscripten_set_click_callback("#canvas", NULL, 1, EmscriptenMouseCallback); + + // Support touch events + emscripten_set_touchstart_callback("#canvas", NULL, 1, EmscriptenTouchCallback); + emscripten_set_touchend_callback("#canvas", NULL, 1, EmscriptenTouchCallback); + emscripten_set_touchmove_callback("#canvas", NULL, 1, EmscriptenTouchCallback); + emscripten_set_touchcancel_callback("#canvas", NULL, 1, EmscriptenTouchCallback); //emscripten_set_touchstart_callback(0, NULL, 1, Emscripten_HandleTouch); //emscripten_set_touchend_callback("#canvas", data, 0, Emscripten_HandleTouch); - emscripten_set_touchstart_callback("#canvas", NULL, 1, EmscriptenInputCallback); - emscripten_set_touchend_callback("#canvas", NULL, 1, EmscriptenInputCallback); - emscripten_set_touchmove_callback("#canvas", NULL, 1, EmscriptenInputCallback); - emscripten_set_touchcancel_callback("#canvas", NULL, 1, EmscriptenInputCallback); - // Support gamepad (not provided by GLFW3 on emscripten) + // Support gamepad events (not provided by GLFW3 on emscripten) emscripten_set_gamepadconnected_callback(NULL, 1, EmscriptenGamepadCallback); emscripten_set_gamepaddisconnected_callback(NULL, 1, EmscriptenGamepadCallback); #endif @@ -2700,8 +2708,39 @@ static EM_BOOL EmscriptenFullscreenChangeCallback(int eventType, const Emscripte return 0; } +// Register keyboard input events +static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboardEvent *keyEvent, void *userData) +{ + if ((eventType == EMSCRIPTEN_EVENT_KEYPRESS) && (strcmp(keyEvent->code, "Escape") == 0)) + { + emscripten_exit_pointerlock(); + } + + return 0; +} + +// Register mouse input events +static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) +{ + if (eventType == EMSCRIPTEN_EVENT_CLICK) + { + EmscriptenPointerlockChangeEvent plce; + emscripten_get_pointerlock_status(&plce); + + if (!plce.isActive) emscripten_request_pointerlock(0, 1); + else + { + emscripten_exit_pointerlock(); + emscripten_get_pointerlock_status(&plce); + //if (plce.isActive) TraceLog(WARNING, "Pointer lock exit did not work!"); + } + } + + return 0; +} + // Register touch input events -static EM_BOOL EmscriptenInputCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData) +static EM_BOOL EmscriptenTouchCallback(int eventType, const EmscriptenTouchEvent *touchEvent, void *userData) { /* for (int i = 0; i < touchEvent->numTouches; i++) -- cgit v1.2.3 From 7e65c300b6927bff3fb9cfa84e98fd662941fc20 Mon Sep 17 00:00:00 2001 From: raysan5 Date: Sun, 16 Apr 2017 13:47:49 +0200 Subject: Make public TakeScreenshot() function --- src/core.c | 47 ++++++++++++++++++++++------------------------- src/raylib.h | 1 + 2 files changed, 23 insertions(+), 25 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index c73a9418..3f3bc6ea 100644 --- a/src/core.c +++ b/src/core.c @@ -316,9 +316,6 @@ static void PollInputEvents(void); // Register user events static void SwapBuffers(void); // Copy back buffer to front buffers static void LogoAnimation(void); // Plays raylib logo appearing animation static void SetupViewport(void); // Set viewport parameters -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) -static void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable -#endif #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) static void ErrorCallback(int error, const char *description); // GLFW3 Error Callback, runs on GLFW3 error @@ -1001,6 +998,28 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } +// Takes a screenshot and saves it in the same folder as executable +void TakeScreenshot(void) +{ +#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) + static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution + char buffer[20]; // Buffer to store file name + + unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); + + sprintf(buffer, "screenshot%03i.png", shotNum); + + // Save image as PNG + SavePNG(buffer, imgData, renderWidth, renderHeight, 4); + + free(imgData); + + shotNum++; + + TraceLog(INFO, "[%s] Screenshot taken #03i", buffer, shotNum); +#endif +} + // Check file extension bool IsFileExtension(const char *fileName, const char *ext) { @@ -2284,28 +2303,6 @@ static void SwapBuffers(void) #endif } -#if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) -// Takes a screenshot and saves it in the same folder as executable -static void TakeScreenshot(void) -{ - static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution - char buffer[20]; // Buffer to store file name - - unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); - - sprintf(buffer, "screenshot%03i.png", shotNum); - - // Save image as PNG - SavePNG(buffer, imgData, renderWidth, renderHeight, 4); - - free(imgData); - - shotNum++; - - TraceLog(INFO, "[%s] Screenshot taken!", buffer); -} -#endif - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) // GLFW3 Error Callback, runs on GLFW3 error static void ErrorCallback(int error, const char *description) diff --git a/src/raylib.h b/src/raylib.h index e8f301ec..b82ec342 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -690,6 +690,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags //RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window -- cgit v1.2.3 From ecfe31bf1d2647dc52b8e1584e4b7f022049e09b Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 21 Apr 2017 00:08:00 +0200 Subject: Make TraceLog() public to the API enum LogType could require some revision... --- src/audio.c | 2 +- src/core.c | 2 +- src/raylib.h | 28 ++++++++++++++++++++++++---- src/text.c | 2 +- src/textures.c | 2 +- src/utils.h | 4 ---- 6 files changed, 28 insertions(+), 12 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index 34be4789..9a7779f4 100644 --- a/src/audio.c +++ b/src/audio.c @@ -75,7 +75,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #else #include "raylib.h" - #include "utils.h" // Required for: fopen() Android mapping, TraceLog() + #include "utils.h" // Required for: fopen() Android mapping #endif #ifdef __APPLE__ diff --git a/src/core.c b/src/core.c index 3f3bc6ea..ee069d97 100644 --- a/src/core.c +++ b/src/core.c @@ -81,7 +81,7 @@ #include "raylib.h" #include "rlgl.h" // raylib OpenGL abstraction layer to OpenGL 1.1, 3.3+ or ES2 -#include "utils.h" // Required for: fopen() Android mapping, TraceLog() +#include "utils.h" // Required for: fopen() Android mapping #define RAYMATH_IMPLEMENTATION // Use raymath as a header-only library (includes implementation) #define RAYMATH_EXTERN_INLINE // Compile raymath functions as static inline (remember, it's a compiler hint) diff --git a/src/raylib.h b/src/raylib.h index b82ec342..286494c7 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -295,7 +295,7 @@ #define RAYWHITE CLITERAL{ 245, 245, 245, 255 } // My own White (raylib logo) //---------------------------------------------------------------------------------- -// Types and Structures Definition +// Structures Definition //---------------------------------------------------------------------------------- #ifndef __cplusplus // Boolean type @@ -516,6 +516,18 @@ typedef struct AudioStream { unsigned int buffers[2]; // OpenAL audio buffers (double buffering) } AudioStream; +//---------------------------------------------------------------------------------- +// Enumerators Definition +//---------------------------------------------------------------------------------- +// Trace log type +typedef enum { + INFO = 0, + WARNING, + ERROR, + DEBUG, + OTHER +} LogType; + // Texture formats // NOTE: Support depends on OpenGL version and platform typedef enum { @@ -552,10 +564,18 @@ typedef enum { } TextureFilterMode; // Texture parameters: wrap mode -typedef enum { WRAP_REPEAT = 0, WRAP_CLAMP, WRAP_MIRROR } TextureWrapMode; +typedef enum { + WRAP_REPEAT = 0, + WRAP_CLAMP, + WRAP_MIRROR +} TextureWrapMode; // Color blending modes (pre-defined) -typedef enum { BLEND_ALPHA = 0, BLEND_ADDITIVE, BLEND_MULTIPLIED } BlendMode; +typedef enum { + BLEND_ALPHA = 0, + BLEND_ADDITIVE, + BLEND_MULTIPLIED +} BlendMode; // Gestures type // NOTE: It could be used as flags to enable only some gestures @@ -689,7 +709,7 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags -//RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) +RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension diff --git a/src/text.c b/src/text.c index a057e347..ebc8b0ff 100644 --- a/src/text.c +++ b/src/text.c @@ -50,7 +50,7 @@ #include // Required for: va_list, va_start(), vfprintf(), va_end() #include // Required for: FILE, fopen(), fclose(), fscanf(), feof(), rewind(), fgets() -#include "utils.h" // Required for: IsFileExtension() +#include "utils.h" // Required for: fopen() Android mapping #if defined(SUPPORT_FILEFORMAT_TTF) // Following libs are used on LoadTTF() diff --git a/src/textures.c b/src/textures.c index af95f9dc..7013038d 100644 --- a/src/textures.c +++ b/src/textures.c @@ -65,7 +65,7 @@ // Required for: rlglLoadTexture() rlDeleteTextures(), // rlglGenerateMipmaps(), some funcs for DrawTexturePro() -#include "utils.h" // Required for: fopen() Android mapping, TraceLog() +#include "utils.h" // Required for: fopen() Android mapping // Support only desired texture formats on stb_image #if !defined(SUPPORT_FILEFORMAT_BMP) diff --git a/src/utils.h b/src/utils.h index 2b4d838b..64592c73 100644 --- a/src/utils.h +++ b/src/utils.h @@ -46,8 +46,6 @@ //---------------------------------------------------------------------------------- // Types and Structures Definition //---------------------------------------------------------------------------------- -typedef enum { INFO = 0, ERROR, WARNING, DEBUG, OTHER } TraceLogType; - #ifdef __cplusplus extern "C" { // Prevents name mangling of functions #endif @@ -60,8 +58,6 @@ extern "C" { // Prevents name mangling of functions //---------------------------------------------------------------------------------- // Module Functions Declaration //---------------------------------------------------------------------------------- -void TraceLog(int msgType, const char *text, ...); // Outputs a trace log message - #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) #if defined(SUPPORT_SAVE_BMP) void SaveBMP(const char *fileName, unsigned char *imgData, int width, int height, int compSize); -- cgit v1.2.3 From 86f2d4b9f9df7514e3f15d8f2a5e92db6ac3c0ba Mon Sep 17 00:00:00 2001 From: Ray Date: Fri, 28 Apr 2017 00:29:50 +0200 Subject: Commented pointer lock on web --- src/core.c | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index ee069d97..1bad2369 100644 --- a/src/core.c +++ b/src/core.c @@ -2719,6 +2719,8 @@ static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboar // Register mouse input events static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) { + /* + // Lock mouse pointer when click on screen if (eventType == EMSCRIPTEN_EVENT_CLICK) { EmscriptenPointerlockChangeEvent plce; @@ -2732,6 +2734,7 @@ static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent //if (plce.isActive) TraceLog(WARNING, "Pointer lock exit did not work!"); } } + */ return 0; } -- cgit v1.2.3 From e197665e1dc3ec895b14b901884fee058dc1b4e9 Mon Sep 17 00:00:00 2001 From: victorfisac Date: Tue, 2 May 2017 15:04:32 +0200 Subject: Added function to set window minimum dimensions... useful when using FLAG_WINDOW_RESIZABLE. --- src/core.c | 9 +++++++++ src/raylib.h | 1 + 2 files changed, 10 insertions(+) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 1bad2369..d7cf1f79 100644 --- a/src/core.c +++ b/src/core.c @@ -629,6 +629,15 @@ void SetWindowMonitor(int monitor) #endif } +// Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +void SetWindowMinSize(int width, int height) +{ +#if defined(PLATFORM_DESKTOP) + const GLFWvidmode *mode = glfwGetVideoMode(glfwGetPrimaryMonitor()); + glfwSetWindowSizeLimits(window, width, height, mode->width, mode->height); +#endif +} + // Get current screen width int GetScreenWidth(void) { diff --git a/src/raylib.h b/src/raylib.h index 6f510f9f..3107661f 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -667,6 +667,7 @@ RLAPI void ToggleFullscreen(void); // Fullscreen RLAPI void SetWindowIcon(Image image); // Set icon for window (only PLATFORM_DESKTOP) RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window (fullscreen mode) +RLAPI void SetWindowMinSize(int width, int height); // Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) RLAPI int GetScreenWidth(void); // Get current screen width RLAPI int GetScreenHeight(void); // Get current screen height -- cgit v1.2.3 From 39732d04ec8ce71cde457ec3a89b3b5aca578e8d Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 May 2017 00:55:26 +0200 Subject: Comments review --- src/core.c | 5 ++--- src/rlgl.h | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index d7cf1f79..1241b3c1 100644 --- a/src/core.c +++ b/src/core.c @@ -5,11 +5,10 @@ * PLATFORMS SUPPORTED: * - Windows (win32/Win64) * - Linux (tested on Ubuntu) -* - Mac (OSX) -* - Android (API Level 9 or greater) +* - OSX (Mac) +* - Android (ARM or ARM64) * - Raspberry Pi (Raspbian) * - HTML5 (Chrome, Firefox) -* - Oculus Rift CV1 * * CONFIGURATION: * diff --git a/src/rlgl.h b/src/rlgl.h index 8358efb8..300949f9 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -37,7 +37,7 @@ * * LICENSE: zlib/libpng * -* Copyright (c) 2014-2016 Ramon Santamaria (@raysan5) +* Copyright (c) 2014-2017 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. -- cgit v1.2.3 From 83aba22e494ffbc78cb9cda6a8e39e82963026f4 Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 May 2017 02:37:37 +0200 Subject: Improved hi-res timer on Win32 --- src/core.c | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 1241b3c1..459b99fb 100644 --- a/src/core.c +++ b/src/core.c @@ -41,6 +41,9 @@ * #define SUPPORT_MOUSE_GESTURES * Mouse gestures are directly mapped like touches and processed by gestures system. * +* #define SUPPORT_BUSY_WAIT_LOOP +* Use busy wait loop for timming sync, if not defined, a high-resolution timer is setup and used +* * DEPENDENCIES: * GLFW3 - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX) * raymath - 3D math functionality (Vector3, Matrix, Quaternion) @@ -75,6 +78,7 @@ #define SUPPORT_MOUSE_GESTURES #define SUPPORT_CAMERA_SYSTEM #define SUPPORT_GESTURES_SYSTEM +#define SUPPORT_BUSY_WAIT_LOOP //------------------------------------------------- #include "raylib.h" @@ -104,9 +108,9 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes -#if defined __linux__ || defined(PLATFORM_WEB) +#if defined(__linux__) || defined(PLATFORM_WEB) #include // Required for: timespec, nanosleep(), select() - POSIX -#elif defined __APPLE__ +#elif defined(__APPLE__) #include // Required for: usleep() #endif @@ -114,13 +118,19 @@ //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 #include // GLFW3 library: Windows, OpenGL context and Input management - #ifdef __linux__ + #ifdef(__linux__) #define GLFW_EXPOSE_NATIVE_X11 // Linux specific definitions for getting #define GLFW_EXPOSE_NATIVE_GLX // native functions like glfwGetX11Window #include // which are required for hiding mouse #endif //#include // OpenGL functions (GLFW3 already includes gl.h) //#define GLFW_DLL // Using GLFW DLL on Windows -> No, we use static version! + + #if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) + // NOTE: Those functions require linking with winmm library + __stdcall unsigned int timeBeginPeriod(unsigned int uPeriod); + __stdcall unsigned int timeEndPeriod(unsigned int uPeriod); + #endif #endif #if defined(PLATFORM_ANDROID) @@ -506,6 +516,10 @@ void CloseWindow(void) glfwTerminate(); #endif +#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) + timeEndPeriod(1); // Restore time period +#endif + #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) // Close surface, context and display if (display != EGL_NO_DISPLAY) @@ -2042,6 +2056,10 @@ static void SetupFramebufferSize(int displayWidth, int displayHeight) static void InitTimer(void) { srand(time(NULL)); // Initialize random seed + +#if !defined(SUPPORT_BUSY_WAIT_LOOP) && defined(_WIN32) + timeBeginPeriod(1); // Setup high-resolution timer to 1ms (granularity of 1-2 ms) +#endif #if defined(PLATFORM_ANDROID) || defined(PLATFORM_RPI) struct timespec now; @@ -2078,7 +2096,6 @@ static double GetTime(void) // http://stackoverflow.com/questions/43057578/c-programming-win32-games-sleep-taking-longer-than-expected static void Wait(float ms) { -#define SUPPORT_BUSY_WAIT_LOOP #if defined(SUPPORT_BUSY_WAIT_LOOP) double prevTime = GetTime(); double nextTime = 0.0; @@ -2086,9 +2103,9 @@ static void Wait(float ms) // Busy wait loop while ((nextTime - prevTime) < ms/1000.0f) nextTime = GetTime(); #else - #if defined _WIN32 + #if defined(_WIN32) Sleep((unsigned int)ms); - #elif defined __linux__ || defined(PLATFORM_WEB) + #elif defined(__linux__) || defined(PLATFORM_WEB) struct timespec req = { 0 }; time_t sec = (int)(ms/1000.0f); ms -= (sec*1000); @@ -2097,7 +2114,7 @@ static void Wait(float ms) // NOTE: Use nanosleep() on Unix platforms... usleep() it's deprecated. while (nanosleep(&req, &req) == -1) continue; - #elif defined __APPLE__ + #elif defined(__APPLE__) usleep(ms*1000.0f); #endif #endif -- cgit v1.2.3 From 822c2ddad59e9839aeb029f5a3dc26681188612b Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 May 2017 02:47:44 +0200 Subject: Some defines tweaks for consistency --- src/audio.c | 4 ++-- src/core.c | 12 ++++++------ src/rlgl.c | 18 +++++++----------- src/rlgl.h | 8 +++----- 4 files changed, 18 insertions(+), 24 deletions(-) (limited to 'src/core.c') diff --git a/src/audio.c b/src/audio.c index 2393e5a4..39befbbc 100644 --- a/src/audio.c +++ b/src/audio.c @@ -79,7 +79,7 @@ #include "utils.h" // Required for: fopen() Android mapping #endif -#ifdef __APPLE__ +#if defined(__APPLE__) #include "OpenAL/al.h" // OpenAL basic header #include "OpenAL/alc.h" // OpenAL context header (like OpenGL, OpenAL requires a context to work) #else @@ -1326,7 +1326,7 @@ void TraceLog(int msgType, const char *text, ...) va_list args; int traceDebugMsgs = 0; -#ifdef DO_NOT_TRACE_DEBUG_MSGS +#if defined(DO_NOT_TRACE_DEBUG_MSGS) traceDebugMsgs = 0; #endif diff --git a/src/core.c b/src/core.c index 459b99fb..1448743f 100644 --- a/src/core.c +++ b/src/core.c @@ -118,7 +118,7 @@ //#define GLFW_INCLUDE_NONE // Disable the standard OpenGL header inclusion on GLFW3 #include // GLFW3 library: Windows, OpenGL context and Input management - #ifdef(__linux__) + #if defined(__linux__) #define GLFW_EXPOSE_NATIVE_X11 // Linux specific definitions for getting #define GLFW_EXPOSE_NATIVE_GLX // native functions like glfwGetX11Window #include // which are required for hiding mouse @@ -668,7 +668,7 @@ int GetScreenHeight(void) void ShowCursor() { #if defined(PLATFORM_DESKTOP) - #ifdef __linux__ + #if defined(__linux__) XUndefineCursor(glfwGetX11Display(), glfwGetX11Window(window)); #else glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); @@ -681,7 +681,7 @@ void ShowCursor() void HideCursor() { #if defined(PLATFORM_DESKTOP) - #ifdef __linux__ + #if defined(__linux__) XColor col; const char nil[] = {0}; @@ -1679,7 +1679,7 @@ static void InitGraphicsDevice(int width, int height) glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); // Choose OpenGL minor version (just hint) glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Profiles Hint: Only 3.3 and above! // Other values: GLFW_OPENGL_ANY_PROFILE, GLFW_OPENGL_COMPAT_PROFILE -#ifdef __APPLE__ +#if defined(__APPLE__) glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // OSX Requires #else glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_FALSE); // Fordward Compatibility Hint: Only 3.3 and above! @@ -1964,7 +1964,7 @@ static void InitGraphicsDevice(int width, int height) // Set viewport parameters static void SetupViewport(void) { -#ifdef __APPLE__ +#if defined(__APPLE__) // Get framebuffer size of current window // NOTE: Required to handle HighDPI display correctly on OSX because framebuffer // is automatically reasized to adapt to new DPI. @@ -3279,7 +3279,7 @@ static void *GamepadThread(void *arg) // Plays raylib logo appearing animation static void LogoAnimation(void) { -#ifndef PLATFORM_WEB +#if !defined(PLATFORM_WEB) int logoPositionX = screenWidth/2 - 128; int logoPositionY = screenHeight/2 - 128; diff --git a/src/rlgl.c b/src/rlgl.c index 1dc83314..edf9e60b 100644 --- a/src/rlgl.c +++ b/src/rlgl.c @@ -67,12 +67,12 @@ #include // Required for: strcmp(), strlen(), strtok() [Used only in extensions loading] #include // Required for: atan2() -#ifndef RLGL_STANDALONE +#if !defined(RLGL_STANDALONE) #include "raymath.h" // Required for: Vector3 and Matrix functions #endif #if defined(GRAPHICS_API_OPENGL_11) - #ifdef __APPLE__ + #if defined(__APPLE__) #include // OpenGL 1.1 library for OSX #else #include // OpenGL 1.1 library @@ -84,7 +84,7 @@ #endif #if defined(GRAPHICS_API_OPENGL_33) - #ifdef __APPLE__ + #if defined(__APPLE__) #include // OpenGL 3 library for OSX #else #define GLAD_IMPLEMENTATION @@ -1286,21 +1286,17 @@ void rlglLoadExtensions(void *loader) { #if defined(GRAPHICS_API_OPENGL_21) || defined(GRAPHICS_API_OPENGL_33) // NOTE: glad is generated and contains only required OpenGL 3.3 Core extensions (and lower versions) - #ifndef __APPLE__ + #if !defined(__APPLE__) if (!gladLoadGLLoader((GLADloadproc)loader)) TraceLog(WARNING, "GLAD: Cannot load OpenGL extensions"); else TraceLog(INFO, "GLAD: OpenGL extensions loaded successfully"); - #endif -#if defined(GRAPHICS_API_OPENGL_21) - #ifndef __APPLE__ + #if defined(GRAPHICS_API_OPENGL_21) if (GLAD_GL_VERSION_2_1) TraceLog(INFO, "OpenGL 2.1 profile supported"); - #endif -#elif defined(GRAPHICS_API_OPENGL_33) - #ifndef __APPLE__ + #elif defined(GRAPHICS_API_OPENGL_33) if(GLAD_GL_VERSION_3_3) TraceLog(INFO, "OpenGL 3.3 Core profile supported"); else TraceLog(ERROR, "OpenGL 3.3 Core profile not supported"); + #endif #endif -#endif // With GLAD, we can check if an extension is supported using the GLAD_GL_xxx booleans //if (GLAD_GL_ARB_vertex_array_object) // Use GL_ARB_vertex_array_object diff --git a/src/rlgl.h b/src/rlgl.h index 300949f9..b51d1c49 100644 --- a/src/rlgl.h +++ b/src/rlgl.h @@ -59,12 +59,10 @@ #ifndef RLGL_H #define RLGL_H -#ifndef RLGL_STANDALONE - #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() -#endif - -#ifdef RLGL_STANDALONE +#if defined(RLGL_STANDALONE) #define RAYMATH_STANDALONE +#else + #include "raylib.h" // Required for: Model, Shader, Texture2D, TraceLog() #endif #include "raymath.h" // Required for: Vector3, Matrix -- cgit v1.2.3 From fd1fe3ac14adbd4bdc8ed409a65aad9d7d7133ca Mon Sep 17 00:00:00 2001 From: Ray Date: Mon, 8 May 2017 21:03:48 +0200 Subject: Lock cursor on first person camera --- src/camera.h | 52 +++++++++++++++------------------------------------- src/core.c | 21 ++++++++++++++++----- 2 files changed, 31 insertions(+), 42 deletions(-) (limited to 'src/core.c') diff --git a/src/camera.h b/src/camera.h index e1b00ac2..e4aa8478 100644 --- a/src/camera.h +++ b/src/camera.h @@ -203,15 +203,14 @@ static int cameraMode = CAMERA_CUSTOM; // Current camera mode #if defined(CAMERA_STANDALONE) // NOTE: Camera controls depend on some raylib input functions // TODO: Set your own input functions (used in UpdateCamera()) -static Vector2 GetMousePosition() { return (Vector2){ 0.0f, 0.0f }; } -static void SetMousePosition(Vector2 pos) {} +static void EnableCursor() {} // Unlock cursor +static void DisableCursor() {} // Lock cursor + +static int IsKeyDown(int key) { return 0; } + static int IsMouseButtonDown(int button) { return 0;} static int GetMouseWheelMove() { return 0; } -static int GetScreenWidth() { return 1280; } -static int GetScreenHeight() { return 720; } -static void ShowCursor() {} -static void HideCursor() {} -static int IsKeyDown(int key) { return 0; } +static Vector2 GetMousePosition() { return (Vector2){ 0.0f, 0.0f }; } #endif //---------------------------------------------------------------------------------- @@ -246,14 +245,19 @@ void SetCameraMode(Camera camera, int mode) //cameraAngle.y = -60.0f*DEG2RAD; // Camera angle in plane XY (0 aligned with X, move positive CW) playerEyesPosition = camera.position.y; + + // Lock cursor for first person and third person cameras + if ((mode == CAMERA_FIRST_PERSON) || + (mode == CAMERA_THIRD_PERSON)) DisableCursor(); + else EnableCursor(); cameraMode = mode; } // Update camera depending on selected mode // NOTE: Camera controls depend on some raylib functions: +// System: EnableCursor(), DisableCursor() // Mouse: GetMousePosition(), SetMousePosition(), IsMouseButtonDown(), GetMouseWheelMove() -// System: GetScreenWidth(), GetScreenHeight(), ShowCursor(), HideCursor() // Keys: IsKeyDown() // TODO: Port to quaternion-based camera void UpdateCamera(Camera *camera) @@ -284,36 +288,10 @@ void UpdateCamera(Camera *camera) if (cameraMode != CAMERA_CUSTOM) { - // Get screen size - int screenWidth = GetScreenWidth(); - int screenHeight = GetScreenHeight(); - - if ((cameraMode == CAMERA_FIRST_PERSON) || - (cameraMode == CAMERA_THIRD_PERSON)) - { - HideCursor(); - - if (mousePosition.x < (float)screenHeight/3.0f) SetMousePosition((Vector2){ screenWidth - screenHeight/3, mousePosition.y }); - else if (mousePosition.y < (float)screenHeight/3.0f) SetMousePosition((Vector2){ mousePosition.x, screenHeight - screenHeight/3 }); - else if (mousePosition.x > (screenWidth - (float)screenHeight/3.0f)) SetMousePosition((Vector2){ screenHeight/3, mousePosition.y }); - else if (mousePosition.y > (screenHeight - (float)screenHeight/3.0f)) SetMousePosition((Vector2){ mousePosition.x, screenHeight/3 }); - else - { - mousePositionDelta.x = mousePosition.x - previousMousePosition.x; - mousePositionDelta.y = mousePosition.y - previousMousePosition.y; - } - } - else // CAMERA_FREE, CAMERA_ORBITAL - { - ShowCursor(); - - mousePositionDelta.x = mousePosition.x - previousMousePosition.x; - mousePositionDelta.y = mousePosition.y - previousMousePosition.y; - } + mousePositionDelta.x = mousePosition.x - previousMousePosition.x; + mousePositionDelta.y = mousePosition.y - previousMousePosition.y; - // NOTE: We GetMousePosition() again because it can be modified by a previous SetMousePosition() call - // If using directly mousePosition variable we have problems on CAMERA_FIRST_PERSON and CAMERA_THIRD_PERSON - previousMousePosition = GetMousePosition(); + previousMousePosition = mousePosition; } // Support for multiple automatic camera modes diff --git a/src/core.c b/src/core.c index 1448743f..508049c9 100644 --- a/src/core.c +++ b/src/core.c @@ -286,6 +286,10 @@ static int gamepadAxisCount = 0; // Register number of available game static Vector2 mousePosition; // Mouse position on screen +#if defined(PLATFORM_WEB) +static bool toggleCursorLock = false; // Ask for cursor pointer lock on next click +#endif + #if defined(SUPPORT_GESTURES_SYSTEM) static Vector2 touchPosition[MAX_TOUCH_POINTS]; // Touch position on screen #endif @@ -708,6 +712,9 @@ void EnableCursor() { #if defined(PLATFORM_DESKTOP) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); +#endif +#if defined(PLATFORM_WEB) + toggleCursorLock = true; #endif cursorHidden = false; } @@ -717,6 +724,9 @@ void DisableCursor() { #if defined(PLATFORM_DESKTOP) glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); +#endif +#if defined(PLATFORM_WEB) + toggleCursorLock = true; #endif cursorHidden = true; } @@ -1821,12 +1831,13 @@ static void InitGraphicsDevice(int width, int height) const EGLint framebufferAttribs[] = { - EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // Type of context support -> Required on RPI? - //EGL_SURFACE_TYPE, EGL_WINDOW_BIT, // Don't use it on Android! + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, // Type of context support -> Required on RPI? + //EGL_SURFACE_TYPE, EGL_WINDOW_BIT, // Don't use it on Android! EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5) EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6) EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5) //EGL_ALPHA_SIZE, 8, // ALPHA bit depth + //EGL_TRANSPARENT_TYPE, EGL_TRANSPARENT_RGB, // Request transparent framebuffer EGL_DEPTH_SIZE, 16, // Depth buffer size (Required to use Depth testing!) //EGL_STENCIL_SIZE, 8, // Stencil buffer size EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA @@ -2744,9 +2755,8 @@ static EM_BOOL EmscriptenKeyboardCallback(int eventType, const EmscriptenKeyboar // Register mouse input events static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent *mouseEvent, void *userData) { - /* // Lock mouse pointer when click on screen - if (eventType == EMSCRIPTEN_EVENT_CLICK) + if ((eventType == EMSCRIPTEN_EVENT_CLICK) && toggleCursorLock) { EmscriptenPointerlockChangeEvent plce; emscripten_get_pointerlock_status(&plce); @@ -2758,8 +2768,9 @@ static EM_BOOL EmscriptenMouseCallback(int eventType, const EmscriptenMouseEvent emscripten_get_pointerlock_status(&plce); //if (plce.isActive) TraceLog(WARNING, "Pointer lock exit did not work!"); } + + toggleCursorLock = false; } - */ return 0; } -- cgit v1.2.3 From 321027a242e287e00ac0884387113db4b09ea065 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 9 May 2017 18:11:02 +0200 Subject: Added comments to create transparent framebuffer Comments to create transparent framebuffer on RPI, when activate you see though full screen window the console below! --- src/core.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 508049c9..08f3a71d 100644 --- a/src/core.c +++ b/src/core.c @@ -1836,8 +1836,8 @@ static void InitGraphicsDevice(int width, int height) EGL_RED_SIZE, 8, // RED color bit depth (alternative: 5) EGL_GREEN_SIZE, 8, // GREEN color bit depth (alternative: 6) EGL_BLUE_SIZE, 8, // BLUE color bit depth (alternative: 5) - //EGL_ALPHA_SIZE, 8, // ALPHA bit depth - //EGL_TRANSPARENT_TYPE, EGL_TRANSPARENT_RGB, // Request transparent framebuffer + //EGL_ALPHA_SIZE, 8, // ALPHA bit depth (required for transparent framebuffer) + //EGL_TRANSPARENT_TYPE, EGL_NONE, // Request transparent framebuffer (EGL_TRANSPARENT_RGB does not work on RPI) EGL_DEPTH_SIZE, 16, // Depth buffer size (Required to use Depth testing!) //EGL_STENCIL_SIZE, 8, // Stencil buffer size EGL_SAMPLE_BUFFERS, sampleBuffer, // Activate MSAA @@ -1912,7 +1912,7 @@ static void InitGraphicsDevice(int width, int height) VC_DISPMANX_ALPHA_T alpha; alpha.flags = DISPMANX_FLAGS_ALPHA_FIXED_ALL_PIXELS; - alpha.opacity = 255; + alpha.opacity = 255; // Set transparency level for framebuffer, requires EGLAttrib: EGL_TRANSPARENT_TYPE alpha.mask = 0; dispmanDisplay = vc_dispmanx_display_open(0); // LCD -- cgit v1.2.3 From bac50fbba5940de6e536157243f3e4ec3dee9d98 Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 9 May 2017 22:03:46 +0200 Subject: Review functions descriptions --- src/core.c | 261 ++++++++++++++++++++++++++++++----------------------------- src/raylib.h | 48 +++++------ 2 files changed, 155 insertions(+), 154 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index 08f3a71d..cca8a1ac 100644 --- a/src/core.c +++ b/src/core.c @@ -380,7 +380,7 @@ static void *GamepadThread(void *arg); // Mouse reading thread // Module Functions Definition - Window and OpenGL Context Functions //---------------------------------------------------------------------------------- #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -// Initialize Window and Graphics Context (OpenGL) +// Initialize window and OpenGL context void InitWindow(int width, int height, const char *title) { TraceLog(INFO, "Initializing raylib (v1.7.0)"); @@ -443,7 +443,7 @@ void InitWindow(int width, int height, const char *title) #endif #if defined(PLATFORM_ANDROID) -// Android activity initialization +// Initialize Android activity void InitWindow(int width, int height, void *state) { TraceLog(INFO, "Initializing raylib (v1.7.0)"); @@ -506,7 +506,7 @@ void InitWindow(int width, int height, void *state) } #endif -// Close Window and Terminate Context +// Close window and unload OpenGL context void CloseWindow(void) { #if defined(SUPPORT_DEFAULT_FONT) @@ -562,7 +562,7 @@ void CloseWindow(void) TraceLog(INFO, "Window closed successfully"); } -// Detect if KEY_ESCAPE pressed or Close icon pressed +// Check if KEY_ESCAPE pressed or Close icon pressed bool WindowShouldClose(void) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) @@ -577,7 +577,7 @@ bool WindowShouldClose(void) #endif } -// Detect if window has been minimized (or lost focus) +// Check if window has been minimized (or lost focus) bool IsWindowMinimized(void) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_WEB) @@ -587,7 +587,7 @@ bool IsWindowMinimized(void) #endif } -// Fullscreen toggle (only PLATFORM_DESKTOP) +// Toggle fullscreen mode (only PLATFORM_DESKTOP) void ToggleFullscreen(void) { #if defined(PLATFORM_DESKTOP) @@ -646,7 +646,7 @@ void SetWindowMonitor(int monitor) #endif } -// Set window minimum dimensions (for FLAG_WINDOW_RESIZABLE) +// Set window minimum dimensions (FLAG_WINDOW_RESIZABLE) void SetWindowMinSize(int width, int height) { #if defined(PLATFORM_DESKTOP) @@ -681,7 +681,7 @@ void ShowCursor() cursorHidden = false; } -// Hide mouse cursor +// Hides mouse cursor void HideCursor() { #if defined(PLATFORM_DESKTOP) @@ -701,13 +701,13 @@ void HideCursor() cursorHidden = true; } -// Check if mouse cursor is hidden +// Check if cursor is not visible bool IsCursorHidden() { return cursorHidden; } -// Enable mouse cursor +// Enables cursor (unlock cursor) void EnableCursor() { #if defined(PLATFORM_DESKTOP) @@ -719,7 +719,7 @@ void EnableCursor() cursorHidden = false; } -// Disable mouse cursor +// Disables cursor (lock cursor) void DisableCursor() { #if defined(PLATFORM_DESKTOP) @@ -732,14 +732,14 @@ void DisableCursor() } #endif // !defined(PLATFORM_ANDROID) -// Sets Background Color +// Set background color (framebuffer clear color) void ClearBackground(Color color) { // Clear full framebuffer (not only render area) to color rlClearColor(color.r, color.g, color.b, color.a); } -// Setup drawing canvas to start drawing +// Setup canvas (framebuffer) to start drawing void BeginDrawing(void) { currentTime = GetTime(); // Number of elapsed seconds since InitTimer() was called @@ -754,7 +754,7 @@ void BeginDrawing(void) // NOTE: Not required with OpenGL 3.3+ } -// End canvas drawing and Swap Buffers (Double Buffering) +// End canvas drawing and swap buffers (double buffering) void EndDrawing(void) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -782,7 +782,7 @@ void EndDrawing(void) } } -// Initialize 2D mode with custom camera +// Initialize 2D mode with custom camera (2D) void Begin2dMode(Camera2D camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -800,7 +800,7 @@ void Begin2dMode(Camera2D camera) rlMultMatrixf(MatrixToFloat(matTransform)); } -// Ends 2D mode custom camera usage +// Ends 2D mode with custom camera void End2dMode(void) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -808,7 +808,7 @@ void End2dMode(void) rlLoadIdentity(); // Reset current matrix (MODELVIEW) } -// Initializes 3D mode for drawing (Camera setup) +// Initializes 3D mode with custom camera (3D) void Begin3dMode(Camera camera) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) @@ -897,7 +897,107 @@ void EndTextureMode(void) rlLoadIdentity(); // Reset current matrix (MODELVIEW) } -// Set target FPS for the game +// Returns a ray trace from mouse position +Ray GetMouseRay(Vector2 mousePosition, Camera camera) +{ + Ray ray; + + // Calculate normalized device coordinates + // NOTE: y value is negative + float x = (2.0f*mousePosition.x)/(float)GetScreenWidth() - 1.0f; + float y = 1.0f - (2.0f*mousePosition.y)/(float)GetScreenHeight(); + float z = 1.0f; + + // Store values in a vector + Vector3 deviceCoords = { x, y, z }; + + TraceLog(DEBUG, "Device coordinates: (%f, %f, %f)", deviceCoords.x, deviceCoords.y, deviceCoords.z); + + // Calculate projection matrix (from perspective instead of frustum) + Matrix matProj = MatrixPerspective(camera.fovy, ((double)GetScreenWidth()/(double)GetScreenHeight()), 0.01, 1000.0); + + // Calculate view matrix from camera look at + Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); + + // Do I need to transpose it? It seems that yes... + // NOTE: matrix order may be incorrect... In OpenGL to get world position from + // camera view it just needs to get inverted, but here we need to transpose it too. + // For example, if you get view matrix, transpose and inverted and you transform it + // to a vector, you will get its 3d world position coordinates (camera.position). + // If you don't transpose, final position will be wrong. + MatrixTranspose(&matView); + +//#define USE_RLGL_UNPROJECT +#if defined(USE_RLGL_UNPROJECT) // OPTION 1: Use rlglUnproject() + + Vector3 nearPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); + Vector3 farPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); + +#else // OPTION 2: Compute unprojection directly here + + // Calculate unproject matrix (multiply projection matrix and view matrix) and invert it + Matrix matProjView = MatrixMultiply(matProj, matView); + MatrixInvert(&matProjView); + + // Calculate far and near points + Quaternion qNear = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; + Quaternion qFar = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; + + // Multiply points by unproject matrix + QuaternionTransform(&qNear, matProjView); + QuaternionTransform(&qFar, matProjView); + + // Calculate normalized world points in vectors + Vector3 nearPoint = { qNear.x/qNear.w, qNear.y/qNear.w, qNear.z/qNear.w}; + Vector3 farPoint = { qFar.x/qFar.w, qFar.y/qFar.w, qFar.z/qFar.w}; +#endif + + // Calculate normalized direction vector + Vector3 direction = VectorSubtract(farPoint, nearPoint); + VectorNormalize(&direction); + + // Apply calculated vectors to ray + ray.position = camera.position; + ray.direction = direction; + + return ray; +} + +// Returns the screen space position from a 3d world space position +Vector2 GetWorldToScreen(Vector3 position, Camera camera) +{ + // Calculate projection matrix (from perspective instead of frustum + Matrix matProj = MatrixPerspective(camera.fovy, (double)GetScreenWidth()/(double)GetScreenHeight(), 0.01, 1000.0); + + // Calculate view matrix from camera look at (and transpose it) + Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); + MatrixTranspose(&matView); + + // Convert world position vector to quaternion + Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; + + // Transform world position to view + QuaternionTransform(&worldPos, matView); + + // Transform result to projection (clip space position) + QuaternionTransform(&worldPos, matProj); + + // Calculate normalized device coordinates (inverted y) + Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w }; + + // Calculate 2d screen position vector + Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)GetScreenWidth(), (ndcPos.y + 1.0f)/2.0f*(float)GetScreenHeight() }; + + return screenPosition; +} + +// Get transform matrix for camera +Matrix GetCameraMatrix(Camera camera) +{ + return MatrixLookAt(camera.position, camera.target, camera.up); +} + +// Set target FPS (maximum) void SetTargetFPS(int fps) { if (fps < 1) targetTime = 0.0; @@ -912,7 +1012,7 @@ int GetFPS(void) return (int)(1.0f/GetFrameTime()); } -// Returns time in seconds for one frame +// Returns time in seconds for last frame drawn float GetFrameTime(void) { // NOTE: We round value to milliseconds @@ -944,7 +1044,6 @@ float *VectorToFloat(Vector3 vec) return buffer; } -// Converts Matrix to float array // NOTE: Returned vector is a transposed version of the Matrix struct, // it should be this way because, despite raymath use OpenGL column-major convention, // Matrix struct memory alignment and variables naming are not coherent @@ -1004,7 +1103,7 @@ int GetRandomValue(int min, int max) return (rand()%(abs(max-min)+1) + min); } -// Fades color by a percentadge +// Color fade-in or fade-out, alpha goes from 0.0f to 1.0f Color Fade(Color color, float alpha) { if (alpha < 0.0f) alpha = 0.0f; @@ -1015,13 +1114,13 @@ Color Fade(Color color, float alpha) return (Color){color.r, color.g, color.b, (unsigned char)colorAlpha}; } -// Activates raylib logo at startup +// Activate raylib logo at startup (can be done with flags) void ShowLogo(void) { showLogo = true; } -// Enable some window/system configurations +// Setup window configuration flags (view FLAGS) void SetConfigFlags(char flags) { configFlags = flags; @@ -1030,6 +1129,8 @@ void SetConfigFlags(char flags) if (configFlags & FLAG_FULLSCREEN_MODE) fullscreen = true; } +// NOTE TraceLog() function is located in [utils.h] + // Takes a screenshot and saves it in the same folder as executable void TakeScreenshot(void) { @@ -1067,14 +1168,14 @@ bool IsFileExtension(const char *fileName, const char *ext) } #if defined(PLATFORM_DESKTOP) -// Check if a file have been dropped into window +// Check if a file has been dropped into window bool IsFileDropped(void) { if (dropFilesCount > 0) return true; else return false; } -// Retrieve dropped files into window +// Get dropped files names char **GetDroppedFiles(int *count) { *count = dropFilesCount; @@ -1095,7 +1196,7 @@ void ClearDroppedFiles(void) } #endif -// Storage save integer value (to defined position) +// Save integer value to storage file (to defined position) // NOTE: Storage positions is directly related to file memory layout (4 bytes each integer) void StorageSaveValue(int position, int value) { @@ -1135,7 +1236,7 @@ void StorageSaveValue(int position, int value) } } -// Storage load integer value (from defined position) +// Load integer value from storage file (from defined position) // NOTE: If requested position could not be found, value 0 is returned int StorageLoadValue(int position) { @@ -1174,106 +1275,6 @@ int StorageLoadValue(int position) return value; } -// Returns a ray trace from mouse position -Ray GetMouseRay(Vector2 mousePosition, Camera camera) -{ - Ray ray; - - // Calculate normalized device coordinates - // NOTE: y value is negative - float x = (2.0f*mousePosition.x)/(float)GetScreenWidth() - 1.0f; - float y = 1.0f - (2.0f*mousePosition.y)/(float)GetScreenHeight(); - float z = 1.0f; - - // Store values in a vector - Vector3 deviceCoords = { x, y, z }; - - TraceLog(DEBUG, "Device coordinates: (%f, %f, %f)", deviceCoords.x, deviceCoords.y, deviceCoords.z); - - // Calculate projection matrix (from perspective instead of frustum) - Matrix matProj = MatrixPerspective(camera.fovy, ((double)GetScreenWidth()/(double)GetScreenHeight()), 0.01, 1000.0); - - // Calculate view matrix from camera look at - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - - // Do I need to transpose it? It seems that yes... - // NOTE: matrix order may be incorrect... In OpenGL to get world position from - // camera view it just needs to get inverted, but here we need to transpose it too. - // For example, if you get view matrix, transpose and inverted and you transform it - // to a vector, you will get its 3d world position coordinates (camera.position). - // If you don't transpose, final position will be wrong. - MatrixTranspose(&matView); - -//#define USE_RLGL_UNPROJECT -#if defined(USE_RLGL_UNPROJECT) // OPTION 1: Use rlglUnproject() - - Vector3 nearPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 0.0f }, matProj, matView); - Vector3 farPoint = rlglUnproject((Vector3){ deviceCoords.x, deviceCoords.y, 1.0f }, matProj, matView); - -#else // OPTION 2: Compute unprojection directly here - - // Calculate unproject matrix (multiply projection matrix and view matrix) and invert it - Matrix matProjView = MatrixMultiply(matProj, matView); - MatrixInvert(&matProjView); - - // Calculate far and near points - Quaternion qNear = { deviceCoords.x, deviceCoords.y, 0.0f, 1.0f }; - Quaternion qFar = { deviceCoords.x, deviceCoords.y, 1.0f, 1.0f }; - - // Multiply points by unproject matrix - QuaternionTransform(&qNear, matProjView); - QuaternionTransform(&qFar, matProjView); - - // Calculate normalized world points in vectors - Vector3 nearPoint = { qNear.x/qNear.w, qNear.y/qNear.w, qNear.z/qNear.w}; - Vector3 farPoint = { qFar.x/qFar.w, qFar.y/qFar.w, qFar.z/qFar.w}; -#endif - - // Calculate normalized direction vector - Vector3 direction = VectorSubtract(farPoint, nearPoint); - VectorNormalize(&direction); - - // Apply calculated vectors to ray - ray.position = camera.position; - ray.direction = direction; - - return ray; -} - -// Returns the screen space position from a 3d world space position -Vector2 GetWorldToScreen(Vector3 position, Camera camera) -{ - // Calculate projection matrix (from perspective instead of frustum - Matrix matProj = MatrixPerspective(camera.fovy, (double)GetScreenWidth()/(double)GetScreenHeight(), 0.01, 1000.0); - - // Calculate view matrix from camera look at (and transpose it) - Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); - MatrixTranspose(&matView); - - // Convert world position vector to quaternion - Quaternion worldPos = { position.x, position.y, position.z, 1.0f }; - - // Transform world position to view - QuaternionTransform(&worldPos, matView); - - // Transform result to projection (clip space position) - QuaternionTransform(&worldPos, matProj); - - // Calculate normalized device coordinates (inverted y) - Vector3 ndcPos = { worldPos.x/worldPos.w, -worldPos.y/worldPos.w, worldPos.z/worldPos.w }; - - // Calculate 2d screen position vector - Vector2 screenPosition = { (ndcPos.x + 1.0f)/2.0f*(float)GetScreenWidth(), (ndcPos.y + 1.0f)/2.0f*(float)GetScreenHeight() }; - - return screenPosition; -} - -// Get transform matrix for camera -Matrix GetCameraMatrix(Camera camera) -{ - return MatrixLookAt(camera.position, camera.target, camera.up); -} - //---------------------------------------------------------------------------------- // Module Functions Definition - Input (Keyboard, Mouse, Gamepad) Functions //---------------------------------------------------------------------------------- @@ -1559,7 +1560,7 @@ int GetMouseWheelMove(void) #endif } -// Returns touch position X +// Returns touch position X for touch point 0 (relative to screen size) int GetTouchX(void) { #if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) @@ -1569,7 +1570,7 @@ int GetTouchX(void) #endif } -// Returns touch position Y +// Returns touch position Y for touch point 0 (relative to screen size) int GetTouchY(void) { #if defined(PLATFORM_ANDROID) || defined(PLATFORM_WEB) @@ -1579,7 +1580,7 @@ int GetTouchY(void) #endif } -// Returns touch position XY +// Returns touch position XY for a touch point index (relative to screen size) // TODO: Touch position should be scaled depending on display size and render size Vector2 GetTouchPosition(int index) { diff --git a/src/raylib.h b/src/raylib.h index 4038215e..b8913c8d 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -656,15 +656,15 @@ extern "C" { // Prevents name mangling of functions // Window and Graphics Device Functions (Module: core) //------------------------------------------------------------------------------------ #if defined(PLATFORM_ANDROID) -RLAPI void InitWindow(int width, int height, void *state); // Init Android Activity and OpenGL Graphics (struct android_app) +RLAPI void InitWindow(int width, int height, void *state); // Initialize Android activity #elif defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) || defined(PLATFORM_WEB) -RLAPI void InitWindow(int width, int height, const char *title); // Initialize Window and OpenGL Graphics +RLAPI void InitWindow(int width, int height, const char *title); // Initialize window and OpenGL context #endif -RLAPI void CloseWindow(void); // Close Window and Terminate Context -RLAPI bool WindowShouldClose(void); // Detect if KEY_ESCAPE pressed or Close icon pressed -RLAPI bool IsWindowMinimized(void); // Detect if window has been minimized (or lost focus) -RLAPI void ToggleFullscreen(void); // Fullscreen toggle (only PLATFORM_DESKTOP) +RLAPI void CloseWindow(void); // Close window and unload OpenGL context +RLAPI bool WindowShouldClose(void); // Check if KEY_ESCAPE pressed or Close icon pressed +RLAPI bool IsWindowMinimized(void); // Check if window has been minimized (or lost focus) +RLAPI void ToggleFullscreen(void); // Toggle fullscreen mode (only PLATFORM_DESKTOP) RLAPI void SetWindowIcon(Image image); // Set icon for window (only PLATFORM_DESKTOP) RLAPI void SetWindowPosition(int x, int y); // Set window position on screen (only PLATFORM_DESKTOP) RLAPI void SetWindowMonitor(int monitor); // Set monitor for the current window (fullscreen mode) @@ -675,29 +675,29 @@ RLAPI int GetScreenHeight(void); // Get current #if !defined(PLATFORM_ANDROID) RLAPI void ShowCursor(void); // Shows cursor RLAPI void HideCursor(void); // Hides cursor -RLAPI bool IsCursorHidden(void); // Returns true if cursor is not visible -RLAPI void EnableCursor(void); // Enables cursor -RLAPI void DisableCursor(void); // Disables cursor +RLAPI bool IsCursorHidden(void); // Check if cursor is not visible +RLAPI void EnableCursor(void); // Enables cursor (unlock cursor) +RLAPI void DisableCursor(void); // Disables cursor (lock cursor) #endif -RLAPI void ClearBackground(Color color); // Sets Background Color -RLAPI void BeginDrawing(void); // Setup drawing canvas to start drawing -RLAPI void EndDrawing(void); // End canvas drawing and Swap Buffers (Double Buffering) +RLAPI void ClearBackground(Color color); // Set background color (framebuffer clear color) +RLAPI void BeginDrawing(void); // Setup canvas (framebuffer) to start drawing +RLAPI void EndDrawing(void); // End canvas drawing and swap buffers (double buffering) -RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera -RLAPI void End2dMode(void); // Ends 2D mode custom camera usage -RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode for drawing (Camera setup) +RLAPI void Begin2dMode(Camera2D camera); // Initialize 2D mode with custom camera (2D) +RLAPI void End2dMode(void); // Ends 2D mode with custom camera +RLAPI void Begin3dMode(Camera camera); // Initializes 3D mode with custom camera (3D) RLAPI void End3dMode(void); // Ends 3D mode and returns to default 2D orthographic mode RLAPI void BeginTextureMode(RenderTexture2D target); // Initializes render texture for drawing RLAPI void EndTextureMode(void); // Ends drawing to render texture RLAPI Ray GetMouseRay(Vector2 mousePosition, Camera camera); // Returns a ray trace from mouse position -RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position from a 3d world space position +RLAPI Vector2 GetWorldToScreen(Vector3 position, Camera camera); // Returns the screen space position for a 3d world space position RLAPI Matrix GetCameraMatrix(Camera camera); // Returns camera transform matrix (view matrix) RLAPI void SetTargetFPS(int fps); // Set target FPS (maximum) RLAPI int GetFPS(void); // Returns current FPS -RLAPI float GetFrameTime(void); // Returns time in seconds for one frame +RLAPI float GetFrameTime(void); // Returns time in seconds for last frame drawn RLAPI Color GetColor(int hexValue); // Returns a Color struct from hexadecimal value RLAPI int GetHexValue(Color color); // Returns hexadecimal value for a Color @@ -708,18 +708,18 @@ RLAPI float *MatrixToFloat(Matrix mat); // Converts Ma RLAPI int GetRandomValue(int min, int max); // Returns a random value between min and max (both included) RLAPI Color Fade(Color color, float alpha); // Color fade-in or fade-out, alpha goes from 0.0f to 1.0f -RLAPI void ShowLogo(void); // Activates raylib logo at startup (can be done with flags) -RLAPI void SetConfigFlags(char flags); // Setup some window configuration flags +RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) +RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension -RLAPI bool IsFileDropped(void); // Check if a file have been dropped into window -RLAPI char **GetDroppedFiles(int *count); // Retrieve dropped files into window +RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window +RLAPI char **GetDroppedFiles(int *count); // Get dropped files names RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer -RLAPI void StorageSaveValue(int position, int value); // Storage save integer value (to defined position) -RLAPI int StorageLoadValue(int position); // Storage load integer value (from defined position) +RLAPI void StorageSaveValue(int position, int value); // Save integer value to storage file (to defined position) +RLAPI int StorageLoadValue(int position); // Load integer value from storage file (from defined position) //------------------------------------------------------------------------------------ // Input Handling Functions (Module: core) @@ -877,7 +877,7 @@ RLAPI void DrawTextEx(SpriteFont spriteFont, const char* text, Vector2 position, RLAPI int MeasureText(const char *text, int fontSize); // Measure string width for default font RLAPI Vector2 MeasureTextEx(SpriteFont spriteFont, const char *text, float fontSize, int spacing); // Measure string size for SpriteFont -RLAPI void DrawFPS(int posX, int posY); // Shows current FPS on top-left corner +RLAPI void DrawFPS(int posX, int posY); // Shows current FPS RLAPI const char *FormatText(const char *text, ...); // Formatting of text with variables to 'embed' RLAPI const char *SubText(const char *text, int position, int length); // Get a piece of a text string -- cgit v1.2.3 From 35fe34ba0f4a8de97e0854a64c52eca88bab98cf Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 11 May 2017 16:24:40 +0200 Subject: Added some useful functions --- src/core.c | 74 ++++++++++++++++++++++++++++++++++++++++++++++-------------- src/raylib.h | 7 ++++-- 2 files changed, 62 insertions(+), 19 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index cca8a1ac..fa368747 100644 --- a/src/core.c +++ b/src/core.c @@ -108,6 +108,16 @@ #include // Required for: strrchr(), strcmp() //#include // Macros for reporting and retrieving error conditions through error codes +#ifdef _WIN32 + #include // Required for: _getch(), _chdir() + #define GETCWD _getcwd // NOTE: MSDN recommends not to use getcwd(), chdir() + #define CHDIR _chdir +#else + #include "unistd.h" // Required for: getch(), chdir() (POSIX) + #define GETCWD getcwd + #define CHDIR chdir +#endif + #if defined(__linux__) || defined(PLATFORM_WEB) #include // Required for: timespec, nanosleep(), select() - POSIX #elif defined(__APPLE__) @@ -259,6 +269,7 @@ static Matrix downscaleView; // Matrix to downscale view (in case static const char *windowTitle; // Window text title... static bool cursorOnScreen = false; // Tracks if cursor is inside client area static bool cursorHidden = false; // Track if cursor is hidden +static int screenshotCounter = 0; // Screenshots counter // Register mouse states static char previousMouseState[3] = { 0 }; // Registers previous mouse button state @@ -1131,25 +1142,15 @@ void SetConfigFlags(char flags) // NOTE TraceLog() function is located in [utils.h] -// Takes a screenshot and saves it in the same folder as executable -void TakeScreenshot(void) +// Takes a screenshot of current screen (saved a .png) +void TakeScreenshot(const char *fileName) { #if defined(PLATFORM_DESKTOP) || defined(PLATFORM_RPI) - static int shotNum = 0; // Screenshot number, increments every screenshot take during program execution - char buffer[20]; // Buffer to store file name - unsigned char *imgData = rlglReadScreenPixels(renderWidth, renderHeight); - - sprintf(buffer, "screenshot%03i.png", shotNum); - - // Save image as PNG - SavePNG(buffer, imgData, renderWidth, renderHeight, 4); - + SavePNG(fileName, imgData, renderWidth, renderHeight, 4); // Save image as PNG free(imgData); - shotNum++; - - TraceLog(INFO, "[%s] Screenshot taken #03i", buffer, shotNum); + TraceLog(INFO, "Screenshot taken: %s", fileName); #endif } @@ -1167,6 +1168,37 @@ bool IsFileExtension(const char *fileName, const char *ext) return result; } +// Get directory for a given fileName (with path) +const char *GetDirectoryPath(const char *fileName) +{ + char *lastSlash = NULL; + static char filePath[256]; // MAX_DIRECTORY_PATH_SIZE = 256 + memset(filePath, 0, 256); + + lastSlash = strrchr(fileName, '\\'); + strncpy(filePath, fileName, strlen(fileName) - (strlen(lastSlash) - 1)); + filePath[strlen(fileName) - strlen(lastSlash)] = '\0'; + + return filePath; +} + +// Get current working directory +const char *GetWorkingDirectory(void) +{ + static char currentDir[256]; // MAX_DIRECTORY_PATH_SIZE = 256 + memset(currentDir, 0, 256); + + GETCWD(currentDir, 256 - 1); + + return currentDir; +} + +// Change working directory, returns true if success +bool ChangeDirectory(const char *dir) +{ + return (CHDIR(dir) == 0); +} + #if defined(PLATFORM_DESKTOP) // Check if a file has been dropped into window bool IsFileDropped(void) @@ -2363,7 +2395,11 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i // NOTE: Before closing window, while loop must be left! } #if defined(PLATFORM_DESKTOP) - else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) TakeScreenshot(); + else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) + { + TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); + screenshotCounter++; + } #endif else { @@ -3003,8 +3039,12 @@ static void ProcessKeyboard(void) // Check exit key (same functionality as GLFW3 KeyCallback()) if (currentKeyState[exitKey] == 1) windowShouldClose = true; - // Check screen capture key - if (currentKeyState[301] == 1) TakeScreenshot(); // raylib key: KEY_F12 (GLFW_KEY_F12) + // Check screen capture key (raylib key: KEY_F12) + if (currentKeyState[301] == 1) + { + TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); + screenshotCounter++; + } } // Restore default keyboard input diff --git a/src/raylib.h b/src/raylib.h index e49081b5..a3276d8e 100644 --- a/src/raylib.h +++ b/src/raylib.h @@ -711,9 +711,12 @@ RLAPI Color Fade(Color color, float alpha); // Color fade- RLAPI void ShowLogo(void); // Activate raylib logo at startup (can be done with flags) RLAPI void SetConfigFlags(char flags); // Setup window configuration flags (view FLAGS) RLAPI void TraceLog(int logType, const char *text, ...); // Show trace log messages (INFO, WARNING, ERROR, DEBUG) -RLAPI void TakeScreenshot(void); // Takes a screenshot and saves it in the same folder as executable -RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension +RLAPI void TakeScreenshot(const char *fileName); // Takes a screenshot of current screen (saved a .png) +RLAPI bool IsFileExtension(const char *fileName, const char *ext);// Check file extension +RLAPI const char *GetDirectoryPath(const char *fileName); // Get directory for a given fileName (with path) +RLAPI const char *GetWorkingDirectory(void); // Get current working directory +RLAPI bool ChangeDirectory(const char *dir); // Change working directory, returns true if success RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window RLAPI char **GetDroppedFiles(int *count); // Get dropped files names RLAPI void ClearDroppedFiles(void); // Clear dropped files paths buffer -- cgit v1.2.3 From e01a1ba10c5be8a98f6aca0f24d95dc1738010ac Mon Sep 17 00:00:00 2001 From: Ray Date: Thu, 18 May 2017 18:57:11 +0200 Subject: Support Gif recording --- src/core.c | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 83 insertions(+), 4 deletions(-) (limited to 'src/core.c') diff --git a/src/core.c b/src/core.c index fa368747..07f3bb07 100644 --- a/src/core.c +++ b/src/core.c @@ -44,6 +44,9 @@ * #define SUPPORT_BUSY_WAIT_LOOP * Use busy wait loop for timming sync, if not defined, a high-resolution timer is setup and used * +* #define SUPPORT_GIF_RECORDING +* Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback() +* * DEPENDENCIES: * GLFW3 - Manage graphic device, OpenGL context and inputs on PLATFORM_DESKTOP (Windows, Linux, OSX) * raymath - 3D math functionality (Vector3, Matrix, Quaternion) @@ -79,6 +82,7 @@ #define SUPPORT_CAMERA_SYSTEM #define SUPPORT_GESTURES_SYSTEM #define SUPPORT_BUSY_WAIT_LOOP +#define SUPPORT_GIF_RECORDING //------------------------------------------------- #include "raylib.h" @@ -97,7 +101,12 @@ #if defined(SUPPORT_CAMERA_SYSTEM) && !defined(PLATFORM_ANDROID) #define CAMERA_IMPLEMENTATION - #include "camera.h" // Camera system functionality + #include "camera.h" // Camera system functionality +#endif + +#if defined(SUPPORT_GIF_RECORDING) + #define GIF_IMPLEMENTATION + #include "external/gif.h" // Support GIF recording #endif #include // Standard input / output lib @@ -318,6 +327,12 @@ static double targetTime = 0.0; // Desired time for one frame, if 0 static char configFlags = 0; // Configuration flags (bit based) static bool showLogo = false; // Track if showing logo at init is enabled +#if defined(SUPPORT_GIF_RECORDING) +static GifWriter gifWriter; +static int gifFramesCounter = 0; +static bool gifRecording = false; +#endif + //---------------------------------------------------------------------------------- // Other Modules Functions Declaration (required by core) //---------------------------------------------------------------------------------- @@ -520,6 +535,14 @@ void InitWindow(int width, int height, void *state) // Close window and unload OpenGL context void CloseWindow(void) { +#if defined(SUPPORT_GIF_RECORDING) + if (gifRecording) + { + GifEnd(&gifWriter); + gifRecording = false; + } +#endif + #if defined(SUPPORT_DEFAULT_FONT) UnloadDefaultFont(); #endif @@ -770,6 +793,35 @@ void EndDrawing(void) { rlglDraw(); // Draw Buffers (Only OpenGL 3+ and ES2) +#if defined(SUPPORT_GIF_RECORDING) + + #define GIF_RECORD_FRAMERATE 10 + + if (gifRecording) + { + gifFramesCounter++; + + // NOTE: We record one gif frame every 10 game frames + if ((gifFramesCounter%GIF_RECORD_FRAMERATE) == 0) + { + // Get image data for the current frame (from backbuffer) + // NOTE: This process is very slow... :( + unsigned char *screenData = rlglReadScreenPixels(screenWidth, screenHeight); + GifWriteFrame(&gifWriter, screenData, screenWidth, screenHeight, 10, 8, false); + + free(screenData); // Free image data + } + + if (((gifFramesCounter/15)%2) == 1) + { + DrawCircle(30, screenHeight - 20, 10, RED); + DrawText("RECORDING", 50, screenHeight - 25, 10, MAROON); + } + + rlglDraw(); // Draw RECORDING message + } +#endif + SwapBuffers(); // Copy back buffer to front buffer PollInputEvents(); // Poll user events @@ -2397,10 +2449,37 @@ static void KeyCallback(GLFWwindow *window, int key, int scancode, int action, i #if defined(PLATFORM_DESKTOP) else if (key == GLFW_KEY_F12 && action == GLFW_PRESS) { - TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); - screenshotCounter++; + #if defined(SUPPORT_GIF_RECORDING) + if (mods == GLFW_MOD_CONTROL) + { + if (gifRecording) + { + GifEnd(&gifWriter); + gifRecording = false; + + TraceLog(INFO, "End animated GIF recording"); + } + else + { + gifRecording = true; + gifFramesCounter = 0; + + // NOTE: delay represents the time between frames in the gif, if we capture a gif frame every + // 10 game frames and each frame trakes 16.6ms (60fps), delay between gif frames should be ~16.6*10. + GifBegin(&gifWriter, FormatText("screenrec%03i.gif", screenshotCounter), screenWidth, screenHeight, (int)(GetFrameTime()*10.0f), 8, false); + screenshotCounter++; + + TraceLog(INFO, "Begin animated GIF recording: %s", FormatText("screenrec%03i.gif", screenshotCounter)); + } + } + else + #endif // SUPPORT_GIF_RECORDING + { + TakeScreenshot(FormatText("screenshot%03i.png", screenshotCounter)); + screenshotCounter++; + } } -#endif +#endif // PLATFORM_DESKTOP else { currentKeyState[key] = action; -- cgit v1.2.3