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