[
  {
    "path": ".gitattributes",
    "content": "# Auto detect text files and perform LF normalization\n* text=auto\n\n# Custom for Visual Studio\n*.cs     diff=csharp\n\n# Standard to msysgit\n*.doc\t diff=astextplain\n*.DOC\t diff=astextplain\n*.docx diff=astextplain\n*.DOCX diff=astextplain\n*.dot  diff=astextplain\n*.DOT  diff=astextplain\n*.pdf  diff=astextplain\n*.PDF\t diff=astextplain\n*.rtf\t diff=astextplain\n*.RTF\t diff=astextplain\n"
  },
  {
    "path": ".gitignore",
    "content": "# Object files\n*.o\n*.ko\n*.obj\n*.elf\n\n# Precompiled Headers\n*.gch\n*.pch\n\n# Libraries\n*.lib\n*.a\n*.la\n*.lo\n\n# Shared objects (inc. Windows DLLs)\n*.so\n*.so.*\n*.dylib\n\n# Executables\n*.out\n*.app\n*.i*86\n*.x86_64\n*.hex\n\n# Debug files\n*.dSYM/\n\n# =========================\n# Operating System Files\n# =========================\n\n# Linux\n# =========================\n\n# Vim temporary files\n*~\n*.swp\n*.swo\n\n# OSX\n# =========================\n\n.DS_Store\n.AppleDouble\n.LSOverride\n\n# Thumbnails\n._*\n\n# Files that might appear in the root of a volume\n.DocumentRevisions-V100\n.fseventsd\n.Spotlight-V100\n.TemporaryItems\n.Trashes\n.VolumeIcon.icns\n\n# Directories potentially created on remote AFP share\n.AppleDB\n.AppleDesktop\nNetwork Trash Folder\nTemporary Items\n.apdisk\n\n# Windows\n# =========================\n\n# Windows image file caches\nThumbs.db\nehthumbs.db\n\n# Folder config file\nDesktop.ini\n\n# Recycle Bin used on file shares\n$RECYCLE.BIN/\n\n# Windows Installer files\n*.cab\n*.msi\n*.msm\n*.msp\n\n# Windows shortcuts\n*.lnk\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2022 Víctor Fisac\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "<img src=\"https://github.com/victorfisac/Physac/blob/master/icon/physac_256x256.png\">\n\n# Physac\n\nPhysac is a small 2D physics engine written in pure C. The engine uses a fixed time-step thread loop to simluate physics.\nA physics step contains the following phases: get collision information, apply dynamics, collision solving and position correction. It uses a very simple struct for physic bodies with a position vector to be used in any 3D rendering API.\n\nThe header file includes some tweakable define values to fit the results that the user wants with a minimal bad results. Most of those values are commented with a little explanation about their uses.\n\n_Note: The example code uses raylib programming library to create the program window and rendering framework._\n\nInstallation\n-----\n\nPhysac requires raylib. To get it, follow the next steps:\n\n    * Go to [raylib](https://www.github.com/raysan5/raylib) and clone the repository.\n    * Ensure to pull the last changes of 'master' branch.\n    * Use code inside examples header comments to compile and execute.\n\nPhysac API\n-----\n\nThe PhysicsBody struct contains all dynamics information and collision shape. The user should use the following structure components:\n```c\ntypedef struct *PhysicsBody {\n    unsigned int id;\n    bool enabled;                   // Enabled dynamics state (collisions are calculated anyway)\n    Vector2 position;               // Physics body shape pivot\n    Vector2 velocity;               // Current linear velocity applied to position\n    Vector2 force;                  // Current linear force (reset to 0 every step)\n    float angularVelocity;          // Current angular velocity applied to orient\n    float torque;                   // Current angular force (reset to 0 every step)\n    float orient;                   // Rotation in radians\n    float staticFriction;           // Friction when the body has not movement (0 to 1)\n    float dynamicFriction;          // Friction when the body has movement (0 to 1)\n    float restitution;              // Restitution coefficient of the body (0 to 1)\n    bool useGravity;                // Apply gravity force to dynamics\n    bool isGrounded;                // Physics grounded on other body state\n    bool freezeOrient;              // Physics rotation constraint\n    PhysicsShape shape;             // Physics body shape information (type, radius, vertices, normals)\n} *PhysicsBody;\n```\nThe header contains a few customizable define values. I set the values that gived me the best results.\n\n```c\n#define     PHYSAC_MAX_BODIES               64\n#define     PHYSAC_MAX_MANIFOLDS            4096\n#define     PHYSAC_MAX_VERTICES             24\n#define     PHYSAC_CIRCLE_VERTICES          24\n\n#define     PHYSAC_COLLISION_ITERATIONS     100\n#define     PHYSAC_PENETRATION_ALLOWANCE    0.05f\n#define     PHYSAC_PENETRATION_CORRECTION   0.4f\n```\n\nPhysac contains defines for memory management functions (malloc, free) to bring the user the opportunity to implement its own memory functions:\n\n```c\n#define     PHYSAC_MALLOC(size)             malloc(size)\n#define     PHYSAC_FREE(ptr)                free(ptr)\n```\n\nThe Physac API functions availables for the user are the following:\n\n```c\n// Initializes physics values, pointers and creates physics loop thread\nvoid InitPhysics(void);\n\n// Returns true if physics thread is currently enabled\nbool IsPhysicsEnabled(void);\n\n// Sets physics global gravity force\nvoid SetPhysicsGravity(float x, float y);\n\n// Creates a new circle physics body with generic parameters\nPhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density);\n\n// Creates a new rectangle physics body with generic parameters\nPhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density);\n\n// Creates a new polygon physics body with generic parameters\nPhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density);\n\n// Adds a force to a physics body\nvoid PhysicsAddForce(PhysicsBody body, Vector2 force);\n\n// Adds a angular force to a physics body\nvoid PhysicsAddTorque(PhysicsBody body, float amount);\n\n// Shatters a polygon shape physics body to little physics bodies with explosion force\nvoid PhysicsShatter(PhysicsBody body, Vector2 position, float force);\n\n// Returns the current amount of created physics bodies\nint GetPhysicsBodiesCount(void);\n\n// Returns a physics body of the bodies pool at a specific index\nPhysicsBody GetPhysicsBody(int index);\n\n// Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON)\nint GetPhysicsShapeType(int index);\n\n// Returns the amount of vertices of a physics body shape\nint GetPhysicsShapeVerticesCount(int index);\n\n// Returns transformed position of a body shape (body position + vertex transformed position)\nVector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex);\n\n// Sets physics body shape transform based on radians parameter\nvoid SetPhysicsBodyRotation(PhysicsBody body, float radians);\n\n// Unitializes and destroy a physics body\nvoid DestroyPhysicsBody(PhysicsBody body);\n\n// Unitializes physics pointers and closes physics loop thread\nvoid ClosePhysics(void);\n```\n_Note: InitPhysics() needs to be called at program start and ClosePhysics() before the program ends. Closing and initializing Physac during the program flow doesn't affect or produces any error (useful as a 'reset' to destroy any created body by user in runtime)._\n\nDependencies\n-----\n\nPhysac uses the following C libraries for memory management, math operations and some debug features:\n\n   *  stdlib.h - Memory allocation [malloc(), free(), srand(), rand()].\n   *  stdio.h  - Message logging (only if PHYSAC_DEBUG is defined) [printf()].\n   *  math.h   - Math operations functions [cos(), sin(), fabs(), sqrtf()].\n\n**It is independent to any graphics engine** and prepared to use any graphics API and use the vertices information (look at examples Drawing logic) to draw lines or shapes in screen. For example, this vertices information can be use in OpenGL API glVertex2f().\n\nBy the way, I use [raylib](http://www.raylib.com) to create the examples. This videogames programming library is used to handle inputs, window management and graphics drawing (using OpenGL API).\n"
  },
  {
    "path": "examples/physics_demo.c",
    "content": "/*******************************************************************************************\n*\n*   Physac - Physics demo\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread \n*           is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency \n*           on MinGW DLL (-static -lpthread)\n*\n*   Compile this program using:\n*       gcc -o $(NAME_PART).exe $(FILE_NAME) -s ..\\icon\\physac_icon -I. -I../src \n*           -I../src/external/raylib/src -static -lraylib -lopengl32 -lgdi32 -pthread -std=c99\n*   \n*   Copyright (c) 2016-2025 Victor Fisac (github: @victorfisac)\n*\n********************************************************************************************/\n\n#include \"raylib.h\"\n\n#define PHYSAC_IMPLEMENTATION\n#include \"../src/physac.h\"\n\nint main()\n{\n    // Initialization\n    //--------------------------------------------------------------------------------------\n    int screenWidth = 800;\n    int screenHeight = 450;\n\n    SetConfigFlags(FLAG_MSAA_4X_HINT);\n    InitWindow(screenWidth, screenHeight, \"[physac] Basic demo\");\n\n    // Physac logo drawing position\n    int logoX = screenWidth - MeasureText(\"Physac\", 30) - 10;\n    int logoY = 15;\n\n    // Initialize physics and default physics bodies\n    InitPhysics();\n\n    // Create floor rectangle physics body\n    PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10);\n    floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n\n    // Create obstacle circle physics body\n    PhysicsBody circle = CreatePhysicsBodyCircle((Vector2){ screenWidth/2, screenHeight/2 }, 45, 10);\n    circle->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n    \n    SetTargetFPS(60);\n    //--------------------------------------------------------------------------------------\n\n    // Main game loop\n    while (!WindowShouldClose())    // Detect window close button or ESC key\n    {\n        // Update\n        //----------------------------------------------------------------------------------\n        // Physics body creation inputs\n        if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))\n            CreatePhysicsBodyPolygon(GetMousePosition(), GetRandomValue(20, 80), GetRandomValue(3, 8), 10);\n        else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON))\n            CreatePhysicsBodyCircle(GetMousePosition(), GetRandomValue(10, 45), 10);\n\n        // Destroy falling physics bodies\n        int bodiesCount = GetPhysicsBodiesCount();\n        for (int i = bodiesCount - 1; i >= 0; i--)\n        {\n            PhysicsBody body = GetPhysicsBody(i);\n            \n            if ((body != NULL) && (body->position.y > screenHeight*2))\n                DestroyPhysicsBody(body);\n        }\n        //----------------------------------------------------------------------------------\n\n        // Draw\n        //----------------------------------------------------------------------------------\n        BeginDrawing();\n\n            ClearBackground(BLACK);\n\n            DrawFPS(screenWidth - 90, screenHeight - 30);\n\n            // Draw created physics bodies\n            bodiesCount = GetPhysicsBodiesCount();\n            for (int i = 0; i < bodiesCount; i++)\n            {\n                PhysicsBody body = GetPhysicsBody(i);\n\n                if (body != NULL)\n                {\n                    int vertexCount = GetPhysicsShapeVerticesCount(i);\n                    for (int j = 0; j < vertexCount; j++)\n                    {\n                        // Get physics bodies shape vertices to draw lines\n                        // Note: GetPhysicsShapeVertex() already calculates rotation transformations\n                        Vector2 vertexA = GetPhysicsShapeVertex(body, j);\n\n                        int jj = (((j + 1) < vertexCount) ? (j + 1) : 0);   // Get next vertex or first to close the shape\n                        Vector2 vertexB = GetPhysicsShapeVertex(body, jj);\n\n                        DrawLineV(vertexA, vertexB, GREEN);     // Draw a line between two vertex positions\n                    }\n                }\n            }\n\n            DrawText(\"Left mouse button to create a polygon\", 10, 10, 10, WHITE);\n            DrawText(\"Right mouse button to create a circle\", 10, 25, 10, WHITE);\n\n            DrawText(\"Physac\", logoX, logoY, 30, WHITE);\n            DrawText(\"Powered by\", logoX + 50, logoY - 7, 10, WHITE);\n\n        EndDrawing();\n        //----------------------------------------------------------------------------------\n    }\n\n    // De-Initialization\n    //--------------------------------------------------------------------------------------   \n    ClosePhysics();       // Unitialize physics\n    \n    CloseWindow();        // Close window and OpenGL context\n    //--------------------------------------------------------------------------------------\n\n    return 0;\n}"
  },
  {
    "path": "examples/physics_friction.c",
    "content": "/*******************************************************************************************\n*\n*   Physac - Physics friction\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread \n*           is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency \n*           on MinGW DLL (-static -lpthread)\n*\n*   Compile this program using:\n*       gcc -o $(NAME_PART).exe $(FILE_NAME) -s ..\\icon\\physac_icon -I. -I../src \n*           -I../src/external/raylib/src -static -lraylib -lopengl32 -lgdi32 -pthread -std=c99\n*   \n*   Copyright (c) 2016-2025 Victor Fisac (github: @victorfisac)\n*\n********************************************************************************************/\n\n#include \"raylib.h\"\n\n#define PHYSAC_IMPLEMENTATION\n#include \"../src/physac.h\"\n\nint main()\n{\n    // Initialization\n    //--------------------------------------------------------------------------------------\n    int screenWidth = 800;\n    int screenHeight = 450;\n\n    SetConfigFlags(FLAG_MSAA_4X_HINT);\n    InitWindow(screenWidth, screenHeight, \"[physac] Friction demo\");\n\n    // Physac logo drawing position\n    int logoX = screenWidth - MeasureText(\"Physac\", 30) - 10;\n    int logoY = 15;\n\n    // Initialize physics and default physics bodies\n    InitPhysics();\n\n    // Create floor rectangle physics body\n    PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, screenWidth, 100, 10);\n    floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n    PhysicsBody wall = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight*0.8f }, 10, 80, 10);\n    wall->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n\n    // Create left ramp physics body\n    PhysicsBody rectLeft = CreatePhysicsBodyRectangle((Vector2){ 25, screenHeight - 5 }, 250, 250, 10);\n    rectLeft->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n    SetPhysicsBodyRotation(rectLeft, 30*DEG2RAD);\n\n    // Create right ramp  physics body\n    PhysicsBody rectRight = CreatePhysicsBodyRectangle((Vector2){ screenWidth - 25, screenHeight - 5 }, 250, 250, 10);\n    rectRight->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n    SetPhysicsBodyRotation(rectRight, 330*DEG2RAD);\n\n    // Create dynamic physics bodies\n    PhysicsBody bodyA = CreatePhysicsBodyRectangle((Vector2){ 35, screenHeight*0.6f }, 40, 40, 10);\n    bodyA->staticFriction = 0.1f;\n    bodyA->dynamicFriction = 0.1f;\n    SetPhysicsBodyRotation(bodyA, 30*DEG2RAD);\n\n    PhysicsBody bodyB = CreatePhysicsBodyRectangle((Vector2){ screenWidth - 35, screenHeight*0.6f }, 40, 40, 10);\n    bodyB->staticFriction = 1;\n    bodyB->dynamicFriction = 1;\n    SetPhysicsBodyRotation(bodyB, 330*DEG2RAD);\n\n    SetTargetFPS(60);\n    //--------------------------------------------------------------------------------------\n\n    // Main game loop\n    while (!WindowShouldClose())    // Detect window close button or ESC key\n    {\n        // Update\n        //----------------------------------------------------------------------------------\n        // ...\n        //----------------------------------------------------------------------------------\n\n        // Draw\n        //----------------------------------------------------------------------------------\n        BeginDrawing();\n\n            ClearBackground(BLACK);\n\n            DrawFPS(screenWidth - 90, screenHeight - 30);\n\n            // Draw created physics bodies\n            int bodiesCount = GetPhysicsBodiesCount();\n            for (int i = 0; i < bodiesCount; i++)\n            {\n                PhysicsBody body = GetPhysicsBody(i);\n\n                if (body != NULL)\n                {\n                    int vertexCount = GetPhysicsShapeVerticesCount(i);\n                    for (int j = 0; j < vertexCount; j++)\n                    {\n                        // Get physics bodies shape vertices to draw lines\n                        // Note: GetPhysicsShapeVertex() already calculates rotation transformations\n                        Vector2 vertexA = GetPhysicsShapeVertex(body, j);\n\n                        int jj = (((j + 1) < vertexCount) ? (j + 1) : 0);   // Get next vertex or first to close the shape\n                        Vector2 vertexB = GetPhysicsShapeVertex(body, jj);\n\n                        DrawLineV(vertexA, vertexB, GREEN);     // Draw a line between two vertex positions\n                    }\n                }\n            }\n\n            DrawRectangle(0, screenHeight - 49, screenWidth, 49, BLACK);\n\n            DrawText(\"Friction amount\", (screenWidth - MeasureText(\"Friction amount\", 30))/2, 75, 30, WHITE);\n            DrawText(\"0.1\", bodyA->position.x - MeasureText(\"0.1\", 20)/2, bodyA->position.y - 7, 20, WHITE);\n            DrawText(\"1\", bodyB->position.x - MeasureText(\"1\", 20)/2, bodyB->position.y - 7, 20, WHITE);\n\n            DrawText(\"Physac\", logoX, logoY, 30, WHITE);\n            DrawText(\"Powered by\", logoX + 50, logoY - 7, 10, WHITE);\n\n        EndDrawing();\n        //----------------------------------------------------------------------------------\n    }\n\n    // De-Initialization\n    //--------------------------------------------------------------------------------------   \n    ClosePhysics();       // Unitialize physics\n    \n    CloseWindow();        // Close window and OpenGL context\n    //--------------------------------------------------------------------------------------\n\n    return 0;\n}"
  },
  {
    "path": "examples/physics_movement.c",
    "content": "/*******************************************************************************************\n*\n*   Physac - Physics movement\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread \n*           is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency \n*           on MinGW DLL (-static -lpthread)\n*\n*   Compile this program using:\n*       gcc -o $(NAME_PART).exe $(FILE_NAME) -s ..\\icon\\physac_icon -I. -I../src \n*           -I../src/external/raylib/src -static -lraylib -lopengl32 -lgdi32 -pthread -std=c99\n*   \n*   Copyright (c) 2016-2025 Victor Fisac (github: @victorfisac)\n*\n********************************************************************************************/\n\n#include \"raylib.h\"\n\n#define PHYSAC_IMPLEMENTATION\n#include \"../src/physac.h\"\n\n#define VELOCITY    0.5f\n\nint main()\n{\n    // Initialization\n    //--------------------------------------------------------------------------------------\n    int screenWidth = 800;\n    int screenHeight = 450;\n\n    SetConfigFlags(FLAG_MSAA_4X_HINT);\n    InitWindow(screenWidth, screenHeight, \"[physac] - Body controller demo\");\n\n    // Physac logo drawing position\n    int logoX = screenWidth - MeasureText(\"Physac\", 30) - 10;\n    int logoY = 15;\n\n    // Initialize physics and default physics bodies\n    InitPhysics();\n\n    // Create floor and walls rectangle physics body\n    PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, screenWidth, 100, 10);\n    PhysicsBody platformLeft = CreatePhysicsBodyRectangle((Vector2){ screenWidth*0.25f, screenHeight*0.6f }, screenWidth*0.25f, 10, 10);\n    PhysicsBody platformRight = CreatePhysicsBodyRectangle((Vector2){ screenWidth*0.75f, screenHeight*0.6f }, screenWidth*0.25f, 10, 10);\n    PhysicsBody wallLeft = CreatePhysicsBodyRectangle((Vector2){ -5, screenHeight/2 }, 10, screenHeight, 10);\n    PhysicsBody wallRight = CreatePhysicsBodyRectangle((Vector2){ screenWidth + 5, screenHeight/2 }, 10, screenHeight, 10);\n\n    // Disable dynamics to floor and walls physics bodies\n    floor->enabled = false;\n    platformLeft->enabled = false;\n    platformRight->enabled = false;\n    wallLeft->enabled = false;\n    wallRight->enabled = false;\n\n    // Create movement physics body\n    PhysicsBody body = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight/2 }, 50, 50, 1);\n    body->freezeOrient = true;  // Constrain body rotation to avoid little collision torque amounts\n    \n    SetTargetFPS(60);\n    //--------------------------------------------------------------------------------------\n\n    // Main game loop\n    while (!WindowShouldClose())    // Detect window close button or ESC key\n    {\n        // Update\n        //----------------------------------------------------------------------------------\n        // Horizontal movement input\n        if (IsKeyDown(KEY_RIGHT))\n            body->velocity.x = VELOCITY;\n        else if (IsKeyDown(KEY_LEFT))\n            body->velocity.x = -VELOCITY;\n\n        // Vertical movement input checking if player physics body is grounded\n        if (IsKeyDown(KEY_UP) && body->isGrounded)\n            body->velocity.y = -VELOCITY*4;\n        //----------------------------------------------------------------------------------\n\n        // Draw\n        //----------------------------------------------------------------------------------\n        BeginDrawing();\n\n            ClearBackground(BLACK);\n\n            DrawFPS(screenWidth - 90, screenHeight - 30);\n\n            // Draw created physics bodies\n            int bodiesCount = GetPhysicsBodiesCount();\n            for (int i = 0; i < bodiesCount; i++)\n            {\n                PhysicsBody body = GetPhysicsBody(i);\n\n                int vertexCount = GetPhysicsShapeVerticesCount(i);\n                for (int j = 0; j < vertexCount; j++)\n                {\n                    // Get physics bodies shape vertices to draw lines\n                    // Note: GetPhysicsShapeVertex() already calculates rotation transformations\n                    Vector2 vertexA = GetPhysicsShapeVertex(body, j);\n\n                    int jj = (((j + 1) < vertexCount) ? (j + 1) : 0);   // Get next vertex or first to close the shape\n                    Vector2 vertexB = GetPhysicsShapeVertex(body, jj);\n\n                    DrawLineV(vertexA, vertexB, GREEN);     // Draw a line between two vertex positions\n                }\n            }\n\n            DrawText(\"Use 'ARROWS' to move player\", 10, 10, 10, WHITE);\n\n            DrawText(\"Physac\", logoX, logoY, 30, WHITE);\n            DrawText(\"Powered by\", logoX + 50, logoY - 7, 10, WHITE);\n\n        EndDrawing();\n        //----------------------------------------------------------------------------------\n    }\n\n    // De-Initialization\n    //--------------------------------------------------------------------------------------   \n    ClosePhysics();       // Unitialize physics\n    \n    CloseWindow();        // Close window and OpenGL context\n    //--------------------------------------------------------------------------------------\n\n    return 0;\n}"
  },
  {
    "path": "examples/physics_restitution.c",
    "content": "/*******************************************************************************************\n*\n*   Physac - Physics restitution\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread \n*           is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency \n*           on MinGW DLL (-static -lpthread)\n*\n*   Compile this program using:\n*       gcc -o $(NAME_PART).exe $(FILE_NAME) -s ..\\icon\\physac_icon -I. -I../src \n*           -I../src/external/raylib/src -static -lraylib -lopengl32 -lgdi32 -pthread -std=c99\n*   \n*   Copyright (c) 2016-2025 Victor Fisac (github: @victorfisac)\n*\n********************************************************************************************/\n\n#include \"raylib.h\"\n\n#define PHYSAC_IMPLEMENTATION\n#include \"../src/physac.h\"\n\nint main()\n{\n    // Initialization\n    //--------------------------------------------------------------------------------------\n    int screenWidth = 800;\n    int screenHeight = 450;\n\n    SetConfigFlags(FLAG_MSAA_4X_HINT);\n    InitWindow(screenWidth, screenHeight, \"[physac] - Restitution demo\");\n\n    // Physac logo drawing position\n    int logoX = screenWidth - MeasureText(\"Physac\", 30) - 10;\n    int logoY = 15;\n\n    // Initialize physics and default physics bodies\n    InitPhysics();\n\n    // Create floor rectangle physics body\n    PhysicsBody floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, screenWidth, 100, 10);\n    floor->enabled = false; // Disable body state to convert it to static (no dynamics, but collisions)\n    floor->restitution = 0.9f;\n\n    // Create circles physics body\n    PhysicsBody circleA = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.25f, screenHeight/2 }, 30, 10);\n    circleA->restitution = 0.0f;\n    PhysicsBody circleB = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.5f, screenHeight/2 }, 30, 10);\n    circleB->restitution = 0.5f;\n    PhysicsBody circleC = CreatePhysicsBodyCircle((Vector2){ screenWidth*0.75f, screenHeight/2 }, 30, 10);\n    circleC->restitution = 0.9f;\n    \n    SetTargetFPS(60);\n    //--------------------------------------------------------------------------------------\n\n    // Main game loop\n    while (!WindowShouldClose())    // Detect window close button or ESC key\n    {\n        // Update\n        //----------------------------------------------------------------------------------\n        // ...\n        //----------------------------------------------------------------------------------\n\n        // Draw\n        //----------------------------------------------------------------------------------\n        BeginDrawing();\n\n            ClearBackground(BLACK);\n\n            DrawFPS(screenWidth - 90, screenHeight - 30);\n\n            // Draw created physics bodies\n            int bodiesCount = GetPhysicsBodiesCount();\n            for (int i = 0; i < bodiesCount; i++)\n            {\n                PhysicsBody body = GetPhysicsBody(i);\n\n                int vertexCount = GetPhysicsShapeVerticesCount(i);\n                for (int j = 0; j < vertexCount; j++)\n                {\n                    // Get physics bodies shape vertices to draw lines\n                    // Note: GetPhysicsShapeVertex() already calculates rotation transformations\n                    Vector2 vertexA = GetPhysicsShapeVertex(body, j);\n\n                    int jj = (((j + 1) < vertexCount) ? (j + 1) : 0);   // Get next vertex or first to close the shape\n                    Vector2 vertexB = GetPhysicsShapeVertex(body, jj);\n\n                    DrawLineV(vertexA, vertexB, GREEN);     // Draw a line between two vertex positions\n                }\n            }\n\n            DrawText(\"Restitution amount\", (screenWidth - MeasureText(\"Restitution amount\", 30))/2, 75, 30, WHITE);\n            DrawText(\"0%\", circleA->position.x - MeasureText(\"0%\", 20)/2, circleA->position.y - 7, 20, WHITE);\n            DrawText(\"50%\", circleB->position.x - MeasureText(\"50%\", 20)/2, circleB->position.y - 7, 20, WHITE);\n            DrawText(\"90%\", circleC->position.x - MeasureText(\"90%\", 20)/2, circleC->position.y - 7, 20, WHITE);\n\n            DrawText(\"Physac\", logoX, logoY, 30, WHITE);\n            DrawText(\"Powered by\", logoX + 50, logoY - 7, 10, WHITE);\n\n        EndDrawing();\n        //----------------------------------------------------------------------------------\n    }\n\n    // De-Initialization\n    //--------------------------------------------------------------------------------------   \n    ClosePhysics();       // Unitialize physics\n    \n    CloseWindow();        // Close window and OpenGL context\n    //--------------------------------------------------------------------------------------\n\n    return 0;\n}"
  },
  {
    "path": "examples/physics_shatter.c",
    "content": "/*******************************************************************************************\n*\n*   Physac - Body shatter\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread \n*           is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency \n*           on MinGW DLL (-static -lpthread)\n*\n*   Compile this program using:\n*       gcc -o $(NAME_PART).exe $(FILE_NAME) -s ..\\icon\\physac_icon -I. -I../src \n*           -I../src/external/raylib/src -static -lraylib -lopengl32 -lgdi32 -pthread -std=c99\n*   \n*   Copyright (c) 2016-2020 Victor Fisac (github: @victorfisac)\n*\n********************************************************************************************/\n\n#include \"raylib.h\"\n\n#define PHYSAC_IMPLEMENTATION\n#include \"../src/physac.h\"\n\n#define SHATTER_FORCE 200.0f\n\nint main()\n{\n    // Initialization\n    //--------------------------------------------------------------------------------------\n    int screenWidth = 800;\n    int screenHeight = 450;\n\n    SetConfigFlags(FLAG_MSAA_4X_HINT);\n    InitWindow(screenWidth, screenHeight, \"[physac] - Shatter demo\");\n\n    // Physac logo drawing position\n    int logoX = screenWidth - MeasureText(\"Physac\", 30) - 10;\n    int logoY = 15;\n    bool shatter = false;\n\n    // Initialize physics and default physics bodies\n    InitPhysics();\n    SetPhysicsGravity(0, 0);\n\n    // Create random polygon physics body to shatter\n    PhysicsBody shatterBody = CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10);\n    \n    SetTargetFPS(60);\n    //--------------------------------------------------------------------------------------\n\n    // Main game loop\n    while (!WindowShouldClose())    // Detect window close button or ESC key\n    {\n        // Update\n        //----------------------------------------------------------------------------------\n        if (IsKeyPressed(KEY_R))\n        {\n            ClosePhysics();\n\n            InitPhysics();\n            SetPhysicsGravity(0, 0);\n\n            CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10);\n        }\n        else if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))\n        {\n            // Note: some values need to be stored in variables due to asynchronous changes during main thread\n            int count = GetPhysicsBodiesCount();\n            \n            for (int i = count - 1; i >= 0; i--)\n            {\n                PhysicsBody currentBody = GetPhysicsBody(i);\n                \n                if (currentBody != NULL)\n                {\n                    PhysicsShatter(currentBody, GetMousePosition(), SHATTER_FORCE);\n                }\n            }\n        }\n        //----------------------------------------------------------------------------------\n\n        // Draw\n        //----------------------------------------------------------------------------------\n        BeginDrawing();\n\n            ClearBackground(BLACK);\n\n            // Draw created physics bodies\n            int bodiesCount = GetPhysicsBodiesCount();\n\n            for (int i = 0; i < bodiesCount; i++)\n            {\n                PhysicsBody currentBody = GetPhysicsBody(i);\n\n                // Check if the body is valid\n                if (currentBody != NULL)\n                {\n                    int vertexCount = GetPhysicsShapeVerticesCount(i);\n\n                    for (int j = 0; j < vertexCount; j++)\n                    {\n                        // Get physics bodies shape vertices to draw lines\n                        Vector2 vertexA = GetPhysicsShapeVertex(currentBody, j);\n\n                        int jj = (((j + 1) < vertexCount) ? (j + 1) : 0);   // Get next vertex or first to close the shape\n                        Vector2 vertexB = GetPhysicsShapeVertex(currentBody, jj);\n\n                        DrawLineV(vertexA, vertexB, GREEN);     // Draw a line between two vertex positions\n                    }\n                }\n            }\n\n            DrawText(\"Left mouse button in polygon area to shatter body\", 10, 10, 10, WHITE);\n            DrawText(\"Physac\", logoX, logoY, 30, WHITE);\n            DrawText(\"Powered by\", logoX + 50, logoY - 7, 10, WHITE);\n\n        EndDrawing();\n        //----------------------------------------------------------------------------------\n    }\n\n    // De-Initialization\n    //--------------------------------------------------------------------------------------   \n    ClosePhysics();       // Uninitialize physics\n    \n    CloseWindow();        // Close window and OpenGL context\n    //--------------------------------------------------------------------------------------\n\n    return 0;\n}"
  },
  {
    "path": "icon/physac.rc",
    "content": "GLFW_ICON ICON \"physac.ico\"\n\n1 VERSIONINFO\nFILEVERSION     1,0,0,0\nPRODUCTVERSION  1,0,0,0\nBEGIN\n  BLOCK \"StringFileInfo\"\n  BEGIN\n    BLOCK \"040904E4\"\n    BEGIN\n      VALUE \"CompanyName\", \"Victor Fisac Fuentes\"\n      VALUE \"FileDescription\", \"Physac - 2D physics header-only library for videogames\"\n      VALUE \"FileVersion\", \"1.0\"\n      VALUE \"InternalName\", \"physac\"\n      VALUE \"LegalCopyright\", \"(c) 2017 Victor Fisac. All rights reserved.\"\n      VALUE \"OriginalFilename\", \"physac.exe\"\n      VALUE \"ProductName\", \"Physac app\"\n      VALUE \"ProductVersion\", \"1.0\"\n    END\n  END\n  BLOCK \"VarFileInfo\"\n  BEGIN\n    VALUE \"Translation\", 0x409, 1252\t// English US\n  END\nEND"
  },
  {
    "path": "src/physac.h",
    "content": "/**********************************************************************************************\n*\n*   Physac v1.1 - 2D Physics library for videogames\n*\n*   DESCRIPTION:\n*\n*   Physac is a small 2D physics library written in pure C. The engine uses a fixed time-step thread loop\n*   to simluate physics. A physics step contains the following phases: get collision information,\n*   apply dynamics, collision solving and position correction. It uses a very simple struct for physic\n*   bodies with a position vector to be used in any 3D rendering API.\n*\n*   CONFIGURATION:\n*\n*   #define PHYSAC_IMPLEMENTATION\n*       Generates the implementation of the library into the included file.\n*       If not defined, the library is in header only mode and can be included in other headers\n*       or source files without problems. But only ONE file should hold the implementation.\n*\n*   #define PHYSAC_STATIC (defined by default)\n*       The generated implementation will stay private inside implementation file and all\n*       internal symbols and functions will only be visible inside that file.\n*\n*   #define PHYSAC_NO_THREADS\n*       The generated implementation won't include pthread library and user must create a secondary thread to call PhysicsThread().\n*       It is so important that the thread where PhysicsThread() is called must not have v-sync or any other CPU limitation.\n*\n*   #define PHYSAC_STANDALONE\n*       Avoid raylib.h header inclusion in this file. Data types defined on raylib are defined\n*       internally in the library and input management and drawing functions must be provided by\n*       the user (check library implementation for further details).\n*\n*   #define PHYSAC_DEBUG\n*       Traces log messages when creating and destroying physics bodies and detects errors in physics\n*       calculations and reference exceptions; it is useful for debug purposes\n*\n*   #define PHYSAC_MALLOC()\n*   #define PHYSAC_FREE()\n*       You can define your own malloc/free implementation replacing stdlib.h malloc()/free() functions.\n*       Otherwise it will include stdlib.h and use the C standard library malloc()/free() function.\n*\n*\n*   NOTE 1: Physac requires multi-threading, when InitPhysics() a second thread is created to manage physics calculations.\n*   NOTE 2: Physac requires static C library linkage to avoid dependency on MinGW DLL (-static -lpthread)\n*\n*   Use the following code to compile:\n*   gcc -o $(NAME_PART).exe $(FILE_NAME) -s -static -lraylib -lpthread -lopengl32 -lgdi32 -lwinmm -std=c99\n*\n*   VERY THANKS TO:\n*       - raysan5: helped with library design\n*       - ficoos: added support for Linux\n*       - R8D8: added support for Linux\n*       - jubalh: fixed implementation of time calculations\n*       - a3f: fixed implementation of time calculations\n*       - define-private-public: added support for OSX\n*       - pamarcos: fixed implementation of physics steps\n*       - noshbar: fixed some memory leaks\n*\n*\n*   LICENSE: zlib/libpng\n*\n*   Copyright (c) 2016-2025 Victor Fisac (github: @victorfisac)\n*\n*   This software is provided \"as-is\", without any express or implied warranty. In no event\n*   will the authors be held liable for any damages arising from the use of this software.\n*\n*   Permission is granted to anyone to use this software for any purpose, including commercial\n*   applications, and to alter it and redistribute it freely, subject to the following restrictions:\n*\n*     1. The origin of this software must not be misrepresented; you must not claim that you\n*     wrote the original software. If you use this software in a product, an acknowledgment\n*     in the product documentation would be appreciated but is not required.\n*\n*     2. Altered source versions must be plainly marked as such, and must not be misrepresented\n*     as being the original software.\n*\n*     3. This notice may not be removed or altered from any source distribution.\n*\n**********************************************************************************************/\n\n#if !defined(PHYSAC_H)\n#define PHYSAC_H\n\n// #define PHYSAC_STATIC\n// #define  PHYSAC_NO_THREADS\n// #define  PHYSAC_STANDALONE\n// #define  PHYSAC_DEBUG\n\n#if defined(PHYSAC_STATIC)\n    #define PHYSACDEF static            // Functions just visible to module including this file\n#else\n    #if defined(__cplusplus)\n        #define PHYSACDEF extern \"C\"    // Functions visible from other files (no name mangling of functions in C++)\n    #else\n        #define PHYSACDEF extern        // Functions visible from other files\n    #endif\n#endif\n\n//----------------------------------------------------------------------------------\n// Defines and Macros\n//----------------------------------------------------------------------------------\n#define     PHYSAC_MAX_BODIES               64\n#define     PHYSAC_MAX_MANIFOLDS            4096\n#define     PHYSAC_MAX_VERTICES             24\n#define     PHYSAC_CIRCLE_VERTICES          24\n\n#define     PHYSAC_FIXED_TIME               1.0f/60.0f\n#define     PHYSAC_COLLISION_ITERATIONS     20\n#define     PHYSAC_PENETRATION_ALLOWANCE    0.05f\n#define     PHYSAC_PENETRATION_CORRECTION   0.4f\n\n#define     PHYSAC_PI                       3.14159265358979323846\n#define     PHYSAC_DEG2RAD                  (PHYSAC_PI/180.0f)\n\n#define     PHYSAC_MALLOC(size)             malloc(size)\n#define     PHYSAC_FREE(ptr)                free(ptr)\n\n//----------------------------------------------------------------------------------\n// Types and Structures Definition\n// NOTE: Below types are required for PHYSAC_STANDALONE usage\n//----------------------------------------------------------------------------------\n#if defined(PHYSAC_STANDALONE)\n    // Vector2 type\n    typedef struct Vector2 {\n        float x;\n        float y;\n    } Vector2;\n\n    // Boolean type\n    #if !defined(_STDBOOL_H)\n        typedef enum { false, true } bool;\n        #define _STDBOOL_H\n    #endif\n#endif\n\ntypedef enum PhysicsShapeType { PHYSICS_CIRCLE, PHYSICS_POLYGON } PhysicsShapeType;\n\n// Previously defined to be used in PhysicsShape struct as circular dependencies\ntypedef struct PhysicsBodyData *PhysicsBody;\n\n// Mat2 type (used for polygon shape rotation matrix)\ntypedef struct Mat2 {\n    float m00;\n    float m01;\n    float m10;\n    float m11;\n} Mat2;\n\ntypedef struct PolygonData {\n    unsigned int vertexCount;                   // Current used vertex and normals count\n    Vector2 positions[PHYSAC_MAX_VERTICES];     // Polygon vertex positions vectors\n    Vector2 normals[PHYSAC_MAX_VERTICES];       // Polygon vertex normals vectors\n} PolygonData;\n\ntypedef struct PhysicsShape {\n    PhysicsShapeType type;                      // Physics shape type (circle or polygon)\n    PhysicsBody body;                           // Shape physics body reference\n    float radius;                               // Circle shape radius (used for circle shapes)\n    Mat2 transform;                             // Vertices transform matrix 2x2\n    PolygonData vertexData;                     // Polygon shape vertices position and normals data (just used for polygon shapes)\n} PhysicsShape;\n\ntypedef struct PhysicsBodyData {\n    unsigned int id;                            // Reference unique identifier\n    bool enabled;                               // Enabled dynamics state (collisions are calculated anyway)\n    Vector2 position;                           // Physics body shape pivot\n    Vector2 velocity;                           // Current linear velocity applied to position\n    Vector2 force;                              // Current linear force (reset to 0 every step)\n    float angularVelocity;                      // Current angular velocity applied to orient\n    float torque;                               // Current angular force (reset to 0 every step)\n    float orient;                               // Rotation in radians\n    float inertia;                              // Moment of inertia\n    float inverseInertia;                       // Inverse value of inertia\n    float mass;                                 // Physics body mass\n    float inverseMass;                          // Inverse value of mass\n    float staticFriction;                       // Friction when the body has not movement (0 to 1)\n    float dynamicFriction;                      // Friction when the body has movement (0 to 1)\n    float restitution;                          // Restitution coefficient of the body (0 to 1)\n    bool useGravity;                            // Apply gravity force to dynamics\n    bool isGrounded;                            // Physics grounded on other body state\n    bool freezeOrient;                          // Physics rotation constraint\n    PhysicsShape shape;                         // Physics body shape information (type, radius, vertices, normals)\n} PhysicsBodyData;\n\ntypedef struct PhysicsManifoldData {\n    unsigned int id;                            // Reference unique identifier\n    PhysicsBody bodyA;                          // Manifold first physics body reference\n    PhysicsBody bodyB;                          // Manifold second physics body reference\n    float penetration;                          // Depth of penetration from collision\n    Vector2 normal;                             // Normal direction vector from 'a' to 'b'\n    Vector2 contacts[2];                        // Points of contact during collision\n    unsigned int contactsCount;                 // Current collision number of contacts\n    float restitution;                          // Mixed restitution during collision\n    float dynamicFriction;                      // Mixed dynamic friction during collision\n    float staticFriction;                       // Mixed static friction during collision\n} PhysicsManifoldData, *PhysicsManifold;\n\n#if defined(__cplusplus)\nextern \"C\" {                                    // Prevents name mangling of functions\n#endif\n\n//----------------------------------------------------------------------------------\n// Module Functions Declaration\n//----------------------------------------------------------------------------------\nPHYSACDEF void InitPhysics(void);                                                                           // Initializes physics values, pointers and creates physics loop thread\nPHYSACDEF void RunPhysicsStep(void);                                                                        // Run physics step, to be used if PHYSICS_NO_THREADS is set in your main loop\nPHYSACDEF void SetPhysicsTimeStep(double delta);                                                            // Sets physics fixed time step in milliseconds. 1.666666 by default\nPHYSACDEF bool IsPhysicsEnabled(void);                                                                      // Returns true if physics thread is currently enabled\nPHYSACDEF void SetPhysicsGravity(float x, float y);                                                         // Sets physics global gravity force\nPHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density);                    // Creates a new circle physics body with generic parameters\nPHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density);    // Creates a new rectangle physics body with generic parameters\nPHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density);        // Creates a new polygon physics body with generic parameters\nPHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force);                                            // Adds a force to a physics body\nPHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount);                                            // Adds an angular force to a physics body\nPHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force);                             // Shatters a polygon shape physics body to little physics bodies with explosion force\nPHYSACDEF int GetPhysicsBodiesCount(void);                                                                  // Returns the current amount of created physics bodies\nPHYSACDEF PhysicsBody GetPhysicsBody(int index);                                                            // Returns a physics body of the bodies pool at a specific index\nPHYSACDEF int GetPhysicsShapeType(int index);                                                               // Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON)\nPHYSACDEF int GetPhysicsShapeVerticesCount(int index);                                                      // Returns the amount of vertices of a physics body shape\nPHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex);                                      // Returns transformed position of a body shape (body position + vertex transformed position)\nPHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians);                                     // Sets physics body shape transform based on radians parameter\nPHYSACDEF void DestroyPhysicsBody(PhysicsBody body);                                                        // Unitializes and destroy a physics body\nPHYSACDEF void ClosePhysics(void);                                                                          // Unitializes physics pointers and closes physics loop thread\n\n#if defined(__cplusplus)\n}\n#endif\n\n#endif // PHYSAC_H\n\n/***********************************************************************************\n*\n*   PHYSAC IMPLEMENTATION\n*\n************************************************************************************/\n\n#if defined(PHYSAC_IMPLEMENTATION)\n\n#if !defined(PHYSAC_NO_THREADS)\n    #include <pthread.h>            // Required for: pthread_t, pthread_create()\n#endif\n\n#if defined(PHYSAC_DEBUG)\n    #include <stdio.h>              // Required for: printf()\n#endif\n\n#include <stdlib.h>                 // Required for: malloc(), free(), srand(), rand()\n#include <math.h>                   // Required for: cosf(), sinf(), fabs(), sqrtf()\n#include <stdint.h>                 // Required for: uint64_t\n\n#if !defined(PHYSAC_STANDALONE)\n    #include \"raymath.h\"            // Required for: Vector2Add(), Vector2Subtract()\n#endif\n\n// Time management functionality\n#include <time.h>                   // Required for: time(), clock_gettime()\n#if defined(__linux__)\n    #if _POSIX_C_SOURCE < 199309L\n        #undef _POSIX_C_SOURCE\n        #define _POSIX_C_SOURCE 199309L // Required for CLOCK_MONOTONIC if compiled with c99 without gnu ext.\n    #endif\n    #include <sys/time.h>           // Required for: timespec\n#elif defined(__APPLE__)            // macOS also defines __MACH__\n    #include <mach/mach_time.h>     // Required for: mach_absolute_time()\n\n#elif defined(EMSCRIPTEN)           // Emscripten uses the browser's time functions\n    #include <emscripten.h>         // Required for: emscripten_get_now()\n#endif\n\n//----------------------------------------------------------------------------------\n// Defines and Macros\n//----------------------------------------------------------------------------------\n#define     min(a,b)                    (((a)<(b))?(a):(b))\n#define     max(a,b)                    (((a)>(b))?(a):(b))\n#define     PHYSAC_FLT_MAX              3.402823466e+38f\n#define     PHYSAC_EPSILON              0.000001f\n#define     PHYSAC_K                    1.0f/3.0f\n#define     PHYSAC_VECTOR_ZERO          (Vector2){ 0.0f, 0.0f }\n\n//----------------------------------------------------------------------------------\n// Global Variables Definition\n//----------------------------------------------------------------------------------\n#if !defined(PHYSAC_NO_THREADS)\nstatic pthread_t physicsThreadId;                           // Physics thread id\n#endif\nstatic unsigned int usedMemory = 0;                         // Total allocated dynamic memory\nstatic volatile bool physicsThreadEnabled = false;          // Physics thread enabled state\nstatic double baseTime = 0.0;                               // Offset time for MONOTONIC clock\nstatic double startTime = 0.0;                              // Start time in milliseconds\nstatic double deltaTime = 1.0/60.0/10.0 * 1000;             // Delta time used for physics steps, in milliseconds\nstatic double currentTime = 0.0;                            // Current time in milliseconds\nstatic uint64_t frequency = 0;                              // Hi-res clock frequency\n\nstatic double accumulator = 0.0;                            // Physics time step delta time accumulator\nstatic unsigned int stepsCount = 0;                         // Total physics steps processed\nstatic Vector2 gravityForce = { 0.0f, 9.81f };              // Physics world gravity force\nstatic PhysicsBody bodies[PHYSAC_MAX_BODIES];               // Physics bodies pointers array\nstatic unsigned int physicsBodiesCount = 0;                 // Physics world current bodies counter\nstatic PhysicsManifold contacts[PHYSAC_MAX_MANIFOLDS];      // Physics bodies pointers array\nstatic unsigned int physicsManifoldsCount = 0;              // Physics world current manifolds counter\n\n//----------------------------------------------------------------------------------\n// Module Internal Functions Declaration\n//----------------------------------------------------------------------------------\nstatic int FindAvailableBodyIndex();                                                                        // Finds a valid index for a new physics body initialization\nstatic PolygonData CreateRandomPolygon(float radius, int sides);                                            // Creates a random polygon shape with max vertex distance from polygon pivot\nstatic PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size);                                       // Creates a rectangle polygon shape based on a min and max positions\nstatic void *PhysicsLoop(void *arg);                                                                        // Physics loop thread function\nstatic void PhysicsStep(void);                                                                              // Physics steps calculations (dynamics, collisions and position corrections)\nstatic int FindAvailableManifoldIndex();                                                                    // Finds a valid index for a new manifold initialization\nstatic PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b);                                 // Creates a new physics manifold to solve collision\nstatic void DestroyPhysicsManifold(PhysicsManifold manifold);                                               // Unitializes and destroys a physics manifold\nstatic void SolvePhysicsManifold(PhysicsManifold manifold);                                                 // Solves a created physics manifold between two physics bodies\nstatic void SolveCircleToCircle(PhysicsManifold manifold);                                                  // Solves collision between two circle shape physics bodies\nstatic void SolveCircleToPolygon(PhysicsManifold manifold);                                                 // Solves collision between a circle to a polygon shape physics bodies\nstatic void SolvePolygonToCircle(PhysicsManifold manifold);                                                 // Solves collision between a polygon to a circle shape physics bodies\nstatic void SolveDifferentShapes(PhysicsManifold manifold, PhysicsBody bodyA, PhysicsBody bodyB);           // Solve collision between two different types of shapes\nstatic void SolvePolygonToPolygon(PhysicsManifold manifold);                                                // Solves collision between two polygons shape physics bodies\nstatic void IntegratePhysicsForces(PhysicsBody body);                                                       // Integrates physics forces into velocity\nstatic void InitializePhysicsManifolds(PhysicsManifold manifold);                                           // Initializes physics manifolds to solve collisions\nstatic void IntegratePhysicsImpulses(PhysicsManifold manifold);                                             // Integrates physics collisions impulses to solve collisions\nstatic void IntegratePhysicsVelocity(PhysicsBody body);                                                     // Integrates physics velocity into position and forces\nstatic void CorrectPhysicsPositions(PhysicsManifold manifold);                                              // Corrects physics bodies positions based on manifolds collision information\nstatic float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB);            // Finds polygon shapes axis least penetration\nstatic void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, PhysicsShape inc, int index);      // Finds two polygon shapes incident face\nstatic int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB);                                // Calculates clipping based on a normal and two faces\nstatic bool BiasGreaterThan(float valueA, float valueB);                                                    // Check if values are between bias range\nstatic Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3);                                      // Returns the barycenter of a triangle given by 3 points\n\nstatic void InitTimer(void);                                                                                // Initializes hi-resolution MONOTONIC timer\nstatic uint64_t GetTimeCount(void);                                                                         // Get hi-res MONOTONIC time measure in mseconds\nstatic double GetCurrTime(void);                                                                         // Get current time measure in milliseconds\n\n// Math functions\nstatic Vector2 MathCross(float value, Vector2 vector);                                                      // Returns the cross product of a vector and a value\nstatic float MathCrossVector2(Vector2 v1, Vector2 v2);                                                      // Returns the cross product of two vectors\nstatic float MathLenSqr(Vector2 vector);                                                                    // Returns the len square root of a vector\nstatic float MathDot(Vector2 v1, Vector2 v2);                                                               // Returns the dot product of two vectors\nstatic inline float DistSqr(Vector2 v1, Vector2 v2);                                                        // Returns the square root of distance between two vectors\nstatic void MathNormalize(Vector2 *vector);                                                                 // Returns the normalized values of a vector\n#if defined(PHYSAC_STANDALONE)\nstatic Vector2 Vector2Add(Vector2 v1, Vector2 v2);                                                          // Returns the sum of two given vectors\nstatic Vector2 Vector2Subtract(Vector2 v1, Vector2 v2);                                                     // Returns the subtract of two given vectors\n#endif\n\nstatic Mat2 Mat2Radians(float radians);                                                                     // Creates a matrix 2x2 from a given radians value\nstatic void Mat2Set(Mat2 *matrix, float radians);                                                           // Set values from radians to a created matrix 2x2\nstatic inline Mat2 Mat2Transpose(Mat2 matrix);                                                              // Returns the transpose of a given matrix 2x2\nstatic inline Vector2 Mat2MultiplyVector2(Mat2 matrix, Vector2 vector);                                     // Multiplies a vector by a matrix 2x2\n\n//----------------------------------------------------------------------------------\n// Module Functions Definition\n//----------------------------------------------------------------------------------\n// Initializes physics values, pointers and creates physics loop thread\nPHYSACDEF void InitPhysics(void)\n{\n    #if !defined(PHYSAC_NO_THREADS)\n        // NOTE: if defined, user will need to create a thread for PhysicsThread function manually\n        // Create physics thread using POSIXS thread libraries\n        pthread_create(&physicsThreadId, NULL, &PhysicsLoop, NULL);\n    #endif\n\n    // Initialize high resolution timer\n    InitTimer();\n\n    #if defined(PHYSAC_DEBUG)\n        printf(\"[PHYSAC] physics module initialized successfully\\n\");\n    #endif\n\n    accumulator = 0.0;\n}\n\n// Returns true if physics thread is currently enabled\nPHYSACDEF bool IsPhysicsEnabled(void)\n{\n    return physicsThreadEnabled;\n}\n\n// Sets physics global gravity force\nPHYSACDEF void SetPhysicsGravity(float x, float y)\n{\n    gravityForce.x = x;\n    gravityForce.y = y;\n}\n\n// Creates a new circle physics body with generic parameters\nPHYSACDEF PhysicsBody CreatePhysicsBodyCircle(Vector2 pos, float radius, float density)\n{\n    PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData));\n    usedMemory += sizeof(PhysicsBodyData);\n\n    int newId = FindAvailableBodyIndex();\n    if (newId != -1)\n    {\n        // Initialize new body with generic values\n        newBody->id = newId;\n        newBody->enabled = true;\n        newBody->position = pos;\n        newBody->velocity = PHYSAC_VECTOR_ZERO;\n        newBody->force = PHYSAC_VECTOR_ZERO;\n        newBody->angularVelocity = 0.0f;\n        newBody->torque = 0.0f;\n        newBody->orient = 0.0f;\n        newBody->shape.type = PHYSICS_CIRCLE;\n        newBody->shape.body = newBody;\n        newBody->shape.radius = radius;\n        newBody->shape.transform = Mat2Radians(0.0f);\n        newBody->shape.vertexData = (PolygonData) { 0 };\n\n        newBody->mass = PHYSAC_PI*radius*radius*density;\n        newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);\n        newBody->inertia = newBody->mass*radius*radius;\n        newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);\n        newBody->staticFriction = 0.4f;\n        newBody->dynamicFriction = 0.2f;\n        newBody->restitution = 0.0f;\n        newBody->useGravity = true;\n        newBody->isGrounded = false;\n        newBody->freezeOrient = false;\n\n        // Add new body to bodies pointers array and update bodies count\n        bodies[physicsBodiesCount] = newBody;\n        physicsBodiesCount++;\n\n        #if defined(PHYSAC_DEBUG)\n            printf(\"[PHYSAC] created polygon physics body id %i\\n\", newBody->id);\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] new physics body creation failed because there is any available id to use\\n\");\n    #endif\n\n    return newBody;\n}\n\n// Creates a new rectangle physics body with generic parameters\nPHYSACDEF PhysicsBody CreatePhysicsBodyRectangle(Vector2 pos, float width, float height, float density)\n{\n    PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData));\n    usedMemory += sizeof(PhysicsBodyData);\n\n    int newId = FindAvailableBodyIndex();\n    if (newId != -1)\n    {\n        // Initialize new body with generic values\n        newBody->id = newId;\n        newBody->enabled = true;\n        newBody->position = pos;\n        newBody->velocity = (Vector2){ 0.0f };\n        newBody->force = (Vector2){ 0.0f };\n        newBody->angularVelocity = 0.0f;\n        newBody->torque = 0.0f;\n        newBody->orient = 0.0f;\n        newBody->shape.type = PHYSICS_POLYGON;\n        newBody->shape.body = newBody;\n        newBody->shape.radius = 0.0f;\n        newBody->shape.transform = Mat2Radians(0.0f);\n        newBody->shape.vertexData = CreateRectanglePolygon(pos, (Vector2){ width, height });\n\n        // Calculate centroid and moment of inertia\n        Vector2 center = { 0.0f, 0.0f };\n        float area = 0.0f;\n        float inertia = 0.0f;\n\n        for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)\n        {\n            // Triangle vertices, third vertex implied as (0, 0)\n            Vector2 p1 = newBody->shape.vertexData.positions[i];\n            int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0);\n            Vector2 p2 = newBody->shape.vertexData.positions[nextIndex];\n\n            float D = MathCrossVector2(p1, p2);\n            float triangleArea = D/2;\n\n            area += triangleArea;\n\n            // Use area to weight the centroid average, not just vertex position\n            center.x += triangleArea*PHYSAC_K*(p1.x + p2.x);\n            center.y += triangleArea*PHYSAC_K*(p1.y + p2.y);\n\n            float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x;\n            float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y;\n            inertia += (0.25f*PHYSAC_K*D)*(intx2 + inty2);\n        }\n\n        center.x *= 1.0f/area;\n        center.y *= 1.0f/area;\n\n        // Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)\n        // Note: this is not really necessary\n        for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)\n        {\n            newBody->shape.vertexData.positions[i].x -= center.x;\n            newBody->shape.vertexData.positions[i].y -= center.y;\n        }\n\n        newBody->mass = density*area;\n        newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);\n        newBody->inertia = density*inertia;\n        newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);\n        newBody->staticFriction = 0.4f;\n        newBody->dynamicFriction = 0.2f;\n        newBody->restitution = 0.0f;\n        newBody->useGravity = true;\n        newBody->isGrounded = false;\n        newBody->freezeOrient = false;\n\n        // Add new body to bodies pointers array and update bodies count\n        bodies[physicsBodiesCount] = newBody;\n        physicsBodiesCount++;\n\n        #if defined(PHYSAC_DEBUG)\n            printf(\"[PHYSAC] created polygon physics body id %i\\n\", newBody->id);\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] new physics body creation failed because there is any available id to use\\n\");\n    #endif\n\n    return newBody;\n}\n\n// Creates a new polygon physics body with generic parameters\nPHYSACDEF PhysicsBody CreatePhysicsBodyPolygon(Vector2 pos, float radius, int sides, float density)\n{\n    PhysicsBody newBody = (PhysicsBody)PHYSAC_MALLOC(sizeof(PhysicsBodyData));\n    usedMemory += sizeof(PhysicsBodyData);\n\n    int newId = FindAvailableBodyIndex();\n    if (newId != -1)\n    {\n        // Initialize new body with generic values\n        newBody->id = newId;\n        newBody->enabled = true;\n        newBody->position = pos;\n        newBody->velocity = PHYSAC_VECTOR_ZERO;\n        newBody->force = PHYSAC_VECTOR_ZERO;\n        newBody->angularVelocity = 0.0f;\n        newBody->torque = 0.0f;\n        newBody->orient = 0.0f;\n        newBody->shape.type = PHYSICS_POLYGON;\n        newBody->shape.body = newBody;\n        newBody->shape.transform = Mat2Radians(0.0f);\n        newBody->shape.vertexData = CreateRandomPolygon(radius, sides);\n\n        // Calculate centroid and moment of inertia\n        Vector2 center = { 0.0f, 0.0f };\n        float area = 0.0f;\n        float inertia = 0.0f;\n\n        for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)\n        {\n            // Triangle vertices, third vertex implied as (0, 0)\n            Vector2 position1 = newBody->shape.vertexData.positions[i];\n            int nextIndex = (((i + 1) < newBody->shape.vertexData.vertexCount) ? (i + 1) : 0);\n            Vector2 position2 = newBody->shape.vertexData.positions[nextIndex];\n\n            float cross = MathCrossVector2(position1, position2);\n            float triangleArea = cross/2;\n\n            area += triangleArea;\n\n            // Use area to weight the centroid average, not just vertex position\n            center.x += triangleArea*PHYSAC_K*(position1.x + position2.x);\n            center.y += triangleArea*PHYSAC_K*(position1.y + position2.y);\n\n            float intx2 = position1.x*position1.x + position2.x*position1.x + position2.x*position2.x;\n            float inty2 = position1.y*position1.y + position2.y*position1.y + position2.y*position2.y;\n            inertia += (0.25f*PHYSAC_K*cross)*(intx2 + inty2);\n        }\n\n        center.x *= 1.0f/area;\n        center.y *= 1.0f/area;\n\n        // Translate vertices to centroid (make the centroid (0, 0) for the polygon in model space)\n        // Note: this is not really necessary\n        for (int i = 0; i < newBody->shape.vertexData.vertexCount; i++)\n        {\n            newBody->shape.vertexData.positions[i].x -= center.x;\n            newBody->shape.vertexData.positions[i].y -= center.y;\n        }\n\n        newBody->mass = density*area;\n        newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);\n        newBody->inertia = density*inertia;\n        newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);\n        newBody->staticFriction = 0.4f;\n        newBody->dynamicFriction = 0.2f;\n        newBody->restitution = 0.0f;\n        newBody->useGravity = true;\n        newBody->isGrounded = false;\n        newBody->freezeOrient = false;\n\n        // Add new body to bodies pointers array and update bodies count\n        bodies[physicsBodiesCount] = newBody;\n        physicsBodiesCount++;\n\n        #if defined(PHYSAC_DEBUG)\n            printf(\"[PHYSAC] created polygon physics body id %i\\n\", newBody->id);\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] new physics body creation failed because there is any available id to use\\n\");\n    #endif\n\n    return newBody;\n}\n\n// Adds a force to a physics body\nPHYSACDEF void PhysicsAddForce(PhysicsBody body, Vector2 force)\n{\n    if (body != NULL)\n        body->force = Vector2Add(body->force, force);\n}\n\n// Adds an angular force to a physics body\nPHYSACDEF void PhysicsAddTorque(PhysicsBody body, float amount)\n{\n    if (body != NULL)\n        body->torque += amount;\n}\n\n// Shatters a polygon shape physics body to little physics bodies with explosion force\nPHYSACDEF void PhysicsShatter(PhysicsBody body, Vector2 position, float force)\n{\n    if (body != NULL)\n    {\n        if (body->shape.type == PHYSICS_POLYGON)\n        {\n            PolygonData vertexData = body->shape.vertexData;\n            bool collision = false;\n\n            for (int i = 0; i < vertexData.vertexCount; i++)\n            {\n                Vector2 positionA = body->position;\n                Vector2 positionB = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[i]));\n                int nextIndex = (((i + 1) < vertexData.vertexCount) ? (i + 1) : 0);\n                Vector2 positionC = Mat2MultiplyVector2(body->shape.transform, Vector2Add(body->position, vertexData.positions[nextIndex]));\n\n                // Check collision between each triangle\n                float alpha = ((positionB.y - positionC.y)*(position.x - positionC.x) + (positionC.x - positionB.x)*(position.y - positionC.y))/\n                              ((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y));\n\n                float beta = ((positionC.y - positionA.y)*(position.x - positionC.x) + (positionA.x - positionC.x)*(position.y - positionC.y))/\n                             ((positionB.y - positionC.y)*(positionA.x - positionC.x) + (positionC.x - positionB.x)*(positionA.y - positionC.y));\n\n                float gamma = 1.0f - alpha - beta;\n\n                if ((alpha > 0.0f) && (beta > 0.0f) && (gamma > 0.0f))\n                {\n                    collision = true;\n                    break;\n                }\n            }\n\n            if (collision)\n            {\n                int count = vertexData.vertexCount;\n                Vector2 bodyPos = body->position;\n                Vector2 *vertices = (Vector2*)PHYSAC_MALLOC(sizeof(Vector2) * count);\n                Mat2 trans = body->shape.transform;\n                \n                for (int i = 0; i < count; i++)\n                    vertices[i] = vertexData.positions[i];\n\n                // Destroy shattered physics body\n                DestroyPhysicsBody(body);\n\n                for (int i = 0; i < count; i++)\n                {\n                    int nextIndex = (((i + 1) < count) ? (i + 1) : 0);\n                    Vector2 center = TriangleBarycenter(vertices[i], vertices[nextIndex], PHYSAC_VECTOR_ZERO);\n                    center = Vector2Add(bodyPos, center);\n                    Vector2 offset = Vector2Subtract(center, bodyPos);\n\n                    PhysicsBody newBody = CreatePhysicsBodyPolygon(center, 10, 3, 10);     // Create polygon physics body with relevant values\n\n                    PolygonData newData = { 0 };\n                    newData.vertexCount = 3;\n\n                    newData.positions[0] = Vector2Subtract(vertices[i], offset);\n                    newData.positions[1] = Vector2Subtract(vertices[nextIndex], offset);\n                    newData.positions[2] = Vector2Subtract(position, center);\n\n                    // Separate vertices to avoid unnecessary physics collisions\n                    newData.positions[0].x *= 0.95f;\n                    newData.positions[0].y *= 0.95f;\n                    newData.positions[1].x *= 0.95f;\n                    newData.positions[1].y *= 0.95f;\n                    newData.positions[2].x *= 0.95f;\n                    newData.positions[2].y *= 0.95f;\n\n                    // Calculate polygon faces normals\n                    for (int j = 0; j < newData.vertexCount; j++)\n                    {\n                        int nextVertex = (((j + 1) < newData.vertexCount) ? (j + 1) : 0);\n                        Vector2 face = Vector2Subtract(newData.positions[nextVertex], newData.positions[j]);\n\n                        newData.normals[j] = (Vector2){ face.y, -face.x };\n                        MathNormalize(&newData.normals[j]);\n                    }\n\n                    // Apply computed vertex data to new physics body shape\n                    newBody->shape.vertexData = newData;\n                    newBody->shape.transform = trans;\n\n                    // Calculate centroid and moment of inertia\n                    center = PHYSAC_VECTOR_ZERO;\n                    float area = 0.0f;\n                    float inertia = 0.0f;\n\n                    for (int j = 0; j < newBody->shape.vertexData.vertexCount; j++)\n                    {\n                        // Triangle vertices, third vertex implied as (0, 0)\n                        Vector2 p1 = newBody->shape.vertexData.positions[j];\n                        int nextVertex = (((j + 1) < newBody->shape.vertexData.vertexCount) ? (j + 1) : 0);\n                        Vector2 p2 = newBody->shape.vertexData.positions[nextVertex];\n\n                        float D = MathCrossVector2(p1, p2);\n                        float triangleArea = D/2;\n\n                        area += triangleArea;\n\n                        // Use area to weight the centroid average, not just vertex position\n                        center.x += triangleArea*PHYSAC_K*(p1.x + p2.x);\n                        center.y += triangleArea*PHYSAC_K*(p1.y + p2.y);\n\n                        float intx2 = p1.x*p1.x + p2.x*p1.x + p2.x*p2.x;\n                        float inty2 = p1.y*p1.y + p2.y*p1.y + p2.y*p2.y;\n                        inertia += (0.25f*PHYSAC_K*D)*(intx2 + inty2);\n                    }\n\n                    center.x *= 1.0f/area;\n                    center.y *= 1.0f/area;\n\n                    newBody->mass = area;\n                    newBody->inverseMass = ((newBody->mass != 0.0f) ? 1.0f/newBody->mass : 0.0f);\n                    newBody->inertia = inertia;\n                    newBody->inverseInertia = ((newBody->inertia != 0.0f) ? 1.0f/newBody->inertia : 0.0f);\n\n                    // Calculate explosion force direction\n                    Vector2 pointA = newBody->position;\n                    Vector2 pointB = Vector2Subtract(newData.positions[1], newData.positions[0]);\n                    pointB.x /= 2.0f;\n                    pointB.y /= 2.0f;\n                    Vector2 forceDirection = Vector2Subtract(Vector2Add(pointA, Vector2Add(newData.positions[0], pointB)), newBody->position);\n                    MathNormalize(&forceDirection);\n                    forceDirection.x *= force;\n                    forceDirection.y *= force;\n\n                    // Apply force to new physics body\n                    PhysicsAddForce(newBody, forceDirection);\n                }\n\n                PHYSAC_FREE(vertices);\n            }\n        }\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] error when trying to shatter a null reference physics body\");\n    #endif\n}\n\n// Returns the current amount of created physics bodies\nPHYSACDEF int GetPhysicsBodiesCount(void)\n{\n    return physicsBodiesCount;\n}\n\n// Returns a physics body of the bodies pool at a specific index\nPHYSACDEF PhysicsBody GetPhysicsBody(int index)\n{\n    if (index < physicsBodiesCount)\n    {\n        if (bodies[index] == NULL)\n        {\n            #if defined(PHYSAC_DEBUG)\n                printf(\"[PHYSAC] error when trying to get a null reference physics body\");\n            #endif\n        }\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] physics body index is out of bounds\");\n    #endif\n\n    return bodies[index];\n}\n\n// Returns the physics body shape type (PHYSICS_CIRCLE or PHYSICS_POLYGON)\nPHYSACDEF int GetPhysicsShapeType(int index)\n{\n    int result = -1;\n\n    if (index < physicsBodiesCount)\n    {\n        if (bodies[index] != NULL) \n            result = bodies[index]->shape.type;\n\n        #if defined(PHYSAC_DEBUG)\n            else\n                printf(\"[PHYSAC] error when trying to get a null reference physics body\");\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] physics body index is out of bounds\");\n    #endif\n\n    return result;\n}\n\n// Returns the amount of vertices of a physics body shape\nPHYSACDEF int GetPhysicsShapeVerticesCount(int index)\n{\n    int result = 0;\n\n    if (index < physicsBodiesCount)\n    {\n        if (bodies[index] != NULL)\n        {\n            switch (bodies[index]->shape.type)\n            {\n                case PHYSICS_CIRCLE: result = PHYSAC_CIRCLE_VERTICES; break;\n                case PHYSICS_POLYGON: result = bodies[index]->shape.vertexData.vertexCount; break;\n                default: break;\n            }\n        }\n        #if defined(PHYSAC_DEBUG)\n            else\n                printf(\"[PHYSAC] error when trying to get a null reference physics body\");\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] physics body index is out of bounds\");\n    #endif\n\n    return result;\n}\n\n// Returns transformed position of a body shape (body position + vertex transformed position)\nPHYSACDEF Vector2 GetPhysicsShapeVertex(PhysicsBody body, int vertex)\n{\n    Vector2 position = { 0.0f, 0.0f };\n\n    if (body != NULL)\n    {\n        switch (body->shape.type)\n        {\n            case PHYSICS_CIRCLE:\n            {\n                position.x = body->position.x + cosf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius;\n                position.y = body->position.y + sinf(360.0f/PHYSAC_CIRCLE_VERTICES*vertex*PHYSAC_DEG2RAD)*body->shape.radius;\n            } break;\n            case PHYSICS_POLYGON:\n            {\n                PolygonData vertexData = body->shape.vertexData;\n                position = Vector2Add(body->position, Mat2MultiplyVector2(body->shape.transform, vertexData.positions[vertex]));\n            } break;\n            default: break;\n        }\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] error when trying to get a null reference physics body\");\n    #endif\n\n    return position;\n}\n\n// Sets physics body shape transform based on radians parameter\nPHYSACDEF void SetPhysicsBodyRotation(PhysicsBody body, float radians)\n{\n    if (body != NULL)\n    {\n        body->orient = radians;\n\n        if (body->shape.type == PHYSICS_POLYGON)\n            body->shape.transform = Mat2Radians(radians);\n    }\n}\n\n// Unitializes and destroys a physics body\nPHYSACDEF void DestroyPhysicsBody(PhysicsBody body)\n{\n    if (body != NULL)\n    {\n        int id = body->id;\n        int index = -1;\n\n        for (int i = 0; i < physicsBodiesCount; i++)\n        {\n            if (bodies[i]->id == id)\n            {\n                index = i;\n                break;\n            }\n        }\n\n        if (index == -1)\n        {\n            #if defined(PHYSAC_DEBUG)\n                printf(\"[PHYSAC] Not possible to find body id %i in pointers array\\n\", id);\n            #endif\n            return;\n        }\n\n        // Free body allocated memory\n        PHYSAC_FREE(body);\n        usedMemory -= sizeof(PhysicsBodyData);\n        bodies[index] = NULL;\n\n        // Reorder physics bodies pointers array and its catched index\n        for (int i = index; i < physicsBodiesCount; i++)\n        {\n            if ((i + 1) < physicsBodiesCount)\n                bodies[i] = bodies[i + 1];\n        }\n\n        // Update physics bodies count\n        physicsBodiesCount--;\n\n        #if defined(PHYSAC_DEBUG)\n            printf(\"[PHYSAC] destroyed physics body id %i\\n\", id);\n        #endif\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] error trying to destroy a null referenced body\\n\");\n    #endif\n}\n\n// Unitializes physics pointers and exits physics loop thread\nPHYSACDEF void ClosePhysics(void)\n{\n    // Exit physics loop thread\n    physicsThreadEnabled = false;\n\n    #if !defined(PHYSAC_NO_THREADS)\n        pthread_join(physicsThreadId, NULL);\n    #endif\n\n    // Unitialize physics manifolds dynamic memory allocations\n    for (int i = physicsManifoldsCount - 1; i >= 0; i--)\n        DestroyPhysicsManifold(contacts[i]);\n\n    // Unitialize physics bodies dynamic memory allocations\n    for (int i = physicsBodiesCount - 1; i >= 0; i--)\n        DestroyPhysicsBody(bodies[i]);\n\n    #if defined(PHYSAC_DEBUG)\n        if (physicsBodiesCount > 0 || usedMemory != 0)\n            printf(\"[PHYSAC] physics module closed with %i still allocated bodies [MEMORY: %i bytes]\\n\", physicsBodiesCount, usedMemory);\n        else if (physicsManifoldsCount > 0 || usedMemory != 0)\n            printf(\"[PHYSAC] physics module closed with %i still allocated manifolds [MEMORY: %i bytes]\\n\", physicsManifoldsCount, usedMemory);\n        else\n            printf(\"[PHYSAC] physics module closed successfully\\n\");\n    #endif\n}\n\n//----------------------------------------------------------------------------------\n// Module Internal Functions Definition\n//----------------------------------------------------------------------------------\n// Finds a valid index for a new physics body initialization\nstatic int FindAvailableBodyIndex()\n{\n    int index = -1;\n    for (int i = 0; i < PHYSAC_MAX_BODIES; i++)\n    {\n        int currentId = i;\n\n        // Check if current id already exist in other physics body\n        for (int k = 0; k < physicsBodiesCount; k++)\n        {\n            if (bodies[k]->id == currentId)\n            {\n                currentId++;\n                break;\n            }\n        }\n\n        // If it is not used, use it as new physics body id\n        if (currentId == i)\n        {\n            index = i;\n            break;\n        }\n    }\n\n    return index;\n}\n\n// Creates a random polygon shape with max vertex distance from polygon pivot\nstatic PolygonData CreateRandomPolygon(float radius, int sides)\n{\n    PolygonData data = { 0 };\n    data.vertexCount = sides;\n\n    // Calculate polygon vertices positions\n    for (int i = 0; i < data.vertexCount; i++)\n    {\n        data.positions[i].x = cosf(360.0f/sides*i*PHYSAC_DEG2RAD)*radius;\n        data.positions[i].y = sinf(360.0f/sides*i*PHYSAC_DEG2RAD)*radius;\n    }\n\n    // Calculate polygon faces normals\n    for (int i = 0; i < data.vertexCount; i++)\n    {\n        int nextIndex = (((i + 1) < sides) ? (i + 1) : 0);\n        Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]);\n\n        data.normals[i] = (Vector2){ face.y, -face.x };\n        MathNormalize(&data.normals[i]);\n    }\n\n    return data;\n}\n\n// Creates a rectangle polygon shape based on a min and max positions\nstatic PolygonData CreateRectanglePolygon(Vector2 pos, Vector2 size)\n{\n    PolygonData data = { 0 };\n    data.vertexCount = 4;\n\n    // Calculate polygon vertices positions\n    data.positions[0] = (Vector2){ pos.x + size.x/2, pos.y - size.y/2 };\n    data.positions[1] = (Vector2){ pos.x + size.x/2, pos.y + size.y/2 };\n    data.positions[2] = (Vector2){ pos.x - size.x/2, pos.y + size.y/2 };\n    data.positions[3] = (Vector2){ pos.x - size.x/2, pos.y - size.y/2 };\n\n    // Calculate polygon faces normals\n    for (int i = 0; i < data.vertexCount; i++)\n    {\n        int nextIndex = (((i + 1) < data.vertexCount) ? (i + 1) : 0);\n        Vector2 face = Vector2Subtract(data.positions[nextIndex], data.positions[i]);\n\n        data.normals[i] = (Vector2){ face.y, -face.x };\n        MathNormalize(&data.normals[i]);\n    }\n\n    return data;\n}\n\n// Physics loop thread function\nstatic void *PhysicsLoop(void *arg)\n{\n    #if defined(PHYSAC_DEBUG)\n        printf(\"[PHYSAC] physics thread created successfully\\n\");\n    #endif\n\n    // Initialize physics loop thread values\n    physicsThreadEnabled = true;\n\n    // Physics update loop\n    while (physicsThreadEnabled)\n    {\n        RunPhysicsStep();\n\n        struct timespec req = { 0 };\n        req.tv_sec = 0;\n        req.tv_nsec = PHYSAC_FIXED_TIME*1000*1000;\n\n        nanosleep(&req, NULL);\n    }\n\n    return 0;\n}\n\n// Physics steps calculations (dynamics, collisions and position corrections)\nstatic void PhysicsStep(void)\n{\n    // Update current steps count\n    stepsCount++;\n\n    // Clear previous generated collisions information\n    for (int i = physicsManifoldsCount - 1; i >= 0; i--)\n    {\n        PhysicsManifold manifold = contacts[i];\n        \n        if (manifold != NULL)\n            DestroyPhysicsManifold(manifold);\n    }\n\n    // Reset physics bodies grounded state\n    for (int i = 0; i < physicsBodiesCount; i++)\n    {\n        PhysicsBody body = bodies[i];\n        body->isGrounded = false;\n    }\n\n    // Generate new collision information\n    for (int i = 0; i < physicsBodiesCount; i++)\n    {\n        PhysicsBody bodyA = bodies[i];\n\n        if (bodyA != NULL)\n        {\n            for (int j = i + 1; j < physicsBodiesCount; j++)\n            {\n                PhysicsBody bodyB = bodies[j];\n\n                if (bodyB != NULL)\n                {\n                    if ((bodyA->inverseMass == 0) && (bodyB->inverseMass == 0))\n                        continue;\n\n                    PhysicsManifold manifold = CreatePhysicsManifold(bodyA, bodyB);\n                    SolvePhysicsManifold(manifold);\n\n                    if (manifold->contactsCount > 0)\n                    {\n                        // Create a new manifold with same information as previously solved manifold and add it to the manifolds pool last slot\n                        PhysicsManifold newManifold = CreatePhysicsManifold(bodyA, bodyB);\n                        newManifold->penetration = manifold->penetration;\n                        newManifold->normal = manifold->normal;\n                        newManifold->contacts[0] = manifold->contacts[0];\n                        newManifold->contacts[1] = manifold->contacts[1];\n                        newManifold->contactsCount = manifold->contactsCount;\n                        newManifold->restitution = manifold->restitution;\n                        newManifold->dynamicFriction = manifold->dynamicFriction;\n                        newManifold->staticFriction = manifold->staticFriction;\n                    }\n                }\n            }\n        }\n    }\n\n    // Integrate forces to physics bodies\n    for (int i = 0; i < physicsBodiesCount; i++)\n    {\n        PhysicsBody body = bodies[i];\n        \n        if (body != NULL)\n            IntegratePhysicsForces(body);\n    }\n\n    // Initialize physics manifolds to solve collisions\n    for (int i = 0; i < physicsManifoldsCount; i++)\n    {\n        PhysicsManifold manifold = contacts[i];\n        \n        if (manifold != NULL)\n            InitializePhysicsManifolds(manifold);\n    }\n\n    // Integrate physics collisions impulses to solve collisions\n    for (int i = 0; i < PHYSAC_COLLISION_ITERATIONS; i++)\n    {\n        for (int j = 0; j < physicsManifoldsCount; j++)\n        {\n            PhysicsManifold manifold = contacts[j];\n            \n            if (manifold != NULL)\n                IntegratePhysicsImpulses(manifold);\n        }\n    }\n\n    // Integrate velocity to physics bodies\n    for (int i = 0; i < physicsBodiesCount; i++)\n    {\n        PhysicsBody body = bodies[i];\n        \n        if (body != NULL)\n            IntegratePhysicsVelocity(body);\n    }\n\n    // Correct physics bodies positions based on manifolds collision information\n    for (int i = 0; i < physicsManifoldsCount; i++)\n    {\n        PhysicsManifold manifold = contacts[i];\n        \n        if (manifold != NULL)\n            CorrectPhysicsPositions(manifold);\n    }\n\n    // Clear physics bodies forces\n    for (int i = 0; i < physicsBodiesCount; i++)\n    {\n        PhysicsBody body = bodies[i];\n        \n        if (body != NULL)\n        {\n            body->force = PHYSAC_VECTOR_ZERO;\n            body->torque = 0.0f;\n        }\n    }\n}\n\n// Wrapper to ensure PhysicsStep is run with at a fixed time step\nPHYSACDEF void RunPhysicsStep(void)\n{\n    // Calculate current time\n    currentTime = GetCurrTime();\n\n    // Calculate current delta time\n    double delta = currentTime - startTime;\n\n    // Store the time elapsed since the last frame began\n    accumulator += delta;\n\n    // Fixed time stepping loop\n    while (accumulator >= deltaTime)\n    {\n        PhysicsStep();\n        accumulator -= deltaTime;\n    }\n\n    // Record the starting of this frame\n    startTime = currentTime;\n}\n\nPHYSACDEF void SetPhysicsTimeStep(double delta)\n{\n    deltaTime = delta;\n}\n\n// Finds a valid index for a new manifold initialization\nstatic int FindAvailableManifoldIndex()\n{\n    int id = physicsManifoldsCount + 1;\n\n    if (id >= PHYSAC_MAX_MANIFOLDS)\n    {\n        return -1;\n    }\n\n    return id;\n}\n\n// Creates a new physics manifold to solve collision\nstatic PhysicsManifold CreatePhysicsManifold(PhysicsBody a, PhysicsBody b)\n{\n    PhysicsManifold newManifold = (PhysicsManifold)PHYSAC_MALLOC(sizeof(PhysicsManifoldData));\n    usedMemory += sizeof(PhysicsManifoldData);\n\n    int newId = FindAvailableManifoldIndex();\n    if (newId != -1)\n    {\n        // Initialize new manifold with generic values\n        newManifold->id = newId;\n        newManifold->bodyA = a;\n        newManifold->bodyB = b;\n        newManifold->penetration = 0;\n        newManifold->normal = PHYSAC_VECTOR_ZERO;\n        newManifold->contacts[0] = PHYSAC_VECTOR_ZERO;\n        newManifold->contacts[1] = PHYSAC_VECTOR_ZERO;\n        newManifold->contactsCount = 0;\n        newManifold->restitution = 0.0f;\n        newManifold->dynamicFriction = 0.0f;\n        newManifold->staticFriction = 0.0f;\n\n        // Add new body to bodies pointers array and update bodies count\n        contacts[physicsManifoldsCount] = newManifold;\n        physicsManifoldsCount++;\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] new physics manifold creation failed because there is any available id to use\\n\");\n    #endif\n\n    return newManifold;\n}\n\n// Unitializes and destroys a physics manifold\nstatic void DestroyPhysicsManifold(PhysicsManifold manifold)\n{\n    if (manifold != NULL)\n    {\n        int id = manifold->id;\n        int index = -1;\n\n        for (int i = 0; i < physicsManifoldsCount; i++)\n        {\n            if (contacts[i]->id == id)\n            {\n                index = i;\n                break;\n            }\n        }\n\n        if (index == -1)\n        {\n            #if defined(PHYSAC_DEBUG)\n                printf(\"[PHYSAC] Not possible to manifold id %i in pointers array\\n\", id);\n            #endif\n            return;\n        }      \n\n        // Free manifold allocated memory\n        PHYSAC_FREE(manifold);\n        usedMemory -= sizeof(PhysicsManifoldData);\n        contacts[index] = NULL;\n\n        // Reorder physics manifolds pointers array and its catched index\n        for (int i = index; i < physicsManifoldsCount; i++)\n        {\n            if ((i + 1) < physicsManifoldsCount)\n                contacts[i] = contacts[i + 1];\n        }\n\n        // Update physics manifolds count\n        physicsManifoldsCount--;\n    }\n    #if defined(PHYSAC_DEBUG)\n        else\n            printf(\"[PHYSAC] error trying to destroy a null referenced manifold\\n\");\n    #endif\n}\n\n// Solves a created physics manifold between two physics bodies\nstatic void SolvePhysicsManifold(PhysicsManifold manifold)\n{\n    switch (manifold->bodyA->shape.type)\n    {\n        case PHYSICS_CIRCLE:\n        {\n            switch (manifold->bodyB->shape.type)\n            {\n                case PHYSICS_CIRCLE: SolveCircleToCircle(manifold); break;\n                case PHYSICS_POLYGON: SolveCircleToPolygon(manifold); break;\n                default: break;\n            }\n        } break;\n        case PHYSICS_POLYGON:\n        {\n            switch (manifold->bodyB->shape.type)\n            {\n                case PHYSICS_CIRCLE: SolvePolygonToCircle(manifold); break;\n                case PHYSICS_POLYGON: SolvePolygonToPolygon(manifold); break;\n                default: break;\n            }\n        } break;\n        default: break;\n    }\n\n    // Update physics body grounded state if normal direction is down and grounded state is not set yet in previous manifolds\n    if (!manifold->bodyB->isGrounded)\n        manifold->bodyB->isGrounded = (manifold->normal.y < 0);\n}\n\n// Solves collision between two circle shape physics bodies\nstatic void SolveCircleToCircle(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    // Calculate translational vector, which is normal\n    Vector2 normal = Vector2Subtract(bodyB->position, bodyA->position);\n\n    float distSqr = MathLenSqr(normal);\n    float radius = bodyA->shape.radius + bodyB->shape.radius;\n\n    // Check if circles are not in contact\n    if (distSqr >= radius*radius)\n    {\n        manifold->contactsCount = 0;\n        return;\n    }\n\n    float distance = sqrtf(distSqr);\n    manifold->contactsCount = 1;\n\n    if (distance == 0.0f)\n    {\n        manifold->penetration = bodyA->shape.radius;\n        manifold->normal = (Vector2){ 1.0f, 0.0f };\n        manifold->contacts[0] = bodyA->position;\n    }\n    else\n    {\n        manifold->penetration = radius - distance;\n        manifold->normal = (Vector2){ normal.x/distance, normal.y/distance }; // Faster than using MathNormalize() due to sqrt is already performed\n        manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y };\n    }\n\n    // Update physics body grounded state if normal direction is down\n    if (!bodyA->isGrounded)\n        bodyA->isGrounded = (manifold->normal.y < 0);\n}\n\n// Solves collision between a circle to a polygon shape physics bodies\nstatic void SolveCircleToPolygon(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    SolveDifferentShapes(manifold, bodyA, bodyB);\n}\n\n// Solves collision between a circle to a polygon shape physics bodies\nstatic void SolvePolygonToCircle(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    SolveDifferentShapes(manifold, bodyB, bodyA);\n    \n    manifold->normal.x *= -1.0f;\n    manifold->normal.y *= -1.0f;\n}\n\n// Solve collision between two different types of shapes\nstatic void SolveDifferentShapes(PhysicsManifold manifold, PhysicsBody bodyA, PhysicsBody bodyB)\n{\n    manifold->contactsCount = 0;\n\n    // Transform circle center to polygon transform space\n    Vector2 center = bodyA->position;\n    center = Mat2MultiplyVector2(Mat2Transpose(bodyB->shape.transform), Vector2Subtract(center, bodyB->position));\n\n    // Find edge with minimum penetration\n    // It is the same concept as using support points in SolvePolygonToPolygon\n    float separation = -PHYSAC_FLT_MAX;\n    int faceNormal = 0;\n    PolygonData vertexData = bodyB->shape.vertexData;\n\n    for (int i = 0; i < vertexData.vertexCount; i++)\n    {\n        float currentSeparation = MathDot(vertexData.normals[i], Vector2Subtract(center, vertexData.positions[i]));\n\n        if (currentSeparation > bodyA->shape.radius)\n            return;\n\n        if (currentSeparation > separation)\n        {\n            separation = currentSeparation;\n            faceNormal = i;\n        }\n    }\n\n    // Grab face's vertices\n    Vector2 v1 = vertexData.positions[faceNormal];\n    int nextIndex = (((faceNormal + 1) < vertexData.vertexCount) ? (faceNormal + 1) : 0);\n    Vector2 v2 = vertexData.positions[nextIndex];\n\n    // Check to see if center is within polygon\n    if (separation < PHYSAC_EPSILON)\n    {\n        manifold->contactsCount = 1;\n        Vector2 normal = Mat2MultiplyVector2(bodyB->shape.transform, vertexData.normals[faceNormal]);\n        manifold->normal = (Vector2){ -normal.x, -normal.y };\n        manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y };\n        manifold->penetration = bodyA->shape.radius;\n        return;\n    }\n\n    // Determine which voronoi region of the edge center of circle lies within\n    float dot1 = MathDot(Vector2Subtract(center, v1), Vector2Subtract(v2, v1));\n    float dot2 = MathDot(Vector2Subtract(center, v2), Vector2Subtract(v1, v2));\n    manifold->penetration = bodyA->shape.radius - separation;\n\n    if (dot1 <= 0.0f) // Closest to v1\n    {\n        if (DistSqr(center, v1) > bodyA->shape.radius*bodyA->shape.radius)\n            return;\n\n        manifold->contactsCount = 1;\n        Vector2 normal = Vector2Subtract(v1, center);\n        normal = Mat2MultiplyVector2(bodyB->shape.transform, normal);\n        MathNormalize(&normal);\n        manifold->normal = normal;\n        v1 = Mat2MultiplyVector2(bodyB->shape.transform, v1);\n        v1 = Vector2Add(v1, bodyB->position);\n        manifold->contacts[0] = v1;\n    }\n    else if (dot2 <= 0.0f) // Closest to v2\n    {\n        if (DistSqr(center, v2) > bodyA->shape.radius*bodyA->shape.radius)\n            return;\n\n        manifold->contactsCount = 1;\n        Vector2 normal = Vector2Subtract(v2, center);\n        v2 = Mat2MultiplyVector2(bodyB->shape.transform, v2);\n        v2 = Vector2Add(v2, bodyB->position);\n        manifold->contacts[0] = v2;\n        normal = Mat2MultiplyVector2(bodyB->shape.transform, normal);\n        MathNormalize(&normal);\n        manifold->normal = normal;\n    }\n    else // Closest to face\n    {\n        Vector2 normal = vertexData.normals[faceNormal];\n\n        if (MathDot(Vector2Subtract(center, v1), normal) > bodyA->shape.radius)\n            return;\n\n        normal = Mat2MultiplyVector2(bodyB->shape.transform, normal);\n        manifold->normal = (Vector2){ -normal.x, -normal.y };\n        manifold->contacts[0] = (Vector2){ manifold->normal.x*bodyA->shape.radius + bodyA->position.x, manifold->normal.y*bodyA->shape.radius + bodyA->position.y };\n        manifold->contactsCount = 1;\n    }\n}\n\n// Solves collision between two polygons shape physics bodies\nstatic void SolvePolygonToPolygon(PhysicsManifold manifold)\n{\n    if ((manifold->bodyA == NULL) || (manifold->bodyB == NULL))\n        return;\n\n    PhysicsShape bodyA = manifold->bodyA->shape;\n    PhysicsShape bodyB = manifold->bodyB->shape;\n    manifold->contactsCount = 0;\n\n    // Check for separating axis with A shape's face planes\n    int faceA = 0;\n    float penetrationA = FindAxisLeastPenetration(&faceA, bodyA, bodyB);\n    \n    if (penetrationA >= 0.0f)\n        return;\n\n    // Check for separating axis with B shape's face planes\n    int faceB = 0;\n    float penetrationB = FindAxisLeastPenetration(&faceB, bodyB, bodyA);\n    \n    if (penetrationB >= 0.0f)\n        return;\n\n    int referenceIndex = 0;\n    bool flip = false;  // Always point from A shape to B shape\n\n    PhysicsShape refPoly; // Reference\n    PhysicsShape incPoly; // Incident\n\n    // Determine which shape contains reference face\n    if (BiasGreaterThan(penetrationA, penetrationB))\n    {\n        refPoly = bodyA;\n        incPoly = bodyB;\n        referenceIndex = faceA;\n    }\n    else\n    {\n        refPoly = bodyB;\n        incPoly = bodyA;\n        referenceIndex = faceB;\n        flip = true;\n    }\n\n    // World space incident face\n    Vector2 incidentFace[2];\n    FindIncidentFace(&incidentFace[0], &incidentFace[1], refPoly, incPoly, referenceIndex);\n\n    // Setup reference face vertices\n    PolygonData refData = refPoly.vertexData;\n    Vector2 v1 = refData.positions[referenceIndex];\n    referenceIndex = (((referenceIndex + 1) < refData.vertexCount) ? (referenceIndex + 1) : 0);\n    Vector2 v2 = refData.positions[referenceIndex];\n\n    // Transform vertices to world space\n    v1 = Mat2MultiplyVector2(refPoly.transform, v1);\n    v1 = Vector2Add(v1, refPoly.body->position);\n    v2 = Mat2MultiplyVector2(refPoly.transform, v2);\n    v2 = Vector2Add(v2, refPoly.body->position);\n\n    // Calculate reference face side normal in world space\n    Vector2 sidePlaneNormal = Vector2Subtract(v2, v1);\n    MathNormalize(&sidePlaneNormal);\n\n    // Orthogonalize\n    Vector2 refFaceNormal = { sidePlaneNormal.y, -sidePlaneNormal.x };\n    float refC = MathDot(refFaceNormal, v1);\n    float negSide = MathDot(sidePlaneNormal, v1)*-1;\n    float posSide = MathDot(sidePlaneNormal, v2);\n\n    // Clip incident face to reference face side planes (due to floating point error, possible to not have required points\n    if (Clip((Vector2){ -sidePlaneNormal.x, -sidePlaneNormal.y }, negSide, &incidentFace[0], &incidentFace[1]) < 2)\n        return;\n\n    if (Clip(sidePlaneNormal, posSide, &incidentFace[0], &incidentFace[1]) < 2)\n        return;\n\n    // Flip normal if required\n    manifold->normal = (flip ? (Vector2){ -refFaceNormal.x, -refFaceNormal.y } : refFaceNormal);\n\n    // Keep points behind reference face\n    int currentPoint = 0; // Clipped points behind reference face\n    float separation = MathDot(refFaceNormal, incidentFace[0]) - refC;\n    \n    if (separation <= 0.0f)\n    {\n        manifold->contacts[currentPoint] = incidentFace[0];\n        manifold->penetration = -separation;\n        currentPoint++;\n    }\n    else\n        manifold->penetration = 0.0f;\n\n    separation = MathDot(refFaceNormal, incidentFace[1]) - refC;\n\n    if (separation <= 0.0f)\n    {\n        manifold->contacts[currentPoint] = incidentFace[1];\n        manifold->penetration += -separation;\n        currentPoint++;\n\n        // Calculate total penetration average\n        manifold->penetration /= currentPoint;\n    }\n\n    manifold->contactsCount = currentPoint;\n}\n\n// Integrates physics forces into velocity\nstatic void IntegratePhysicsForces(PhysicsBody body)\n{\n    if ((body == NULL) || (body->inverseMass == 0.0f) || !body->enabled)\n        return;\n\n    body->velocity.x += (body->force.x*body->inverseMass)*(deltaTime/2.0);\n    body->velocity.y += (body->force.y*body->inverseMass)*(deltaTime/2.0);\n\n    if (body->useGravity)\n    {\n        body->velocity.x += gravityForce.x*(deltaTime/1000/2.0);\n        body->velocity.y += gravityForce.y*(deltaTime/1000/2.0);\n    }\n\n    if (!body->freezeOrient)\n        body->angularVelocity += body->torque*body->inverseInertia*(deltaTime/2.0);\n}\n\n// Initializes physics manifolds to solve collisions\nstatic void InitializePhysicsManifolds(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    // Calculate average restitution, static and dynamic friction\n    manifold->restitution = sqrtf(bodyA->restitution*bodyB->restitution);\n    manifold->staticFriction = sqrtf(bodyA->staticFriction*bodyB->staticFriction);\n    manifold->dynamicFriction = sqrtf(bodyA->dynamicFriction*bodyB->dynamicFriction);\n\n    for (int i = 0; i < manifold->contactsCount; i++)\n    {\n        // Caculate radius from center of mass to contact\n        Vector2 radiusA = Vector2Subtract(manifold->contacts[i], bodyA->position);\n        Vector2 radiusB = Vector2Subtract(manifold->contacts[i], bodyB->position);\n\n        Vector2 crossA = MathCross(bodyA->angularVelocity, radiusA);\n        Vector2 crossB = MathCross(bodyB->angularVelocity, radiusB);\n\n        Vector2 radiusV = { 0.0f, 0.0f };\n        radiusV.x = bodyB->velocity.x + crossB.x - bodyA->velocity.x - crossA.x;\n        radiusV.y = bodyB->velocity.y + crossB.y - bodyA->velocity.y - crossA.y;\n\n        // Determine if we should perform a resting collision or not;\n        // The idea is if the only thing moving this object is gravity, then the collision should be performed without any restitution\n        if (MathLenSqr(radiusV) < (MathLenSqr((Vector2){ gravityForce.x*deltaTime/1000, gravityForce.y*deltaTime/1000 }) + PHYSAC_EPSILON))\n            manifold->restitution = 0;\n    }\n}\n\n// Integrates physics collisions impulses to solve collisions\nstatic void IntegratePhysicsImpulses(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    // Early out and positional correct if both objects have infinite mass\n    if (fabs(bodyA->inverseMass + bodyB->inverseMass) <= PHYSAC_EPSILON)\n    {\n        bodyA->velocity = PHYSAC_VECTOR_ZERO;\n        bodyB->velocity = PHYSAC_VECTOR_ZERO;\n        return;\n    }\n\n    for (int i = 0; i < manifold->contactsCount; i++)\n    {\n        // Calculate radius from center of mass to contact\n        Vector2 radiusA = Vector2Subtract(manifold->contacts[i], bodyA->position);\n        Vector2 radiusB = Vector2Subtract(manifold->contacts[i], bodyB->position);\n\n        // Calculate relative velocity\n        Vector2 radiusV = { 0.0f, 0.0f };\n        radiusV.x = bodyB->velocity.x + MathCross(bodyB->angularVelocity, radiusB).x - bodyA->velocity.x - MathCross(bodyA->angularVelocity, radiusA).x;\n        radiusV.y = bodyB->velocity.y + MathCross(bodyB->angularVelocity, radiusB).y - bodyA->velocity.y - MathCross(bodyA->angularVelocity, radiusA).y;\n\n        // Relative velocity along the normal\n        float contactVelocity = MathDot(radiusV, manifold->normal);\n\n        // Do not resolve if velocities are separating\n        if (contactVelocity > 0.0f)\n            return;\n\n        float raCrossN = MathCrossVector2(radiusA, manifold->normal);\n        float rbCrossN = MathCrossVector2(radiusB, manifold->normal);\n\n        float inverseMassSum = bodyA->inverseMass + bodyB->inverseMass + (raCrossN*raCrossN)*bodyA->inverseInertia + (rbCrossN*rbCrossN)*bodyB->inverseInertia;\n\n        // Calculate impulse scalar value\n        float impulse = -(1.0f + manifold->restitution)*contactVelocity;\n        impulse /= inverseMassSum;\n        impulse /= (float)manifold->contactsCount;\n\n        // Apply impulse to each physics body\n        Vector2 impulseV = { manifold->normal.x*impulse, manifold->normal.y*impulse };\n\n        if (bodyA->enabled)\n        {\n            bodyA->velocity.x += bodyA->inverseMass*(-impulseV.x);\n            bodyA->velocity.y += bodyA->inverseMass*(-impulseV.y);\n            \n            if (!bodyA->freezeOrient)\n                bodyA->angularVelocity += bodyA->inverseInertia*MathCrossVector2(radiusA, (Vector2){ -impulseV.x, -impulseV.y });\n        }\n\n        if (bodyB->enabled)\n        {\n            bodyB->velocity.x += bodyB->inverseMass*(impulseV.x);\n            bodyB->velocity.y += bodyB->inverseMass*(impulseV.y);\n            \n            if (!bodyB->freezeOrient)\n                bodyB->angularVelocity += bodyB->inverseInertia*MathCrossVector2(radiusB, impulseV);\n        }\n\n        // Apply friction impulse to each physics body\n        radiusV.x = bodyB->velocity.x + MathCross(bodyB->angularVelocity, radiusB).x - bodyA->velocity.x - MathCross(bodyA->angularVelocity, radiusA).x;\n        radiusV.y = bodyB->velocity.y + MathCross(bodyB->angularVelocity, radiusB).y - bodyA->velocity.y - MathCross(bodyA->angularVelocity, radiusA).y;\n\n        Vector2 tangent = { radiusV.x - (manifold->normal.x*MathDot(radiusV, manifold->normal)), radiusV.y - (manifold->normal.y*MathDot(radiusV, manifold->normal)) };\n        MathNormalize(&tangent);\n\n        // Calculate impulse tangent magnitude\n        float impulseTangent = -MathDot(radiusV, tangent);\n        impulseTangent /= inverseMassSum;\n        impulseTangent /= (float)manifold->contactsCount;\n\n        float absImpulseTangent = fabs(impulseTangent);\n\n        // Don't apply tiny friction impulses\n        if (absImpulseTangent <= PHYSAC_EPSILON)\n            return;\n\n        // Apply coulumb's law\n        Vector2 tangentImpulse = { 0.0f, 0.0f };\n        if (absImpulseTangent < impulse*manifold->staticFriction)\n            tangentImpulse = (Vector2){ tangent.x*impulseTangent, tangent.y*impulseTangent };\n        else\n            tangentImpulse = (Vector2){ tangent.x*-impulse*manifold->dynamicFriction, tangent.y*-impulse*manifold->dynamicFriction };\n\n        // Apply friction impulse\n        if (bodyA->enabled)\n        {\n            bodyA->velocity.x += bodyA->inverseMass*(-tangentImpulse.x);\n            bodyA->velocity.y += bodyA->inverseMass*(-tangentImpulse.y);\n\n            if (!bodyA->freezeOrient)\n                bodyA->angularVelocity += bodyA->inverseInertia*MathCrossVector2(radiusA, (Vector2){ -tangentImpulse.x, -tangentImpulse.y });\n        }\n\n        if (bodyB->enabled)\n        {\n            bodyB->velocity.x += bodyB->inverseMass*(tangentImpulse.x);\n            bodyB->velocity.y += bodyB->inverseMass*(tangentImpulse.y);\n\n            if (!bodyB->freezeOrient)\n                bodyB->angularVelocity += bodyB->inverseInertia*MathCrossVector2(radiusB, tangentImpulse);\n        }\n    }\n}\n\n// Integrates physics velocity into position and forces\nstatic void IntegratePhysicsVelocity(PhysicsBody body)\n{\n    if ((body == NULL) ||!body->enabled)\n        return;\n\n    body->position.x += body->velocity.x*deltaTime;\n    body->position.y += body->velocity.y*deltaTime;\n\n    if (!body->freezeOrient)\n        body->orient += body->angularVelocity*deltaTime;\n\n    Mat2Set(&body->shape.transform, body->orient);\n\n    IntegratePhysicsForces(body);\n}\n\n// Corrects physics bodies positions based on manifolds collision information\nstatic void CorrectPhysicsPositions(PhysicsManifold manifold)\n{\n    PhysicsBody bodyA = manifold->bodyA;\n    PhysicsBody bodyB = manifold->bodyB;\n\n    if ((bodyA == NULL) || (bodyB == NULL))\n        return;\n\n    Vector2 correction = { 0.0f, 0.0f };\n    correction.x = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.x*PHYSAC_PENETRATION_CORRECTION;\n    correction.y = (max(manifold->penetration - PHYSAC_PENETRATION_ALLOWANCE, 0.0f)/(bodyA->inverseMass + bodyB->inverseMass))*manifold->normal.y*PHYSAC_PENETRATION_CORRECTION;\n\n    if (bodyA->enabled)\n    {\n        bodyA->position.x -= correction.x*bodyA->inverseMass;\n        bodyA->position.y -= correction.y*bodyA->inverseMass;\n    }\n\n    if (bodyB->enabled)\n    {\n        bodyB->position.x += correction.x*bodyB->inverseMass;\n        bodyB->position.y += correction.y*bodyB->inverseMass;\n    }\n}\n\n// Returns the extreme point along a direction within a polygon\nstatic Vector2 GetSupport(PhysicsShape shape, Vector2 dir)\n{\n    float bestProjection = -PHYSAC_FLT_MAX;\n    Vector2 bestVertex = { 0.0f, 0.0f };\n    PolygonData data = shape.vertexData;\n\n    for (int i = 0; i < data.vertexCount; i++)\n    {\n        Vector2 vertex = data.positions[i];\n        float projection = MathDot(vertex, dir);\n\n        if (projection > bestProjection)\n        {\n            bestVertex = vertex;\n            bestProjection = projection;\n        }\n    }\n\n    return bestVertex;\n}\n\n// Finds polygon shapes axis least penetration\nstatic float FindAxisLeastPenetration(int *faceIndex, PhysicsShape shapeA, PhysicsShape shapeB)\n{\n    float bestDistance = -PHYSAC_FLT_MAX;\n    int bestIndex = 0;\n\n    PolygonData dataA = shapeA.vertexData;\n\n    for (int i = 0; i < dataA.vertexCount; i++)\n    {\n        // Retrieve a face normal from A shape\n        Vector2 normal = dataA.normals[i];\n        Vector2 transNormal = Mat2MultiplyVector2(shapeA.transform, normal);\n\n        // Transform face normal into B shape's model space\n        Mat2 buT = Mat2Transpose(shapeB.transform);\n        normal = Mat2MultiplyVector2(buT, transNormal);\n\n        // Retrieve support point from B shape along -n\n        Vector2 support = GetSupport(shapeB, (Vector2){ -normal.x, -normal.y });\n\n        // Retrieve vertex on face from A shape, transform into B shape's model space\n        Vector2 vertex = dataA.positions[i];\n        vertex = Mat2MultiplyVector2(shapeA.transform, vertex);\n        vertex = Vector2Add(vertex, shapeA.body->position);\n        vertex = Vector2Subtract(vertex, shapeB.body->position);\n        vertex = Mat2MultiplyVector2(buT, vertex);\n\n        // Compute penetration distance in B shape's model space\n        float distance = MathDot(normal, Vector2Subtract(support, vertex));\n\n        // Store greatest distance\n        if (distance > bestDistance)\n        {\n            bestDistance = distance;\n            bestIndex = i;\n        }\n    }\n\n    *faceIndex = bestIndex;\n    return bestDistance;\n}\n\n// Finds two polygon shapes incident face\nstatic void FindIncidentFace(Vector2 *v0, Vector2 *v1, PhysicsShape ref, PhysicsShape inc, int index)\n{\n    PolygonData refData = ref.vertexData;\n    PolygonData incData = inc.vertexData;\n\n    Vector2 referenceNormal = refData.normals[index];\n\n    // Calculate normal in incident's frame of reference\n    referenceNormal = Mat2MultiplyVector2(ref.transform, referenceNormal); // To world space\n    referenceNormal = Mat2MultiplyVector2(Mat2Transpose(inc.transform), referenceNormal); // To incident's model space\n\n    // Find most anti-normal face on polygon\n    int incidentFace = 0;\n    float minDot = PHYSAC_FLT_MAX;\n\n    for (int i = 0; i < incData.vertexCount; i++)\n    {\n        float dot = MathDot(referenceNormal, incData.normals[i]);\n\n        if (dot < minDot)\n        {\n            minDot = dot;\n            incidentFace = i;\n        }\n    }\n\n    // Assign face vertices for incident face\n    *v0 = Mat2MultiplyVector2(inc.transform, incData.positions[incidentFace]);\n    *v0 = Vector2Add(*v0, inc.body->position);\n    incidentFace = (((incidentFace + 1) < incData.vertexCount) ? (incidentFace + 1) : 0);\n    *v1 = Mat2MultiplyVector2(inc.transform, incData.positions[incidentFace]);\n    *v1 = Vector2Add(*v1, inc.body->position);\n}\n\n// Calculates clipping based on a normal and two faces\nstatic int Clip(Vector2 normal, float clip, Vector2 *faceA, Vector2 *faceB)\n{\n    int sp = 0;\n    Vector2 out[2] = { *faceA, *faceB };\n\n    // Retrieve distances from each endpoint to the line\n    float distanceA = MathDot(normal, *faceA) - clip;\n    float distanceB = MathDot(normal, *faceB) - clip;\n\n    // If negative (behind plane)\n    if (distanceA <= 0.0f)\n        out[sp++] = *faceA;\n\n    if (distanceB <= 0.0f)\n        out[sp++] = *faceB;\n\n    // If the points are on different sides of the plane\n    if ((distanceA*distanceB) < 0.0f)\n    {\n        // Push intersection point\n        float alpha = distanceA/(distanceA - distanceB);\n        out[sp] = *faceA;\n        Vector2 delta = Vector2Subtract(*faceB, *faceA);\n        delta.x *= alpha;\n        delta.y *= alpha;\n        out[sp] = Vector2Add(out[sp], delta);\n        sp++;\n    }\n\n    // Assign the new converted values\n    *faceA = out[0];\n    *faceB = out[1];\n\n    return sp;\n}\n\n// Check if values are between bias range\nstatic bool BiasGreaterThan(float valueA, float valueB)\n{\n    return (valueA >= (valueB*0.95f + valueA*0.01f));\n}\n\n// Returns the barycenter of a triangle given by 3 points\nstatic Vector2 TriangleBarycenter(Vector2 v1, Vector2 v2, Vector2 v3)\n{\n    Vector2 result = { 0.0f, 0.0f };\n\n    result.x = (v1.x + v2.x + v3.x)/3;\n    result.y = (v1.y + v2.y + v3.y)/3;\n\n    return result;\n}\n\n// Initializes hi-resolution MONOTONIC timer\nstatic void InitTimer(void)\n{\n    srand(time(NULL));              // Initialize random seed\n\n    #if defined(_WIN32)\n        QueryPerformanceFrequency((unsigned long long int *) &frequency);\n    #endif\n\n    #if defined(__linux__)\n        struct timespec now;\n        if (clock_gettime(CLOCK_MONOTONIC, &now) == 0)\n            frequency = 1000000000;\n    #endif\n\n    #if defined(__APPLE__)\n        mach_timebase_info_data_t timebase;\n        mach_timebase_info(&timebase);\n        frequency = (timebase.denom*1e9)/timebase.numer;\n    #endif\n\n    #if defined(EMSCRIPTEN)\n      frequency = 1000;\n    #endif\n\n    baseTime = GetTimeCount();      // Get MONOTONIC clock time offset\n    startTime = GetCurrTime();   // Get current time\n}\n\n// Get hi-res MONOTONIC time measure in seconds\nstatic uint64_t GetTimeCount(void)\n{\n    uint64_t value = 0;\n\n    #if defined(_WIN32)\n        QueryPerformanceCounter((unsigned long long int *) &value);\n    #endif\n\n    #if defined(__linux__)\n        struct timespec now;\n        clock_gettime(CLOCK_MONOTONIC, &now);\n        value = (uint64_t)now.tv_sec*(uint64_t)1000000000 + (uint64_t)now.tv_nsec;\n    #endif\n\n    #if defined(__APPLE__)\n        value = mach_absolute_time();\n    #endif\n\n    #if defined(EMSCRIPTEN)\n      value = emscripten_get_now();\n    #endif\n\n    return value;\n}\n\n// Get current time in milliseconds\nstatic double GetCurrTime(void)\n{\n    return (double)(GetTimeCount() - baseTime)/frequency*1000;\n}\n\n// Returns the cross product of a vector and a value\nstatic inline Vector2 MathCross(float value, Vector2 vector)\n{\n    return (Vector2){ -value*vector.y, value*vector.x };\n}\n\n// Returns the cross product of two vectors\nstatic inline float MathCrossVector2(Vector2 v1, Vector2 v2)\n{\n    return (v1.x*v2.y - v1.y*v2.x);\n}\n\n// Returns the len square root of a vector\nstatic inline float MathLenSqr(Vector2 vector)\n{\n    return (vector.x*vector.x + vector.y*vector.y);\n}\n\n// Returns the dot product of two vectors\nstatic inline float MathDot(Vector2 v1, Vector2 v2)\n{\n    return (v1.x*v2.x + v1.y*v2.y);\n}\n\n// Returns the square root of distance between two vectors\nstatic inline float DistSqr(Vector2 v1, Vector2 v2)\n{\n    Vector2 dir = Vector2Subtract(v1, v2);\n    return MathDot(dir, dir);\n}\n\n// Returns the normalized values of a vector\nstatic void MathNormalize(Vector2 *vector)\n{\n    float length, ilength;\n\n    Vector2 aux = *vector;\n    length = sqrtf(aux.x*aux.x + aux.y*aux.y);\n\n    if (length == 0)\n        length = 1.0f;\n\n    ilength = 1.0f/length;\n\n    vector->x *= ilength;\n    vector->y *= ilength;\n}\n\n#if defined(PHYSAC_STANDALONE)\n// Returns the sum of two given vectors\nstatic inline Vector2 Vector2Add(Vector2 v1, Vector2 v2)\n{\n    return (Vector2){ v1.x + v2.x, v1.y + v2.y };\n}\n\n// Returns the subtract of two given vectors\nstatic inline Vector2 Vector2Subtract(Vector2 v1, Vector2 v2)\n{\n    return (Vector2){ v1.x - v2.x, v1.y - v2.y };\n}\n#endif\n\n// Creates a matrix 2x2 from a given radians value\nstatic Mat2 Mat2Radians(float radians)\n{\n    float c = cosf(radians);\n    float s = sinf(radians);\n\n    return (Mat2){ c, -s, s, c };\n}\n\n// Set values from radians to a created matrix 2x2\nstatic void Mat2Set(Mat2 *matrix, float radians)\n{\n    float cos = cosf(radians);\n    float sin = sinf(radians);\n\n    matrix->m00 = cos;\n    matrix->m01 = -sin;\n    matrix->m10 = sin;\n    matrix->m11 = cos;\n}\n\n// Returns the transpose of a given matrix 2x2\nstatic inline Mat2 Mat2Transpose(Mat2 matrix)\n{\n    return (Mat2){ matrix.m00, matrix.m10, matrix.m01, matrix.m11 };\n}\n\n// Multiplies a vector by a matrix 2x2\nstatic inline Vector2 Mat2MultiplyVector2(Mat2 matrix, Vector2 vector)\n{\n    return (Vector2){ matrix.m00*vector.x + matrix.m01*vector.y, matrix.m10*vector.x + matrix.m11*vector.y };\n}\n\n#endif  // PHYSAC_IMPLEMENTATION\n"
  }
]