2
0
mirror of https://github.com/raylib-cs/raylib-cs synced 2025-06-30 19:03:42 -04:00

Update/merge examples back into main repo (#192)

This commit is contained in:
2023-08-25 08:08:32 +01:00
committed by GitHub
parent fa682b00ac
commit bcdf8cec5b
320 changed files with 57965 additions and 1 deletions

1
.gitignore vendored
View File

@ -9,6 +9,7 @@
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
.vscode/ .vscode/
*.data
# Binaries # Binaries
![Bb]in/ ![Bb]in/

View File

@ -0,0 +1,193 @@
/*******************************************************************************************
*
* raylib [audio] example - Module playing (streaming)
*
* NOTE: This example requires OpenAL Soft library installed
*
* This example has been created using raylib 1.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class ModulePlaying
{
const int MaxCircles = 64;
struct CircleWave
{
public Vector2 Position;
public float Radius;
public float Alpha;
public float Speed;
public Color Color;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT); // NOTE: Try to enable MSAA 4X
InitWindow(screenWidth, screenHeight, "raylib [audio] example - module playing (streaming)");
InitAudioDevice();
Color[] colors = new Color[14] {
Color.ORANGE,
Color.RED,
Color.GOLD,
Color.LIME,
Color.BLUE,
Color.VIOLET,
Color.BROWN,
Color.LIGHTGRAY,
Color.PINK,
Color.YELLOW,
Color.GREEN,
Color.SKYBLUE,
Color.PURPLE,
Color.BEIGE
};
// Creates ome circles for visual effect
CircleWave[] circles = new CircleWave[MaxCircles];
for (int i = MaxCircles - 1; i >= 0; i--)
{
circles[i].Alpha = 0.0f;
circles[i].Radius = GetRandomValue(10, 40);
circles[i].Position.X = GetRandomValue((int)circles[i].Radius, screenWidth - (int)circles[i].Radius);
circles[i].Position.Y = GetRandomValue((int)circles[i].Radius, screenHeight - (int)circles[i].Radius);
circles[i].Speed = (float)GetRandomValue(1, 100) / 20000.0f;
circles[i].Color = colors[GetRandomValue(0, 13)];
}
Music music = LoadMusicStream("resources/audio/mini1111.Xm");
music.Looping = false;
float pitch = 1.0f;
PlayMusicStream(music);
float timePlayed = 0.0f;
bool pause = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateMusicStream(music); // Update music buffer with new stream data
// Restart music playing (stop and play)
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
StopMusicStream(music);
PlayMusicStream(music);
}
// Pause/Resume music playing
if (IsKeyPressed(KeyboardKey.KEY_P))
{
pause = !pause;
if (pause)
{
PauseMusicStream(music);
}
else
{
ResumeMusicStream(music);
}
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
pitch -= 0.01f;
}
else if (IsKeyDown(KeyboardKey.KEY_UP))
{
pitch += 0.01f;
}
SetMusicPitch(music, pitch);
// Get timePlayed scaled to bar dimensions
timePlayed = GetMusicTimePlayed(music) / GetMusicTimeLength(music) * (screenWidth - 40);
// Color circles animation
for (int i = MaxCircles - 1; (i >= 0) && !pause; i--)
{
circles[i].Alpha += circles[i].Speed;
circles[i].Radius += circles[i].Speed * 10.0f;
if (circles[i].Alpha > 1.0f)
{
circles[i].Speed *= -1;
}
if (circles[i].Alpha <= 0.0f)
{
circles[i].Alpha = 0.0f;
circles[i].Radius = GetRandomValue(10, 40);
circles[i].Position.X = GetRandomValue(
(int)circles[i].Radius,
screenWidth - (int)circles[i].Radius
);
circles[i].Position.Y = GetRandomValue(
(int)circles[i].Radius,
screenHeight - (int)circles[i].Radius
);
circles[i].Color = colors[GetRandomValue(0, 13)];
circles[i].Speed = (float)GetRandomValue(1, 100) / 2000.0f;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
for (int i = MaxCircles - 1; i >= 0; i--)
{
DrawCircleV(
circles[i].Position,
circles[i].Radius,
ColorAlpha(circles[i].Color, circles[i].Alpha)
);
}
// Draw time bar
DrawRectangle(20, screenHeight - 20 - 12, screenWidth - 40, 12, Color.LIGHTGRAY);
DrawRectangle(20, screenHeight - 20 - 12, (int)timePlayed, 12, Color.MAROON);
DrawRectangleLines(20, screenHeight - 20 - 12, screenWidth - 40, 12, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadMusicStream(music);
CloseAudioDevice();
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,106 @@
/*******************************************************************************************
*
* raylib [audio] example - IntPtr playing (streaming)
*
* NOTE: This example requires OpenAL Soft library installed
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class MusicStreamDemo
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [audio] example - music playing (streaming)");
InitAudioDevice();
Music music = LoadMusicStream("resources/audio/country.mp3");
PlayMusicStream(music);
float timePlayed = 0.0f;
bool pause = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateMusicStream(music); // Update music buffer with new stream data
// Restart music playing (stop and play)
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
StopMusicStream(music);
PlayMusicStream(music);
}
// Pause/Resume music playing
if (IsKeyPressed(KeyboardKey.KEY_P))
{
pause = !pause;
if (pause)
{
PauseMusicStream(music);
}
else
{
ResumeMusicStream(music);
}
}
// Get timePlayed scaled to bar dimensions (400 pixels)
timePlayed = GetMusicTimePlayed(music) / GetMusicTimeLength(music) * 400;
if (timePlayed > 400)
{
StopMusicStream(music);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("MUSIC SHOULD BE PLAYING!", 255, 150, 20, Color.LIGHTGRAY);
DrawRectangle(200, 200, 400, 12, Color.LIGHTGRAY);
DrawRectangle(200, 200, (int)timePlayed, 12, Color.MAROON);
DrawRectangleLines(200, 200, 400, 12, Color.GRAY);
DrawText("PRESS SPACE TO RESTART MUSIC", 215, 250, 20, Color.LIGHTGRAY);
DrawText("PRESS P TO PAUSE/RESUME MUSIC", 208, 280, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadMusicStream(music);
CloseAudioDevice();
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,76 @@
/*******************************************************************************************
*
* raylib [audio] example - Sound loading and playing
*
* NOTE: This example requires OpenAL Soft library installed
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Audio;
public class SoundLoading
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [audio] example - sound loading and playing");
InitAudioDevice();
Sound fxWav = LoadSound("resources/audio/sound.wav");
Sound fxOgg = LoadSound("resources/audio/target.ogg");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
PlaySound(fxWav);
}
if (IsKeyPressed(KeyboardKey.KEY_ENTER))
{
PlaySound(fxOgg);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Press SPACE to PLAY the WAV sound!", 200, 180, 20, Color.LIGHTGRAY);
DrawText("Press ENTER to PLAY the OGG sound!", 200, 220, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadSound(fxWav);
UnloadSound(fxOgg);
CloseAudioDevice();
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,175 @@
/*******************************************************************************************
*
* raylib [core] example - Basic window
*
* Welcome to raylib!
*
* To test examples, just press F6 and execute raylib_compile_execute script
* Note that compiled executable is placed in the same folder as .c file
*
* You can find all basic examples on C:\raylib\raylib\examples folder or
* raylib official webpage: www.raylib.com
*
* Enjoy using raylib. :)
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
enum GameScreen
{
Logo = 0,
Title,
Gameplay,
Ending
}
public class BasicScreenManager
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic screen manager");
GameScreen currentScreen = GameScreen.Logo;
// TODO: Initialize all required variables and load all required data here!
// Useful to count frames
int framesCounter = 0;
SetTargetFPS(60); // Set desired framerate (frames-per-second)
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
switch (currentScreen)
{
case GameScreen.Logo:
{
// TODO: Update LOGO screen variables here!
// Count frames
framesCounter++;
// Wait for 2 seconds (120 frames) before jumping to TITLE screen
if (framesCounter > 120)
{
currentScreen = GameScreen.Title;
}
}
break;
case GameScreen.Title:
{
// TODO: Update TITLE screen variables here!
// Press enter to change to GAMEPLAY screen
if (IsKeyPressed(KeyboardKey.KEY_ENTER) || IsGestureDetected(Gesture.GESTURE_TAP))
{
currentScreen = GameScreen.Gameplay;
}
}
break;
case GameScreen.Gameplay:
{
// TODO: Update GAMEPLAY screen variables here!
// Press enter to change to ENDING screen
if (IsKeyPressed(KeyboardKey.KEY_ENTER) || IsGestureDetected(Gesture.GESTURE_TAP))
{
currentScreen = GameScreen.Ending;
}
}
break;
case GameScreen.Ending:
{
// TODO: Update ENDING screen variables here!
// Press enter to return to TITLE screen
if (IsKeyPressed(KeyboardKey.KEY_ENTER) || IsGestureDetected(Gesture.GESTURE_TAP))
{
currentScreen = GameScreen.Title;
}
}
break;
default:
break;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
switch (currentScreen)
{
case GameScreen.Logo:
{
// TODO: Draw LOGO screen here!
DrawText("LOGO SCREEN", 20, 20, 40, Color.LIGHTGRAY);
DrawText("WAIT for 2 SECONDS...", 290, 220, 20, Color.GRAY);
}
break;
case GameScreen.Title:
{
// TODO: Draw TITLE screen here!
DrawRectangle(0, 0, screenWidth, screenHeight, Color.GREEN);
DrawText("TITLE SCREEN", 20, 20, 40, Color.DARKGREEN);
DrawText("PRESS ENTER or TAP to JUMP to GAMEPLAY SCREEN", 120, 220, 20, Color.DARKGREEN);
}
break;
case GameScreen.Gameplay:
{
// TODO: Draw GAMEPLAY screen here!
DrawRectangle(0, 0, screenWidth, screenHeight, Color.PURPLE);
DrawText("GAMEPLAY SCREEN", 20, 20, 40, Color.MAROON);
DrawText("PRESS ENTER or TAP to JUMP to ENDING SCREEN", 130, 220, 20, Color.MAROON);
}
break;
case GameScreen.Ending:
{
// TODO: Draw ENDING screen here!
DrawRectangle(0, 0, screenWidth, screenHeight, Color.BLUE);
DrawText("ENDING SCREEN", 20, 20, 40, Color.DARKBLUE);
DrawText("PRESS ENTER or TAP to RETURN to TITLE SCREEN", 120, 220, 20, Color.DARKBLUE);
}
break;
default:
break;
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
// TODO: Unload all loaded data (textures, fonts, audio) here!
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,69 @@
/*******************************************************************************************
*
* raylib [core] example - Basic window
*
* Welcome to raylib!
*
* To test examples, just press F6 and execute raylib_compile_execute script
* Note that compiled executable is placed in the same folder as .c file
*
* You can find all basic examples on C:\raylib\raylib\examples folder or
* raylib official webpage: www.raylib.com
*
* Enjoy using raylib. :)
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using System;
using System.Text;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class BasicWindow
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Congrats! You created your first window!", 190, 200, 20, Color.MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,175 @@
/*******************************************************************************************
*
* raylib [core] example - 2d camera
*
* This example has been created using raylib 1.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera2dDemo
{
public const int MaxBuildings = 100;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
Rectangle player = new(400, 280, 40, 40);
Rectangle[] buildings = new Rectangle[MaxBuildings];
Color[] buildColors = new Color[MaxBuildings];
int spacing = 0;
for (int i = 0; i < MaxBuildings; i++)
{
buildings[i].Width = GetRandomValue(50, 200);
buildings[i].Height = GetRandomValue(100, 800);
buildings[i].Y = screenHeight - 130 - buildings[i].Height;
buildings[i].X = -6000 + spacing;
spacing += (int)buildings[i].Width;
buildColors[i] = new Color(
GetRandomValue(200, 240),
GetRandomValue(200, 240),
GetRandomValue(200, 250),
255
);
}
Camera2D camera = new();
camera.Target = new Vector2(player.X + 20, player.Y + 20);
camera.Offset = new Vector2(screenWidth / 2, screenHeight / 2);
camera.Rotation = 0.0f;
camera.Zoom = 1.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Player movement
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
player.X += 2;
}
else if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
player.X -= 2;
}
// Camera3D target follows player
camera.Target = new Vector2(player.X + 20, player.Y + 20);
// Camera3D rotation controls
if (IsKeyDown(KeyboardKey.KEY_A))
{
camera.Rotation--;
}
else if (IsKeyDown(KeyboardKey.KEY_S))
{
camera.Rotation++;
}
// Limit camera rotation to 80 degrees (-40 to 40)
if (camera.Rotation > 40)
{
camera.Rotation = 40;
}
else if (camera.Rotation < -40)
{
camera.Rotation = -40;
}
// Camera3D zoom controls
camera.Zoom += ((float)GetMouseWheelMove() * 0.05f);
if (camera.Zoom > 3.0f)
{
camera.Zoom = 3.0f;
}
else if (camera.Zoom < 0.1f)
{
camera.Zoom = 0.1f;
}
// Camera3D reset (zoom and rotation)
if (IsKeyPressed(KeyboardKey.KEY_R))
{
camera.Zoom = 1.0f;
camera.Rotation = 0.0f;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode2D(camera);
DrawRectangle(-6000, 320, 13000, 8000, Color.DARKGRAY);
for (int i = 0; i < MaxBuildings; i++)
{
DrawRectangleRec(buildings[i], buildColors[i]);
}
DrawRectangleRec(player, Color.RED);
DrawRectangle((int)camera.Target.X, -500, 1, (int)(screenHeight * 4), Color.GREEN);
DrawLine(
(int)(-screenWidth * 10),
(int)camera.Target.Y,
(int)(screenWidth * 10),
(int)camera.Target.Y,
Color.GREEN
);
EndMode2D();
DrawText("SCREEN AREA", 640, 10, 20, Color.RED);
DrawRectangle(0, 0, (int)screenWidth, 5, Color.RED);
DrawRectangle(0, 5, 5, (int)screenHeight - 10, Color.RED);
DrawRectangle((int)screenWidth - 5, 5, 5, (int)screenHeight - 10, Color.RED);
DrawRectangle(0, (int)screenHeight - 5, (int)screenWidth, 5, Color.RED);
DrawRectangle(10, 10, 250, 113, ColorAlpha(Color.SKYBLUE, 0.5f));
DrawRectangleLines(10, 10, 250, 113, Color.BLUE);
DrawText("Free 2d camera controls:", 20, 20, 10, Color.BLACK);
DrawText("- Right/Left to move Offset", 40, 40, 10, Color.DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out", 40, 60, 10, Color.DARKGRAY);
DrawText("- A / S to Rotate", 40, 80, 10, Color.DARKGRAY);
DrawText("- R to reset Zoom and Rotation", 40, 100, 10, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,402 @@
/*******************************************************************************************
*
* raylib [core] example - 2d camera platformer
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by arvyy (@arvyy) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 arvyy (@arvyy)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
namespace Examples.Core;
public class Camera2dPlatformer
{
const int G = 400;
const float PlayerJumpSpeed = 350.0f;
const float PlayerHorSpeed = 200.0f;
struct Player
{
public Vector2 Position;
public float Speed;
public bool CanJump;
}
struct EnvItem
{
public Rectangle Rect;
public int Blocking;
public Color Color;
public EnvItem(Rectangle rect, int blocking, Color color)
{
this.Rect = rect;
this.Blocking = blocking;
this.Color = color;
}
}
delegate void CameraUpdaterCallback(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height
);
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
Player player = new();
player.Position = new Vector2(400, 280);
player.Speed = 0;
player.CanJump = false;
EnvItem[] envItems = new EnvItem[]
{
new EnvItem(new Rectangle(0, 0, 1000, 400), 0, Color.LIGHTGRAY),
new EnvItem(new Rectangle(0, 400, 1000, 200), 1, Color.GRAY),
new EnvItem(new Rectangle(300, 200, 400, 10), 1, Color.GRAY),
new EnvItem(new Rectangle(250, 300, 100, 10), 1, Color.GRAY),
new EnvItem(new Rectangle(650, 300, 100, 10), 1, Color.GRAY)
};
Camera2D camera = new();
camera.Target = player.Position;
camera.Offset = new Vector2(screenWidth / 2, screenHeight / 2);
camera.Rotation = 0.0f;
camera.Zoom = 1.0f;
// Store callbacks to the multiple update camera functions
CameraUpdaterCallback[] cameraUpdaters = new CameraUpdaterCallback[]
{
UpdateCameraCenter,
UpdateCameraCenterInsideMap,
UpdateCameraCenterSmoothFollow,
UpdateCameraEvenOutOnLanding,
UpdateCameraPlayerBoundsPush
};
int cameraOption = 0;
int cameraUpdatersLength = cameraUpdaters.Length;
string[] cameraDescriptions = new string[]{
"Follow player center",
"Follow player center, but clamp to map edges",
"Follow player center; smoothed",
"Follow player center horizontally; update player center vertically after landing",
"Player push camera on getting too close to screen edge"
};
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
float deltaTime = GetFrameTime();
UpdatePlayer(ref player, envItems, deltaTime);
camera.Zoom += ((float)GetMouseWheelMove() * 0.05f);
if (camera.Zoom > 3.0f)
{
camera.Zoom = 3.0f;
}
else if (camera.Zoom < 0.25f)
{
camera.Zoom = 0.25f;
}
if (IsKeyPressed(KeyboardKey.KEY_R))
{
camera.Zoom = 1.0f;
player.Position = new Vector2(400, 280);
}
if (IsKeyPressed(KeyboardKey.KEY_C))
{
cameraOption = (cameraOption + 1) % cameraUpdatersLength;
}
// Call update camera function by its pointer
cameraUpdaters[cameraOption](ref camera, ref player, envItems, deltaTime, screenWidth, screenHeight);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.LIGHTGRAY);
BeginMode2D(camera);
for (int i = 0; i < envItems.Length; i++)
{
DrawRectangleRec(envItems[i].Rect, envItems[i].Color);
}
Rectangle playerRect = new(player.Position.X - 20, player.Position.Y - 40, 40, 40);
DrawRectangleRec(playerRect, Color.RED);
EndMode2D();
DrawText("Controls:", 20, 20, 10, Color.BLACK);
DrawText("- Right/Left to move", 40, 40, 10, Color.DARKGRAY);
DrawText("- Space to jump", 40, 60, 10, Color.DARKGRAY);
DrawText("- Mouse Wheel to Zoom in-out, R to reset zoom", 40, 80, 10, Color.DARKGRAY);
DrawText("- C to change camera mode", 40, 100, 10, Color.DARKGRAY);
DrawText("Current camera mode:", 20, 120, 10, Color.BLACK);
DrawText(cameraDescriptions[cameraOption], 40, 140, 10, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
static void UpdatePlayer(ref Player player, EnvItem[] envItems, float delta)
{
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
player.Position.X -= PlayerHorSpeed * delta;
}
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
player.Position.X += PlayerHorSpeed * delta;
}
if (IsKeyDown(KeyboardKey.KEY_SPACE) && player.CanJump)
{
player.Speed = -PlayerJumpSpeed;
player.CanJump = false;
}
int hitObstacle = 0;
for (int i = 0; i < envItems.Length; i++)
{
EnvItem ei = envItems[i];
Vector2 p = player.Position;
if (ei.Blocking != 0 &&
ei.Rect.X <= p.X &&
ei.Rect.X + ei.Rect.Width >= p.X &&
ei.Rect.Y >= p.Y &&
ei.Rect.Y <= p.Y + player.Speed * delta)
{
hitObstacle = 1;
player.Speed = 0.0f;
player.Position.Y = ei.Rect.Y;
}
}
if (hitObstacle == 0)
{
player.Position.Y += player.Speed * delta;
player.Speed += G * delta;
player.CanJump = false;
}
else
{
player.CanJump = true;
}
}
static void UpdateCameraCenter(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height
)
{
camera.Offset = new Vector2(width / 2, height / 2);
camera.Target = player.Position;
}
static void UpdateCameraCenterInsideMap(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height)
{
camera.Target = player.Position;
camera.Offset = new Vector2(width / 2, height / 2);
float minX = 1000, minY = 1000, maxX = -1000, maxY = -1000;
for (int i = 0; i < envItems.Length; i++)
{
EnvItem ei = envItems[i];
minX = Math.Min(ei.Rect.X, minX);
maxX = Math.Max(ei.Rect.X + ei.Rect.Width, maxX);
minY = Math.Min(ei.Rect.Y, minY);
maxY = Math.Max(ei.Rect.Y + ei.Rect.Height, maxY);
}
Vector2 max = GetWorldToScreen2D(new Vector2(maxX, maxY), camera);
Vector2 min = GetWorldToScreen2D(new Vector2(minX, minY), camera);
if (max.X < width)
{
camera.Offset.X = width - (max.X - width / 2);
}
if (max.Y < height)
{
camera.Offset.Y = height - (max.Y - height / 2);
}
if (min.X > 0)
{
camera.Offset.X = width / 2 - min.X;
}
if (min.Y > 0)
{
camera.Offset.Y = height / 2 - min.Y;
}
}
static void UpdateCameraCenterSmoothFollow(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height
)
{
const float minSpeed = 30;
const float minEffectLength = 10;
const float fractionSpeed = 0.8f;
camera.Offset = new Vector2(width / 2, height / 2);
Vector2 diff = Vector2Subtract(player.Position, camera.Target);
float length = Vector2Length(diff);
if (length > minEffectLength)
{
float speed = Math.Max(fractionSpeed * length, minSpeed);
camera.Target = Vector2Add(camera.Target, Vector2Scale(diff, speed * delta / length));
}
}
static void UpdateCameraEvenOutOnLanding(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height
)
{
float evenOutSpeed = 700;
int eveningOut = 0;
float evenOutTarget = 0.0f;
camera.Offset = new Vector2(width / 2, height / 2);
camera.Target.X = player.Position.X;
if (eveningOut != 0)
{
if (evenOutTarget > camera.Target.Y)
{
camera.Target.Y += evenOutSpeed * delta;
if (camera.Target.Y > evenOutTarget)
{
camera.Target.Y = evenOutTarget;
eveningOut = 0;
}
}
else
{
camera.Target.Y -= evenOutSpeed * delta;
if (camera.Target.Y < evenOutTarget)
{
camera.Target.Y = evenOutTarget;
eveningOut = 0;
}
}
}
else
{
if (player.CanJump && (player.Speed == 0) && (player.Position.Y != camera.Target.Y))
{
eveningOut = 1;
evenOutTarget = player.Position.Y;
}
}
}
static void UpdateCameraPlayerBoundsPush(
ref Camera2D camera,
ref Player player,
EnvItem[] envItems,
float delta,
int width,
int height
)
{
Vector2 bbox = new(0.2f, 0.2f);
Vector2 bboxWorldMin = GetScreenToWorld2D(
new Vector2((1 - bbox.X) * 0.5f * width, (1 - bbox.Y) * 0.5f * height),
camera
);
Vector2 bboxWorldMax = GetScreenToWorld2D(
new Vector2((1 + bbox.X) * 0.5f * width,
(1 + bbox.Y) * 0.5f * height),
camera
);
camera.Offset = new Vector2((1 - bbox.X) * 0.5f * width, (1 - bbox.Y) * 0.5f * height);
if (player.Position.X < bboxWorldMin.X)
{
camera.Target.X = player.Position.X;
}
if (player.Position.Y < bboxWorldMin.Y)
{
camera.Target.Y = player.Position.Y;
}
if (player.Position.X > bboxWorldMax.X)
{
camera.Target.X = bboxWorldMin.X + (player.Position.X - bboxWorldMax.X);
}
if (player.Position.Y > bboxWorldMax.Y)
{
camera.Target.Y = bboxWorldMin.Y + (player.Position.Y - bboxWorldMax.Y);
}
}
}

View File

@ -0,0 +1,186 @@
/*******************************************************************************************
*
* raylib [core] example - 3d camera first person
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dFirstPerson
{
public const int MaxColumns = 20;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera first person");
// Define the camera to look into our 3d world (position, target, up vector)
Camera3D camera = new();
camera.Position = new Vector3(4.0f, 2.0f, 4.0f);
camera.Target = new Vector3(0.0f, 1.8f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 60.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Generates some random columns
float[] heights = new float[MaxColumns];
Vector3[] positions = new Vector3[MaxColumns];
Color[] colors = new Color[MaxColumns];
for (int i = 0; i < MaxColumns; i++)
{
heights[i] = (float)GetRandomValue(1, 12);
positions[i] = new Vector3(GetRandomValue(-15, 15), heights[i] / 2, GetRandomValue(-15, 15));
colors[i] = new Color(GetRandomValue(20, 255), GetRandomValue(10, 55), 30, 255);
}
CameraMode cameraMode = CameraMode.CAMERA_FIRST_PERSON;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Switch camera mode
if (IsKeyPressed(KeyboardKey.KEY_ONE))
{
cameraMode = CameraMode.CAMERA_FREE;
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
}
if (IsKeyPressed(KeyboardKey.KEY_TWO))
{
cameraMode = CameraMode.CAMERA_FIRST_PERSON;
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
}
if (IsKeyPressed(KeyboardKey.KEY_THREE))
{
cameraMode = CameraMode.CAMERA_THIRD_PERSON;
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
}
if (IsKeyPressed(KeyboardKey.KEY_FOUR))
{
cameraMode = CameraMode.CAMERA_ORBITAL;
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
}
// Switch camera projection
if (IsKeyPressed(KeyboardKey.KEY_P))
{
if (camera.Projection == CameraProjection.CAMERA_PERSPECTIVE)
{
// Create isometric view
cameraMode = CameraMode.CAMERA_THIRD_PERSON;
// Note: The target distance is related to the render distance in the orthographic projection
camera.Position = new Vector3(0.0f, 2.0f, -100.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.Projection = CameraProjection.CAMERA_ORTHOGRAPHIC;
camera.FovY = 20.0f; // near plane width in CAMERA_ORTHOGRAPHIC
// CameraYaw(&camera, -135 * DEG2RAD, true);
// CameraPitch(&camera, -45 * DEG2RAD, true, true, false);
}
else if (camera.Projection == CameraProjection.CAMERA_ORTHOGRAPHIC)
{
// Reset to default view
cameraMode = CameraMode.CAMERA_THIRD_PERSON;
camera.Position = new Vector3(0.0f, 2.0f, 10.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
camera.FovY = 60.0f;
}
}
// Update camera computes movement internally depending on the camera mode
// Some default standard keyboard/mouse inputs are hardcoded to simplify use
// For advance camera controls, it's reecommended to compute camera movement manually
UpdateCamera(ref camera, CameraMode.CAMERA_CUSTOM);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
// Draw ground
DrawPlane(new Vector3(0.0f, 0.0f, 0.0f), new Vector2(32.0f, 32.0f), Color.LIGHTGRAY);
// Draw a blue wall
DrawCube(new Vector3(-16.0f, 2.5f, 0.0f), 1.0f, 5.0f, 32.0f, Color.BLUE);
// Draw a green wall
DrawCube(new Vector3(16.0f, 2.5f, 0.0f), 1.0f, 5.0f, 32.0f, Color.LIME);
// Draw a yellow wall
DrawCube(new Vector3(0.0f, 2.5f, 16.0f), 32.0f, 5.0f, 1.0f, Color.GOLD);
// Draw some cubes around
for (int i = 0; i < MaxColumns; i++)
{
DrawCube(positions[i], 2.0f, heights[i], 2.0f, colors[i]);
DrawCubeWires(positions[i], 2.0f, heights[i], 2.0f, Color.MAROON);
}
// Draw player cube
if (cameraMode == CameraMode.CAMERA_THIRD_PERSON)
{
DrawCube(camera.Target, 0.5f, 0.5f, 0.5f, Color.PURPLE);
DrawCubeWires(camera.Target, 0.5f, 0.5f, 0.5f, Color.DARKPURPLE);
}
EndMode3D();
// Draw info boxes
DrawRectangle(5, 5, 330, 100, ColorAlpha(Color.SKYBLUE, 0.5f));
DrawRectangleLines(10, 10, 330, 100, Color.BLUE);
DrawText("Camera controls:", 15, 15, 10, Color.BLACK);
DrawText("- Move keys: W, A, S, D, Space, Left-Ctrl", 15, 30, 10, Color.BLACK);
DrawText("- Look around: arrow keys or mouse", 15, 45, 10, Color.BLACK);
DrawText("- Camera mode keys: 1, 2, 3, 4", 15, 60, 10, Color.BLACK);
DrawText("- Zoom keys: num-plus, num-minus or mouse scroll", 15, 75, 10, Color.BLACK);
DrawText("- Camera projection key: P", 15, 90, 10, Color.BLACK);
DrawRectangle(600, 5, 195, 100, Fade(Color.SKYBLUE, 0.5f));
DrawRectangleLines(600, 5, 195, 100, Color.BLUE);
DrawText("Camera status:", 610, 15, 10, Color.BLACK);
DrawText($"- Mode: {cameraMode}", 610, 30, 10, Color.BLACK);
DrawText($"- Projection: {camera.Projection}", 610, 45, 10, Color.BLACK);
DrawText($"- Position: {camera.Position}", 610, 60, 10, Color.BLACK);
DrawText($"- Target: {camera.Target}", 610, 75, 10, Color.BLACK);
DrawText($"- Up: {camera.Up}", 610, 90, 10, Color.BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,89 @@
/*******************************************************************************************
*
* raylib [core] example - Initialize 3d camera free
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dFree
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
if (IsKeyDown(KeyboardKey.KEY_Z))
{
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, Color.RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, Color.MAROON);
DrawGrid(10, 1.0f);
EndMode3D();
DrawRectangle(10, 10, 320, 133, ColorAlpha(Color.SKYBLUE, 0.5f));
DrawRectangleLines(10, 10, 320, 133, Color.BLUE);
DrawText("Free camera default controls:", 20, 20, 10, Color.BLACK);
DrawText("- Mouse Wheel to Zoom in-out", 40, 40, 10, Color.DARKGRAY);
DrawText("- Mouse Wheel Pressed to Pan", 40, 60, 10, Color.DARKGRAY);
DrawText("- Alt + Mouse Wheel Pressed to Rotate", 40, 80, 10, Color.DARKGRAY);
DrawText("- Alt + Ctrl + Mouse Wheel Pressed for Smooth Zoom", 40, 100, 10, Color.DARKGRAY);
DrawText("- Z to zoom to (0, 0, 0)", 40, 120, 10, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,78 @@
/*******************************************************************************************
*
* raylib [core] example - Initialize 3d camera mode
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Camera3dMode
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera mode");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, Color.RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, Color.MAROON);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("Welcome to the third dimension!", 10, 40, 20, Color.DARKGRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,87 @@
/*******************************************************************************************
*
* raylib [core] example - Custom logging
*
* This example has been created using raylib 2.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Pablo Marcos Oltra (@pamarcos) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Pablo Marcos Oltra (@pamarcos) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Runtime.InteropServices;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public unsafe class CustomLogging
{
[UnmanagedCallersOnly(CallConvs = new[] { typeof(System.Runtime.CompilerServices.CallConvCdecl) })]
private static void LogCustom(int logLevel, sbyte* text, sbyte* args)
{
var message = Logging.GetLogMessage(new IntPtr(text), new IntPtr(args));
/*Console.ForegroundColor = (TraceLogLevel)logLevel switch
{
TraceLogLevel.LOG_ALL => ConsoleColor.White,
TraceLogLevel.LOG_TRACE => ConsoleColor.Black,
TraceLogLevel.LOG_DEBUG => ConsoleColor.Blue,
TraceLogLevel.LOG_INFO => ConsoleColor.Black,
TraceLogLevel.LOG_WARNING => ConsoleColor.DarkYellow,
TraceLogLevel.LOG_ERROR => ConsoleColor.Red,
TraceLogLevel.LOG_FATAL => ConsoleColor.Red,
TraceLogLevel.LOG_NONE => ConsoleColor.White,
_ => throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null)
};*/
Console.WriteLine($"Custom " + message);
// Console.ResetColor();
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// First thing we do is setting our custom logger to ensure everything raylib logs
// will use our own logger instead of its internal one
Raylib.SetTraceLogCallback(&LogCustom);
InitWindow(screenWidth, screenHeight, "raylib [core] example - custom logging");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Check out the console output to see the custom logger in action!", 60, 200, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
Raylib.SetTraceLogCallback(&Logging.LogConsole);
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,85 @@
/*******************************************************************************************
*
* raylib [core] example - Windows drop files
*
* This example only works on platforms that support drag ref drop (Windows, Linux, OSX, Html5?)
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class DropFiles
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - drop files");
string[] files = new string[0];
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsFileDropped())
{
files = Raylib.GetDroppedFiles();
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (files.Length == 0)
{
DrawText("Drop your files to this window!", 100, 40, 20, Color.DARKGRAY);
}
else
{
DrawText("Dropped files:", 100, 40, 20, Color.DARKGRAY);
for (int i = 0; i < files.Length; i++)
{
if (i % 2 == 0)
{
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, ColorAlpha(Color.LIGHTGRAY, 0.5f));
}
else
{
DrawRectangle(0, 85 + 40 * i, screenWidth, 40, ColorAlpha(Color.LIGHTGRAY, 0.3f));
}
DrawText(files[i], 120, 100 + 40 * i, 10, Color.GRAY);
}
DrawText("Drop new files...", 100, 110 + 40 * files.Length, 20, Color.DARKGRAY);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,324 @@
/*******************************************************************************************
*
* raylib [core] example - Gamepad input
*
* NOTE: This example requires a Gamepad connected to the system
* raylib is configured to work with the following gamepads:
* - Xbox 360 Controller (Xbox 360, Xbox One)
* - PLAYSTATION(R)3 Controller
* Check raylib.h for buttons configuration
*
* This example has been created using raylib 1.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputGamepad
{
// NOTE: Gamepad name ID depends on drivers and OS
// public const string XBOX360_NAME_ID = "Microsoft;
// public const string PS3_NAME_ID = "PLAYSTATION(R)3;
public const string XBOX360_NAME_ID = "Xbox";
public const string PS3_NAME_ID = "PLAYSTATION(R)3";
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Set MSAA 4X hint before windows creation
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [core] example - gamepad input");
Texture2D texPs3Pad = LoadTexture("resources/ps3.png");
Texture2D texXboxPad = LoadTexture("resources/xbox.png");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// ...
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (IsGamepadAvailable(0))
{
string gamepadName = GetGamepadName_(0);
DrawText($"GP1: {gamepadName}", 10, 10, 10, Color.BLACK);
if (gamepadName == XBOX360_NAME_ID)
{
DrawTexture(texXboxPad, 0, 0, Color.DARKGRAY);
// Draw buttons: xbox home
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE))
{
DrawCircle(394, 89, 19, Color.RED);
}
// Draw buttons: basic
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE_RIGHT))
{
DrawCircle(436, 150, 9, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE_LEFT))
{
DrawCircle(352, 150, 9, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_LEFT))
{
DrawCircle(501, 151, 15, Color.BLUE);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_DOWN))
{
DrawCircle(536, 187, 15, Color.LIME);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_RIGHT))
{
DrawCircle(572, 151, 15, Color.MAROON);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_UP))
{
DrawCircle(536, 115, 15, Color.GOLD);
}
// Draw buttons: d-pad
DrawRectangle(317, 202, 19, 71, Color.BLACK);
DrawRectangle(293, 228, 69, 19, Color.BLACK);
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_UP))
{
DrawRectangle(317, 202, 19, 26, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_DOWN))
{
DrawRectangle(317, 202 + 45, 19, 26, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_LEFT))
{
DrawRectangle(292, 228, 25, 19, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_RIGHT))
{
DrawRectangle(292 + 44, 228, 26, 19, Color.RED);
}
// Draw buttons: left-right back
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_TRIGGER_1))
{
DrawCircle(259, 61, 20, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_TRIGGER_1))
{
DrawCircle(536, 61, 20, Color.RED);
}
// Draw axis: left joystick
DrawCircle(259, 152, 39, Color.BLACK);
DrawCircle(259, 152, 34, Color.LIGHTGRAY);
DrawCircle(
259 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_X) * 20),
152 - (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_Y) * 20),
25,
Color.BLACK
);
// Draw axis: right joystick
DrawCircle(461, 237, 38, Color.BLACK);
DrawCircle(461, 237, 33, Color.LIGHTGRAY);
DrawCircle(
461 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_X) * 20),
237 - (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_Y) * 20),
25, Color.BLACK
);
// Draw axis: left-right triggers
float leftTriggerX = GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_TRIGGER);
float rightTriggerX = GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_RIGHT_TRIGGER);
DrawRectangle(170, 30, 15, 70, Color.GRAY);
DrawRectangle(604, 30, 15, 70, Color.GRAY);
DrawRectangle(170, 30, 15, (int)(((1.0f + leftTriggerX) / 2.0f) * 70), Color.RED);
DrawRectangle(604, 30, 15, (int)(((1.0f + rightTriggerX) / 2.0f) * 70), Color.RED);
}
else if (gamepadName == PS3_NAME_ID)
{
DrawTexture(texPs3Pad, 0, 0, Color.DARKGRAY);
// Draw buttons: ps
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE))
{
DrawCircle(396, 222, 13, Color.RED);
}
// Draw buttons: basic
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE_LEFT))
{
DrawRectangle(328, 170, 32, 13, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_MIDDLE_RIGHT))
{
DrawTriangle(
new Vector2(436, 168),
new Vector2(436, 185),
new Vector2(464, 177),
Color.RED
);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_UP))
{
DrawCircle(557, 144, 13, Color.LIME);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_RIGHT))
{
DrawCircle(586, 173, 13, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_DOWN))
{
DrawCircle(557, 203, 13, Color.VIOLET);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_FACE_LEFT))
{
DrawCircle(527, 173, 13, Color.PINK);
}
// Draw buttons: d-pad
DrawRectangle(225, 132, 24, 84, Color.BLACK);
DrawRectangle(195, 161, 84, 25, Color.BLACK);
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_UP))
{
DrawRectangle(225, 132, 24, 29, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_DOWN))
{
DrawRectangle(225, 132 + 54, 24, 30, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_LEFT))
{
DrawRectangle(195, 161, 30, 25, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_FACE_RIGHT))
{
DrawRectangle(195 + 54, 161, 30, 25, Color.RED);
}
// Draw buttons: left-right back buttons
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_LEFT_TRIGGER_1))
{
DrawCircle(239, 82, 20, Color.RED);
}
if (IsGamepadButtonDown(0, GamepadButton.GAMEPAD_BUTTON_RIGHT_TRIGGER_1))
{
DrawCircle(557, 82, 20, Color.RED);
}
// Draw axis: left joystick
DrawCircle(319, 255, 35, Color.BLACK);
DrawCircle(319, 255, 31, Color.LIGHTGRAY);
DrawCircle(
319 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_X) * 20),
255 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_Y) * 20),
25,
Color.BLACK
);
// Draw axis: right joystick
DrawCircle(475, 255, 35, Color.BLACK);
DrawCircle(475, 255, 31, Color.LIGHTGRAY);
DrawCircle(
475 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_RIGHT_X) * 20),
255 + (int)(GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_RIGHT_Y) * 20),
25,
Color.BLACK
);
// Draw axis: left-right triggers
float leftTriggerX = GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_LEFT_TRIGGER);
float rightTriggerX = GetGamepadAxisMovement(0, GamepadAxis.GAMEPAD_AXIS_RIGHT_TRIGGER);
DrawRectangle(169, 48, 15, 70, Color.GRAY);
DrawRectangle(611, 48, 15, 70, Color.GRAY);
DrawRectangle(169, 48, 15, (int)(((1.0f - leftTriggerX) / 2.0f) * 70), Color.RED);
DrawRectangle(611, 48, 15, (int)(((1.0f - rightTriggerX) / 2.0f) * 70), Color.RED);
}
else
{
DrawText("- GENERIC GAMEPAD -", 280, 180, 20, Color.GRAY);
// TODO: Draw generic gamepad
}
DrawText($"DETECTED AXIS [{GetGamepadAxisCount(0)}]:", 10, 50, 10, Color.MAROON);
for (int i = 0; i < GetGamepadAxisCount(0); i++)
{
DrawText(
$"AXIS {i}: {GetGamepadAxisMovement(0, (GamepadAxis)i)}",
20,
70 + 20 * i,
10,
Color.DARKGRAY
);
}
if (GetGamepadButtonPressed() != (int)GamepadButton.GAMEPAD_BUTTON_UNKNOWN)
{
DrawText($"DETECTED BUTTON: {GetGamepadButtonPressed()}", 10, 430, 10, Color.RED);
}
else
{
DrawText("DETECTED BUTTON: NONE", 10, 430, 10, Color.GRAY);
}
}
else
{
DrawText("GP1: NOT DETECTED", 10, 10, 10, Color.GRAY);
DrawTexture(texXboxPad, 0, 0, Color.LIGHTGRAY);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texPs3Pad);
UnloadTexture(texXboxPad);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,158 @@
/*******************************************************************************************
*
* raylib [core] example - Gestures Detection
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputGestures
{
public const int MaxGestureStrings = 20;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - gestures detection");
Vector2 touchPosition = new(0, 0);
Rectangle touchArea = new(220, 10, screenWidth - 230, screenHeight - 20);
int gesturesCount = 0;
string[] gestureStrings = new string[MaxGestureStrings];
Gesture currentGesture = Gesture.GESTURE_NONE;
Gesture lastGesture = Gesture.GESTURE_NONE;
// SetGesturesEnabled(0b0000000000001001); // Enable only some gestures to be detected
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
lastGesture = currentGesture;
currentGesture = GetGestureDetected();
touchPosition = GetTouchPosition(0);
if (CheckCollisionPointRec(touchPosition, touchArea) && (currentGesture != Gesture.GESTURE_NONE))
{
if (currentGesture != lastGesture)
{
// Store gesture string
switch ((Gesture)currentGesture)
{
case Gesture.GESTURE_TAP:
gestureStrings[gesturesCount] = "GESTURE TAP";
break;
case Gesture.GESTURE_DOUBLETAP:
gestureStrings[gesturesCount] = "GESTURE DOUBLETAP";
break;
case Gesture.GESTURE_HOLD:
gestureStrings[gesturesCount] = "GESTURE HOLD";
break;
case Gesture.GESTURE_DRAG:
gestureStrings[gesturesCount] = "GESTURE DRAG";
break;
case Gesture.GESTURE_SWIPE_RIGHT:
gestureStrings[gesturesCount] = "GESTURE SWIPE RIGHT";
break;
case Gesture.GESTURE_SWIPE_LEFT:
gestureStrings[gesturesCount] = "GESTURE SWIPE LEFT";
break;
case Gesture.GESTURE_SWIPE_UP:
gestureStrings[gesturesCount] = "GESTURE SWIPE UP";
break;
case Gesture.GESTURE_SWIPE_DOWN:
gestureStrings[gesturesCount] = "GESTURE SWIPE DOWN";
break;
case Gesture.GESTURE_PINCH_IN:
gestureStrings[gesturesCount] = "GESTURE PINCH IN";
break;
case Gesture.GESTURE_PINCH_OUT:
gestureStrings[gesturesCount] = "GESTURE PINCH OUT";
break;
default:
break;
}
gesturesCount++;
// Reset gestures strings
if (gesturesCount >= MaxGestureStrings)
{
for (int i = 0; i < MaxGestureStrings; i++)
{
gestureStrings[i] = " ";
}
gesturesCount = 0;
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectangleRec(touchArea, Color.GRAY);
DrawRectangle(225, 15, screenWidth - 240, screenHeight - 30, Color.RAYWHITE);
DrawText("GESTURES TEST AREA", screenWidth - 270, screenHeight - 40, 20, ColorAlpha(Color.GRAY, 0.5f));
for (int i = 0; i < gesturesCount; i++)
{
if (i % 2 == 0)
{
DrawRectangle(10, 30 + 20 * i, 200, 20, ColorAlpha(Color.LIGHTGRAY, 0.5f));
}
else
{
DrawRectangle(10, 30 + 20 * i, 200, 20, ColorAlpha(Color.LIGHTGRAY, 0.3f));
}
if (i < gesturesCount - 1)
{
DrawText(gestureStrings[i], 35, 36 + 20 * i, 10, Color.DARKGRAY);
}
else
{
DrawText(gestureStrings[i], 35, 36 + 20 * i, 10, Color.MAROON);
}
}
DrawRectangleLines(10, 29, 200, screenHeight - 50, Color.GRAY);
DrawText("DETECTED GESTURES", 50, 15, 10, Color.GRAY);
if (currentGesture != Gesture.GESTURE_NONE)
{
DrawCircleV(touchPosition, 30, Color.MAROON);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,79 @@
/*******************************************************************************************
*
* raylib [core] example - Keyboard input
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputKeys
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
Vector2 ballPosition = new((float)screenWidth / 2, (float)screenHeight / 2);
SetTargetFPS(60); // Set target frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
ballPosition.X += 2.0f;
}
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
ballPosition.X -= 2.0f;
}
if (IsKeyDown(KeyboardKey.KEY_UP))
{
ballPosition.Y -= 2.0f;
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
ballPosition.Y += 2.0f;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("move the ball with arrow keys", 10, 10, 20, Color.DARKGRAY);
DrawCircleV(ballPosition, 50, Color.MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,75 @@
/*******************************************************************************************
*
* raylib [core] example - Mouse input
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMouse
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - mouse input");
Vector2 ballPosition = new(-100.0f, -100.0f);
Color ballColor = Color.DARKBLUE;
SetTargetFPS(60);
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
ballPosition = GetMousePosition();
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
ballColor = Color.MAROON;
}
else if (IsMouseButtonPressed(MouseButton.MOUSE_MIDDLE_BUTTON))
{
ballColor = Color.LIME;
}
else if (IsMouseButtonPressed(MouseButton.MOUSE_RIGHT_BUTTON))
{
ballColor = Color.DARKBLUE;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawCircleV(ballPosition, 40, ballColor);
DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,64 @@
/*******************************************************************************************
*
* raylib [core] examples - Mouse wheel input
*
* This test has been created using raylib 1.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMouseWheel
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input mouse wheel");
int boxPositionY = screenHeight / 2 - 40;
// Scrolling speed in pixels
int scrollSpeed = 4;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
boxPositionY -= (int)(GetMouseWheelMove() * scrollSpeed);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectangle(screenWidth / 2 - 40, boxPositionY, 80, 80, Color.MAROON);
DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, Color.GRAY);
DrawText($"Box position Y: {boxPositionY}", 10, 40, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,91 @@
/*******************************************************************************************
*
* raylib [core] example - Input multitouch
*
* This example has been created using raylib 2.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Berni (@Berni8k) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Berni (@Berni8k) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class InputMultitouch
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - input multitouch");
const int MaxTouchPoints = 10;
Vector2[] touchPositions = new Vector2[MaxTouchPoints];
SetTargetFPS(60);
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Get the touch point count (h ow many fingers are touching the screen )
int tCount = GetTouchPointCount();
// Clamp touch points available (set the maximum touch points allowed )
if (tCount > MaxTouchPoints)
{
tCount = MaxTouchPoints;
}
// Get touch points positions
for (int i = 0; i < tCount; i++)
{
touchPositions[i] = GetTouchPosition(i);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
for (int i = 0; i < tCount; i++)
{
// Make sure point is not (0, 0) as this means there is no touch for it
if ((touchPositions[i].X > 0) && (touchPositions[i].Y > 0))
{
// Draw circle and touch index number
DrawCircleV(touchPositions[i], 34, Color.ORANGE);
DrawText(i.ToString(),
(int)touchPositions[i].X - 10,
(int)touchPositions[i].Y - 70,
40,
Color.BLACK
);
}
}
DrawText("touch the screen at multiple locations to get multiple balls", 10, 10, 20, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,161 @@
/*******************************************************************************************
*
* raylib example - loading thread
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Threading;
using static Raylib_cs.Raylib;
using static Raylib_cs.Color;
using static Raylib_cs.KeyboardKey;
namespace Examples.Core;
enum State
{
STATE_WAITING,
STATE_LOADING,
STATE_FINISHED
}
public class LoadingThread
{
// C# bool is atomic. Used for synchronization
// https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references
// Data Loaded completion indicator
static bool dataLoaded = false;
// Data progress accumulator
static int dataProgress = 0;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - loading thread");
// Loading data thread id
Thread thread = new(new ThreadStart(LoadDataThread));
State state = State.STATE_WAITING;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
switch (state)
{
case State.STATE_WAITING:
{
if (IsKeyPressed(KEY_ENTER))
{
thread.Start();
//int error = pthread_create(ref, NULL, ref, NULL);
//if (error != 0) TraceLog(TraceLogLevel.LOG_ERROR, "Error creating loading thread");
//else TraceLog(TraceLogLevel.LOG_INFO, "Loading thread initialized successfully");
state = State.STATE_LOADING;
}
}
break;
case State.STATE_LOADING:
{
framesCounter++;
if (dataLoaded)
{
framesCounter = 0;
state = State.STATE_FINISHED;
}
}
break;
case State.STATE_FINISHED:
{
if (IsKeyPressed(KEY_ENTER))
{
// Reset everything to launch again
// atomic_store(ref, false);
dataProgress = 0;
state = State.STATE_WAITING;
}
}
break;
default: break;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
switch (state)
{
case State.STATE_WAITING:
DrawText("PRESS ENTER to START LOADING DATA", 150, 170, 20, DARKGRAY);
break;
case State.STATE_LOADING:
{
DrawRectangle(150, 200, dataProgress, 60, SKYBLUE);
if ((framesCounter / 15) % 2 == 0) DrawText("LOADING DATA...", 240, 210, 40, DARKBLUE);
}
break;
case State.STATE_FINISHED:
{
DrawRectangle(150, 200, 500, 60, LIME);
DrawText("DATA LOADED!", 250, 210, 40, GREEN);
}
break;
default: break;
}
DrawRectangleLines(150, 200, 500, 60, DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
// Loading data thread function definition
static void LoadDataThread()
{
int timeCounter = 0; // Time counted in ms
// clock_t prevTime = clock(); // Previous time
// We simulate data loading with a time counter for 5 seconds
while (timeCounter < 5000)
{
//clock_t currentTime = clock() - prevTime;
//timeCounter = currentTime*1000/CLOCKS_PER_SEC;
timeCounter += 1;
// We accumulate time over a global variable to be used in
// main thread as a progress bar
dataProgress = timeCounter / 10;
}
// When data has finished loading, we set global variable
dataLoaded = true;
}
}

122
Examples/Core/Picking3D.cs Normal file
View File

@ -0,0 +1,122 @@
/*******************************************************************************************
*
* raylib [core] example - Picking in 3d mode
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class Picking3d
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d picking");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 cubePosition = new(0.0f, 1.0f, 0.0f);
Vector3 cubeSize = new(2.0f, 2.0f, 2.0f);
// Picking line ray
Ray ray = new(new Vector3(0.0f, 0.0f, 0.0f), Vector3.Zero);
RayCollision collision = new();
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
if (!collision.Hit)
{
ray = GetMouseRay(GetMousePosition(), camera);
// Check collision between ray and box
BoundingBox box = new(
cubePosition - cubeSize / 2,
cubePosition + cubeSize / 2
);
collision = GetRayCollisionBox(ray, box);
}
else
{
collision.Hit = false;
}
ray = GetMouseRay(GetMousePosition(), camera);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
if (collision.Hit)
{
DrawCube(cubePosition, cubeSize.X, cubeSize.Y, cubeSize.Z, Color.RED);
DrawCubeWires(cubePosition, cubeSize.X, cubeSize.Y, cubeSize.Z, Color.MAROON);
DrawCubeWires(cubePosition, cubeSize.X + 0.2f, cubeSize.Y + 0.2f, cubeSize.Z + 0.2f, Color.GREEN);
}
else
{
DrawCube(cubePosition, cubeSize.X, cubeSize.Y, cubeSize.Z, Color.GRAY);
DrawCubeWires(cubePosition, cubeSize.X, cubeSize.Y, cubeSize.Z, Color.DARKGRAY);
}
DrawRay(ray, Color.MAROON);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("Try selecting the box with mouse!", 240, 10, 20, Color.DARKGRAY);
if (collision.Hit)
{
int posX = (screenWidth - MeasureText("BOX SELECTED", 30)) / 2;
DrawText("BOX SELECTED", posX, (int)(screenHeight * 0.1f), 30, Color.GREEN);
}
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,71 @@
/*******************************************************************************************
*
* raylib [core] example - Generate random values
*
* This example has been created using raylib 1.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class RandomValues
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - generate random values");
// Variable used to count frames
int framesCounter = 0;
// Get a random integer number between -8 and 5 (both included)
int randValue = GetRandomValue(-8, 5);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
framesCounter++;
// Every two seconds (120 frames) a new random value is generated
if (((framesCounter / 120) % 2) == 1)
{
randValue = GetRandomValue(-8, 5);
framesCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Every 2 seconds a new random value is generated:", 130, 100, 20, Color.MAROON);
DrawText($"{randValue}", 360, 180, 80, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,84 @@
/*******************************************************************************************
*
* raylib [core] example - Scissor test
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Dill (@MysteriousSpace) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Dill (@MysteriousSpace)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class ScissorTest
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - scissor test");
Rectangle scissorArea = new(0, 0, 300, 300);
bool scissorMode = true;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_S))
{
scissorMode = !scissorMode;
}
// Centre the scissor area around the mouse position
scissorArea.X = GetMouseX() - scissorArea.Width / 2;
scissorArea.Y = GetMouseY() - scissorArea.Height / 2;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (scissorMode)
{
BeginScissorMode((int)scissorArea.X, (int)scissorArea.Y, (int)scissorArea.Width, (int)scissorArea.Height);
}
// Draw full screen rectangle and some text
// NOTE: Only part defined by scissor area will be rendered
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color.RED);
DrawText("Move the mouse around to reveal this text!", 190, 200, 20, Color.LIGHTGRAY);
if (scissorMode)
{
EndScissorMode();
}
DrawRectangleLinesEx(scissorArea, 1, Color.BLACK);
DrawText("Press S to toggle scissor test", 10, 10, 20, Color.BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,136 @@
/*******************************************************************************************
*
* raylib [core] example - smooth pixel-perfect camera
*
* This example has been created using raylib 3.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Giancamillo Alessandroni (@NotManyIdeasDev) and
* reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Giancamillo Alessandroni (@NotManyIdeasDev) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public static class SmoothPixelPerfect
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int virtualScreenWidth = 160;
const int virtualScreenHeight = 90;
const float virtualRatio = (float)screenWidth / (float)virtualScreenWidth;
InitWindow(screenWidth, screenHeight, "raylib [core] example - smooth pixel-perfect camera");
// Game world camera
Camera2D worldSpaceCamera = new();
worldSpaceCamera.Zoom = 1.0f;
// Smoothing camera
Camera2D screenSpaceCamera = new();
screenSpaceCamera.Zoom = 1.0f;
// This is where we'll draw all our objects.
RenderTexture2D target = LoadRenderTexture(virtualScreenWidth, virtualScreenHeight);
Rectangle rec01 = new(70.0f, 35.0f, 20.0f, 20.0f);
Rectangle rec02 = new(90.0f, 55.0f, 30.0f, 10.0f);
Rectangle rec03 = new(80.0f, 65.0f, 15.0f, 25.0f);
// The target's height is flipped (in the source Rectangle), due to OpenGL reasons
Rectangle sourceRec = new(
0.0f,
0.0f,
(float)target.Texture.Width,
-(float)target.Texture.Height
);
Rectangle destRec = new(
-virtualRatio,
-virtualRatio,
screenWidth + (virtualRatio * 2),
screenHeight + (virtualRatio * 2)
);
Vector2 origin = new(0.0f, 0.0f);
float rotation = 0.0f;
float cameraX = 0.0f;
float cameraY = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
rotation += 60.0f * GetFrameTime(); // Rotate the rectangles, 60 degrees per second
// Make the camera move to demonstrate the effect
cameraX = (MathF.Sin((float)GetTime()) * 50.0f) - 10.0f;
cameraY = MathF.Cos((float)GetTime()) * 30.0f;
// Set the camera's target to the values computed above
screenSpaceCamera.Target = new Vector2(cameraX, cameraY);
// Round worldSpace coordinates, keep decimals into screenSpace coordinates
worldSpaceCamera.Target.X = (int)screenSpaceCamera.Target.X;
screenSpaceCamera.Target.X -= worldSpaceCamera.Target.X;
screenSpaceCamera.Target.X *= virtualRatio;
worldSpaceCamera.Target.Y = (int)screenSpaceCamera.Target.Y;
screenSpaceCamera.Target.Y -= worldSpaceCamera.Target.Y;
screenSpaceCamera.Target.Y *= virtualRatio;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginMode2D(worldSpaceCamera);
DrawRectanglePro(rec01, origin, rotation, Color.BLACK);
DrawRectanglePro(rec02, origin, -rotation, Color.RED);
DrawRectanglePro(rec03, origin, rotation + 45.0f, Color.BLUE);
EndMode2D();
EndTextureMode();
BeginDrawing();
ClearBackground(Color.RED);
BeginMode2D(screenSpaceCamera);
DrawTexturePro(target.Texture, sourceRec, destRec, origin, 0.0f, Color.WHITE);
EndMode2D();
DrawText($"Screen resolution: {screenWidth}x{screenHeight}", 10, 10, 20, Color.DARKBLUE);
DrawText($"World resolution: {virtualScreenWidth}x{virtualScreenHeight}", 10, 40, 20, Color.DARKGREEN);
DrawFPS(GetScreenWidth() - 95, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,174 @@
/*******************************************************************************************
*
* raylib [core] example - split screen
*
* This example has been created using raylib 3.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Jeffery Myers (@JeffM2501) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Jeffery Myers (@JeffM2501)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public unsafe class SplitScreen
{
static Texture2D TextureGrid;
static Camera3D CameraPlayer1;
static Camera3D CameraPlayer2;
// Scene drawing
static void DrawScene()
{
int count = 5;
float spacing = 4;
// Grid of cube trees on a plane to make a "world"
// Simple world plane
DrawPlane(new Vector3(0, 0, 0), new Vector2(50, 50), Color.BEIGE);
for (float x = -count * spacing; x <= count * spacing; x += spacing)
{
for (float z = -count * spacing; z <= count * spacing; z += spacing)
{
DrawCube(new Vector3(x, 1.5f, z), 1, 1, 1, Color.LIME);
DrawCube(new Vector3(x, 0.5f, z), 0.25f, 1, 0.25f, Color.BROWN);
}
}
// Draw a cube at each player's position
DrawCube(CameraPlayer1.Position, 1, 1, 1, Color.RED);
DrawCube(CameraPlayer2.Position, 1, 1, 1, Color.BLUE);
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - split screen");
// Generate a simple texture to use for trees
Image img = GenImageChecked(256, 256, 32, 32, Color.DARKGRAY, Color.WHITE);
TextureGrid = LoadTextureFromImage(img);
UnloadImage(img);
SetTextureFilter(TextureGrid, TextureFilter.TEXTURE_FILTER_ANISOTROPIC_16X);
SetTextureWrap(TextureGrid, TextureWrap.TEXTURE_WRAP_CLAMP);
// Setup player 1 camera and screen
CameraPlayer1.FovY = 45.0f;
CameraPlayer1.Up.Y = 1.0f;
CameraPlayer1.Target.Y = 1.0f;
CameraPlayer1.Position.Z = -3.0f;
CameraPlayer1.Position.Y = 1.0f;
RenderTexture2D screenPlayer1 = LoadRenderTexture(screenWidth / 2, screenHeight);
// Setup player two camera and screen
CameraPlayer2.FovY = 45.0f;
CameraPlayer2.Up.Y = 1.0f;
CameraPlayer2.Target.Y = 3.0f;
CameraPlayer2.Position.X = -3.0f;
CameraPlayer2.Position.Y = 3.0f;
RenderTexture2D screenPlayer2 = LoadRenderTexture(screenWidth / 2, screenHeight);
// Build a flipped rectangle the size of the split view to use for drawing later
Rectangle splitScreenRect = new(
0.0f,
0.0f,
(float)screenPlayer1.Texture.Width,
(float)-screenPlayer1.Texture.Height
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// If anyone moves this frame, how far will they move based on the time since the last frame
// this moves thigns at 10 world units per second, regardless of the actual FPS
float offsetThisFrame = 10.0f * GetFrameTime();
// Move Player1 forward and backwards (no turning)
if (IsKeyDown(KeyboardKey.KEY_W))
{
CameraPlayer1.Position.Z += offsetThisFrame;
CameraPlayer1.Target.Z += offsetThisFrame;
}
else if (IsKeyDown(KeyboardKey.KEY_S))
{
CameraPlayer1.Position.Z -= offsetThisFrame;
CameraPlayer1.Target.Z -= offsetThisFrame;
}
// Move Player2 forward and backwards (no turning)
if (IsKeyDown(KeyboardKey.KEY_UP))
{
CameraPlayer2.Position.X += offsetThisFrame;
CameraPlayer2.Target.X += offsetThisFrame;
}
else if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
CameraPlayer2.Position.X -= offsetThisFrame;
CameraPlayer2.Target.X -= offsetThisFrame;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Draw Player1 view to the render texture
BeginTextureMode(screenPlayer1);
ClearBackground(Color.SKYBLUE);
BeginMode3D(CameraPlayer1);
DrawScene();
EndMode3D();
DrawText("PLAYER 1 W/S to move", 10, 10, 20, Color.RED);
EndTextureMode();
// Draw Player2 view to the render texture
BeginTextureMode(screenPlayer2);
ClearBackground(Color.SKYBLUE);
BeginMode3D(CameraPlayer2);
DrawScene();
EndMode3D();
DrawText("PLAYER 2 UP/DOWN to move", 10, 10, 20, Color.BLUE);
EndTextureMode();
// Draw both views render textures to the screen side by side
BeginDrawing();
ClearBackground(Color.BLACK);
DrawTextureRec(screenPlayer1.Texture, splitScreenRect, new Vector2(0, 0), Color.WHITE);
DrawTextureRec(screenPlayer2.Texture, splitScreenRect, new Vector2(screenWidth / 2.0f, 0), Color.WHITE);
EndDrawing();
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(screenPlayer1);
UnloadRenderTexture(screenPlayer2);
UnloadTexture(TextureGrid);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,202 @@
/*******************************************************************************************
*
* raylib [core] example - Storage save/load values
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class StorageValues
{
// NOTE: Storage positions must start with 0, directly related to file memory layout
enum StorageData
{
Score,
HiScore
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const string storageDataFile = "storage.data";
InitWindow(screenWidth, screenHeight, "raylib [core] example - storage save/load values");
int score = 0;
int hiscore = 0;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_R))
{
score = GetRandomValue(1000, 2000);
hiscore = GetRandomValue(2000, 4000);
}
if (IsKeyPressed(KeyboardKey.KEY_ENTER))
{
SaveStorageValue(storageDataFile, (int)StorageData.Score, score);
SaveStorageValue(storageDataFile, (int)StorageData.HiScore, hiscore);
}
else if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
// NOTE: If requested position could not be found, value 0 is returned
score = LoadStorageValue(storageDataFile, (int)StorageData.Score);
hiscore = LoadStorageValue(storageDataFile, (int)StorageData.HiScore);
}
framesCounter++;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText($"SCORE: {score}", 280, 130, 40, Color.MAROON);
DrawText($"HI-SCORE: {hiscore}", 210, 200, 50, Color.BLACK);
DrawText($"frames: {framesCounter}", 10, 10, 20, Color.LIME);
DrawText("Press R to generate random numbers", 220, 40, 20, Color.LIGHTGRAY);
DrawText("Press ENTER to SAVE values", 250, 310, 20, Color.LIGHTGRAY);
DrawText("Press SPACE to LOAD values", 252, 350, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Save integer value to storage file (to defined position)
// NOTE: Storage positions is directly related to file memory layout (4 bytes each integer)
private static unsafe bool SaveStorageValue(string fileName, uint position, int value)
{
using var fileNameBuffer = fileName.ToUtf8Buffer();
bool success = false;
uint dataSize = 0;
uint newDataSize = 0;
byte* fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
byte* newFileData = null;
if (fileData != null)
{
if (dataSize <= (position * sizeof(int)))
{
// Increase data size up to position and store value
newDataSize = (position + 1) * sizeof(int);
newFileData = (byte*)MemRealloc(fileData, (int)newDataSize);
if (newFileData != null)
{
// RL_REALLOC succeded
int* dataPtr = (int*)newFileData;
dataPtr[position] = value;
}
else
{
// RL_REALLOC failed
uint positionInBytes = position * sizeof(int);
TraceLog(
TraceLogLevel.LOG_WARNING,
@$"FILEIO: [{fileName}] Failed to realloc data ({dataSize}),
position in bytes({positionInBytes}) bigger than actual file size"
);
// We store the old size of the file
newFileData = fileData;
newDataSize = dataSize;
}
}
else
{
// Store the old size of the file
newFileData = fileData;
newDataSize = dataSize;
// Replace value on selected position
int* dataPtr = (int*)newFileData;
dataPtr[position] = value;
}
success = SaveFileData(fileNameBuffer.AsPointer(), newFileData, newDataSize);
MemFree(newFileData);
TraceLog(TraceLogLevel.LOG_INFO, $"FILEIO: [{fileName}] Saved storage value: {value}");
}
else
{
TraceLog(TraceLogLevel.LOG_INFO, $"FILEIO: [{fileName}] File created successfully");
dataSize = (position + 1) * sizeof(int);
fileData = (byte*)MemAlloc((int)dataSize);
int* dataPtr = (int*)fileData;
dataPtr[position] = value;
success = SaveFileData(fileNameBuffer.AsPointer(), fileData, dataSize);
UnloadFileData(fileData);
TraceLog(TraceLogLevel.LOG_INFO, $"FILEIO: [{fileName}] Saved storage value: {value}");
}
return success;
}
// Load integer value from storage file (from defined position)
// NOTE: If requested position could not be found, value 0 is returned
private static unsafe int LoadStorageValue(string fileName, uint position)
{
using var fileNameBuffer = fileName.ToUtf8Buffer();
int value = 0;
uint dataSize = 0;
byte* fileData = LoadFileData(fileNameBuffer.AsPointer(), &dataSize);
if (fileData != null)
{
if (dataSize < (position * 4))
{
TraceLog(
TraceLogLevel.LOG_WARNING,
$"FILEIO: [{fileName}] Failed to find storage position: {value}"
);
}
else
{
int* dataPtr = (int*)fileData;
value = dataPtr[position];
}
UnloadFileData(fileData);
TraceLog(TraceLogLevel.LOG_INFO, $"FILEIO: [{fileName}] Loaded storage value: {value}");
}
return value;
}
}

View File

@ -0,0 +1,191 @@
/*******************************************************************************************
*
* raylib [core] example - VR Simulator (Oculus Rift CV1 parameters)
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class VrSimulator
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 1080;
const int screenHeight = 600;
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [core] example - vr simulator");
// VR device parameters definition
VrDeviceInfo device = new VrDeviceInfo
{
// Oculus Rift CV1 parameters for simulator
HResolution = 2160,
VResolution = 1200,
HScreenSize = 0.133793f,
VScreenSize = 0.0669f,
VScreenCenter = 0.04678f,
EyeToScreenDistance = 0.041f,
LensSeparationDistance = 0.07f,
InterpupillaryDistance = 0.07f,
};
// NOTE: CV1 uses a Fresnel-hybrid-asymmetric lenses with specific distortion compute shaders.
// Following parameters are an approximation to distortion stereo rendering but results differ from actual
// device.
unsafe
{
device.LensDistortionValues[0] = 1.0f;
device.LensDistortionValues[1] = 0.22f;
device.LensDistortionValues[2] = 0.24f;
device.LensDistortionValues[3] = 0.0f;
device.ChromaAbCorrection[0] = 0.996f;
device.ChromaAbCorrection[1] = -0.004f;
device.ChromaAbCorrection[2] = 1.014f;
device.ChromaAbCorrection[3] = 0.0f;
}
// Load VR stereo config for VR device parameteres (Oculus Rift CV1 parameters)
VrStereoConfig config = LoadVrStereoConfig(device);
// Distortion shader (uses device lens distortion and chroma)
Shader distortion = LoadShader(null, "resources/distortion330.fs");
// Update distortion shader with lens and distortion-scale parameters
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "leftLensCenter"),
config.LeftLensCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "rightLensCenter"),
config.RightLensCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "leftScreenCenter"),
config.LeftScreenCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "rightScreenCenter"),
config.RightScreenCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "scale"),
config.Scale,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
distortion,
GetShaderLocation(distortion, "scaleIn"),
config.ScaleIn,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
unsafe
{
SetShaderValue(
distortion,
GetShaderLocation(distortion, "deviceWarpParam"),
device.LensDistortionValues,
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
SetShaderValue(
distortion,
GetShaderLocation(distortion, "chromaAbParam"),
device.ChromaAbCorrection,
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
}
// Initialize framebuffer for stereo rendering
// NOTE: Screen size should match HMD aspect ratio
RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight());
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(5.0f, 2.0f, 5.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 60.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
SetTargetFPS(90); // Set our game to run at 90 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FIRST_PERSON);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginVrStereoMode(config);
BeginMode3D(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, Color.RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, Color.MAROON);
DrawGrid(40, 1.0f);
EndMode3D();
EndVrStereoMode();
EndTextureMode();
BeginShaderMode(distortion);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, (float)target.Texture.Width, (float)-target.Texture.Height),
new Vector2(0.0f, 0.0f),
Color.WHITE
);
EndShaderMode();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadVrStereoConfig(config);
UnloadRenderTexture(target);
UnloadShader(distortion);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,276 @@
/*******************************************************************************************
*
* raylib [core] example - window flags
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.ConfigFlags;
namespace Examples.Core;
public class WindowFlags
{
public static int Main()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Possible window flags
/*
FLAG_VSYNC_HINT
FLAG_FULLSCREEN_MODE -> not working properly -> wrong scaling!
FLAG_WINDOW_RESIZABLE
FLAG_WINDOW_UNDECORATED
FLAG_WINDOW_TRANSPARENT
FLAG_WINDOW_HIDDEN
FLAG_WINDOW_MINIMIZED -> Not supported on window creation
FLAG_WINDOW_MAXIMIZED -> Not supported on window creation
FLAG_WINDOW_UNFOCUSED
FLAG_WINDOW_TOPMOST
FLAG_WINDOW_HIGHDPI -> errors after minimize-resize, fb size is recalculated
FLAG_WINDOW_ALWAYS_RUN
FLAG_MSAA_4X_HINT
*/
// Set configuration flags for window creation
SetConfigFlags(FLAG_VSYNC_HINT | FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [core] example - window flags");
Vector2 ballPosition = new(GetScreenWidth() / 2, GetScreenHeight() / 2);
Vector2 ballSpeed = new(5.0f, 4.0f);
int ballRadius = 20;
int framesCounter = 0;
//----------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//-----------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_F))
{
// modifies window size when scaling!
ToggleFullscreen();
}
if (IsKeyPressed(KeyboardKey.KEY_R))
{
if (IsWindowState(FLAG_WINDOW_RESIZABLE))
{
ClearWindowState(FLAG_WINDOW_RESIZABLE);
}
else
{
SetWindowState(FLAG_WINDOW_RESIZABLE);
}
}
if (IsKeyPressed(KeyboardKey.KEY_D))
{
if (IsWindowState(FLAG_WINDOW_UNDECORATED))
{
ClearWindowState(FLAG_WINDOW_UNDECORATED);
}
else
{
SetWindowState(FLAG_WINDOW_UNDECORATED);
}
}
if (IsKeyPressed(KeyboardKey.KEY_H))
{
if (!IsWindowState(FLAG_WINDOW_HIDDEN))
{
SetWindowState(FLAG_WINDOW_HIDDEN);
}
framesCounter = 0;
}
if (IsWindowState(FLAG_WINDOW_HIDDEN))
{
framesCounter++;
if (framesCounter >= 240)
{
// Show window after 3 seconds
ClearWindowState(FLAG_WINDOW_HIDDEN);
}
}
if (IsKeyPressed(KeyboardKey.KEY_N))
{
if (!IsWindowState(FLAG_WINDOW_MINIMIZED))
{
MinimizeWindow();
}
framesCounter = 0;
}
if (IsWindowState(FLAG_WINDOW_MINIMIZED))
{
framesCounter++;
if (framesCounter >= 240)
{
// Restore window after 3 seconds
RestoreWindow();
}
}
if (IsKeyPressed(KeyboardKey.KEY_M))
{
// NOTE: Requires FLAG_WINDOW_RESIZABLE enabled!
if (IsWindowState(FLAG_WINDOW_MAXIMIZED))
{
RestoreWindow();
}
else
{
MaximizeWindow();
}
}
if (IsKeyPressed(KeyboardKey.KEY_U))
{
if (IsWindowState(FLAG_WINDOW_UNFOCUSED))
{
ClearWindowState(FLAG_WINDOW_UNFOCUSED);
}
else
{
SetWindowState(FLAG_WINDOW_UNFOCUSED);
}
}
if (IsKeyPressed(KeyboardKey.KEY_T))
{
if (IsWindowState(FLAG_WINDOW_TOPMOST))
{
ClearWindowState(FLAG_WINDOW_TOPMOST);
}
else
{
SetWindowState(FLAG_WINDOW_TOPMOST);
}
}
if (IsKeyPressed(KeyboardKey.KEY_A))
{
if (IsWindowState(FLAG_WINDOW_ALWAYS_RUN))
{
ClearWindowState(FLAG_WINDOW_ALWAYS_RUN);
}
else
{
SetWindowState(FLAG_WINDOW_ALWAYS_RUN);
}
}
if (IsKeyPressed(KeyboardKey.KEY_V))
{
if (IsWindowState(FLAG_VSYNC_HINT))
{
ClearWindowState(FLAG_VSYNC_HINT);
}
else
{
SetWindowState(FLAG_VSYNC_HINT);
}
}
// Bouncing ball logic
ballPosition.X += ballSpeed.X;
ballPosition.Y += ballSpeed.Y;
if ((ballPosition.X >= (GetScreenWidth() - ballRadius)) || (ballPosition.X <= ballRadius))
{
ballSpeed.X *= -1.0f;
}
if ((ballPosition.Y >= (GetScreenHeight() - ballRadius)) || (ballPosition.Y <= ballRadius))
{
ballSpeed.Y *= -1.0f;
}
//-----------------------------------------------------
// Draw
//-----------------------------------------------------
BeginDrawing();
if (IsWindowState(FLAG_WINDOW_TRANSPARENT))
{
ClearBackground(Color.BLANK);
}
else
{
ClearBackground(Color.RAYWHITE);
}
DrawCircleV(ballPosition, ballRadius, Color.MAROON);
DrawRectangleLinesEx(new Rectangle(0, 0, GetScreenWidth(), GetScreenHeight()), 4, Color.RAYWHITE);
DrawCircleV(GetMousePosition(), 10, Color.DARKBLUE);
DrawFPS(10, 10);
DrawText($"Screen Size: [{GetScreenWidth()}, {GetScreenHeight()}]", 10, 40, 10, Color.GREEN);
// Draw window state info
Color on = Color.LIME;
Color off = Color.MAROON;
DrawText("Following flags can be set after window creation:", 10, 60, 10, Color.GRAY);
DrawWindowState(FLAG_FULLSCREEN_MODE, "[F] FLAG_FULLSCREEN_MODE: ", 10, 80, 10);
DrawWindowState(FLAG_WINDOW_RESIZABLE, "[R] FLAG_WINDOW_RESIZABLE: ", 10, 100, 10);
DrawWindowState(FLAG_WINDOW_UNDECORATED, "[D] FLAG_WINDOW_UNDECORATED: ", 10, 120, 10);
DrawWindowState(FLAG_WINDOW_HIDDEN, "[H] FLAG_WINDOW_HIDDEN: ", 10, 140, 10);
DrawWindowState(FLAG_WINDOW_MINIMIZED, "[N] FLAG_WINDOW_MINIMIZED: ", 10, 160, 10);
DrawWindowState(FLAG_WINDOW_MAXIMIZED, "[M] FLAG_WINDOW_MAXIMIZED: ", 10, 180, 10);
DrawWindowState(FLAG_WINDOW_UNFOCUSED, "[G] FLAG_WINDOW_UNFOCUSED: ", 10, 200, 10);
DrawWindowState(FLAG_WINDOW_TOPMOST, "[T] FLAG_WINDOW_TOPMOST: ", 10, 220, 10);
DrawWindowState(FLAG_WINDOW_ALWAYS_RUN, "[A] FLAG_WINDOW_ALWAYS_RUN: ", 10, 240, 10);
DrawWindowState(FLAG_VSYNC_HINT, "[V] FLAG_VSYNC_HINT: ", 10, 260, 10);
DrawText("Following flags can only be set before window creation:", 10, 300, 10, Color.GRAY);
DrawWindowState(FLAG_WINDOW_HIGHDPI, "[F] FLAG_WINDOW_HIGHDPI: ", 10, 320, 10);
DrawWindowState(FLAG_WINDOW_TRANSPARENT, "[F] FLAG_WINDOW_TRANSPARENT: ", 10, 340, 10);
DrawWindowState(FLAG_MSAA_4X_HINT, "[F] FLAG_MSAA_4X_HINT: ", 10, 360, 10);
EndDrawing();
//-----------------------------------------------------
}
// De-Initialization
//---------------------------------------------------------
CloseWindow();
//----------------------------------------------------------
return 0;
}
static void DrawWindowState(ConfigFlags flag, string text, int posX, int posY, int fontSize)
{
Color onColor = Color.LIME;
Color offColor = Color.MAROON;
if (Raylib.IsWindowState(flag))
{
DrawText($"{text} on", posX, posY, fontSize, onColor);
}
else
{
DrawText($"{text} off", posX, posY, fontSize, offColor);
}
}
}

View File

@ -0,0 +1,139 @@
/*******************************************************************************************
*
* raylib [core] example - window scale letterbox
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class WindowLetterbox
{
public static int Main()
{
const int windowWidth = 800;
const int windowHeight = 450;
// Enable config flags for resizable window and vertical synchro
SetConfigFlags(ConfigFlags.FLAG_WINDOW_RESIZABLE | ConfigFlags.FLAG_VSYNC_HINT);
InitWindow(windowWidth, windowHeight, "raylib [core] example - window scale letterbox");
SetWindowMinSize(320, 240);
int gameScreenWidth = 640;
int gameScreenHeight = 480;
// Render texture initialization, used to hold the rendering result so we can easily resize it
RenderTexture2D target = LoadRenderTexture(gameScreenWidth, gameScreenHeight);
SetTextureFilter(target.Texture, TextureFilter.TEXTURE_FILTER_BILINEAR);
Color[] colors = new Color[10];
for (int i = 0; i < 10; i++)
{
colors[i] = new Color(GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Compute required framebuffer scaling
float scale = MathF.Min(
(float)GetScreenWidth() / gameScreenWidth,
(float)GetScreenHeight() / gameScreenHeight
);
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
// Recalculate random colors for the bars
for (int i = 0; i < 10; i++)
{
colors[i] = new Color(
GetRandomValue(100, 250),
GetRandomValue(50, 150),
GetRandomValue(10, 100),
255
);
}
}
// Update virtual mouse (clamped mouse value behind game screen)
Vector2 mouse = GetMousePosition();
Vector2 virtualMouse = Vector2.Zero;
virtualMouse.X = (mouse.X - (GetScreenWidth() - (gameScreenWidth * scale)) * 0.5f) / scale;
virtualMouse.Y = (mouse.Y - (GetScreenHeight() - (gameScreenHeight * scale)) * 0.5f) / scale;
Vector2 max = new((float)gameScreenWidth, (float)gameScreenHeight);
virtualMouse = Vector2.Clamp(virtualMouse, Vector2.Zero, max);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.BLACK);
// Draw everything in the render texture, note this will not be rendered on screen, yet
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
for (int i = 0; i < 10; i++)
{
DrawRectangle(0, (gameScreenHeight / 10) * i, gameScreenWidth, gameScreenHeight / 10, colors[i]);
}
DrawText(
"If executed inside a window,\nyou can resize the window,\nand see the screen scaling!",
10,
25,
20,
Color.WHITE
);
DrawText($"Default Mouse: [{(int)mouse.X} {(int)mouse.Y}]", 350, 25, 20, Color.GREEN);
DrawText($"Virtual Mouse: [{(int)virtualMouse.X}, {(int)virtualMouse.Y}]", 350, 55, 20, Color.YELLOW);
EndTextureMode();
// Draw RenderTexture2D to window, properly scaled
Rectangle sourceRec = new(
0.0f,
0.0f,
(float)target.Texture.Width,
(float)-target.Texture.Height
);
Rectangle destRec = new(
(GetScreenWidth() - ((float)gameScreenWidth * scale)) * 0.5f,
(GetScreenHeight() - ((float)gameScreenHeight * scale)) * 0.5f,
(float)gameScreenWidth * scale,
(float)gameScreenHeight * scale
);
DrawTexturePro(target.Texture, sourceRec, destRec, new Vector2(0, 0), 0.0f, Color.WHITE);
EndDrawing();
//--------------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,97 @@
/*******************************************************************************************
*
* raylib [core] example - World to screen
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Core;
public class WorldScreen
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 3d camera free");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 cubePosition = new(0.0f, 0.0f, 0.0f);
Vector2 cubeScreenPosition;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
// Calculate cube screen space position (with a little offset to be in top)
cubeScreenPosition = GetWorldToScreen(
new Vector3(cubePosition.X, cubePosition.Y + 2.5f, cubePosition.Z),
camera
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawCube(cubePosition, 2.0f, 2.0f, 2.0f, Color.RED);
DrawCubeWires(cubePosition, 2.0f, 2.0f, 2.0f, Color.MAROON);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText(
"Enemy: 100 / 100",
(int)cubeScreenPosition.X - MeasureText("Enemy: 100 / 100", 20) / 2,
(int)cubeScreenPosition.Y,
20,
Color.BLACK
);
DrawText(
"Text is always on top of the cube",
(screenWidth - MeasureText("Text is always on top of the cube", 20)) / 2,
25,
20,
Color.GRAY
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

264
Examples/Easings.cs Normal file
View File

@ -0,0 +1,264 @@
using System;
namespace Examples;
public static class Easings
{
// Linear Easing functions
public static float EaseLinearNone(float t, float b, float c, float d)
{
return (c * t / d + b);
}
public static float EaseLinearIn(float t, float b, float c, float d)
{
return (c * t / d + b);
}
public static float EaseLinearOut(float t, float b, float c, float d)
{
return (c * t / d + b);
}
public static float EaseLinearInOut(float t, float b, float c, float d)
{
return (c * t / d + b);
}
// Sine Easing functions
public static float EaseSineIn(float t, float b, float c, float d)
{
return (-c * MathF.Cos(t / d * (MathF.PI / 2)) + c + b);
}
public static float EaseSineOut(float t, float b, float c, float d)
{
return (c * MathF.Sin(t / d * (MathF.PI / 2)) + b);
}
public static float EaseSineInOut(float t, float b, float c, float d)
{
return (-c / 2 * (MathF.Cos(MathF.PI * t / d) - 1) + b);
}
// Circular Easing functions
public static float EaseCircIn(float t, float b, float c, float d)
{
return (-c * (MathF.Sqrt(1 - (t /= d) * t) - 1) + b);
}
public static float EaseCircOut(float t, float b, float c, float d)
{
return (c * MathF.Sqrt(1 - (t = t / d - 1) * t) + b);
}
public static float EaseCircInOut(float t, float b, float c, float d)
{
if ((t /= d / 2) < 1)
{
return (-c / 2 * (MathF.Sqrt(1 - t * t) - 1) + b);
}
return (c / 2 * (MathF.Sqrt(1 - t * (t -= 2)) + 1) + b);
}
// Cubic Easing functions
public static float EaseCubicIn(float t, float b, float c, float d)
{
return (c * (t /= d) * t * t + b);
}
public static float EaseCubicOut(float t, float b, float c, float d)
{
return (c * ((t = t / d - 1) * t * t + 1) + b);
}
public static float EaseCubicInOut(float t, float b, float c, float d)
{
if ((t /= d / 2) < 1)
{
return (c / 2 * t * t * t + b);
}
return (c / 2 * ((t -= 2) * t * t + 2) + b);
}
// Quadratic Easing functions
public static float EaseQuadIn(float t, float b, float c, float d)
{
return (c * (t /= d) * t + b);
}
public static float EaseQuadOut(float t, float b, float c, float d)
{
return (-c * (t /= d) * (t - 2) + b);
}
public static float EaseQuadInOut(float t, float b, float c, float d)
{
if ((t /= d / 2) < 1)
{
return (((c / 2) * (t * t)) + b);
}
return (-c / 2 * (((t - 2) * (--t)) - 1) + b);
}
// Exponential Easing functions
public static float EaseExpoIn(float t, float b, float c, float d)
{
return (t == 0) ? b : (c * MathF.Pow(2, 10 * (t / d - 1)) + b);
}
public static float EaseExpoOut(float t, float b, float c, float d)
{
return (t == d) ? (b + c) : (c * (-MathF.Pow(2, -10 * t / d) + 1) + b);
}
public static float EaseExpoInOut(float t, float b, float c, float d)
{
if (t == 0)
{
return b;
}
if (t == d)
{
return (b + c);
}
if ((t /= d / 2) < 1)
{
return (c / 2 * MathF.Pow(2, 10 * (t - 1)) + b);
}
return (c / 2 * (-MathF.Pow(2, -10 * --t) + 2) + b);
}
// Back Easing functions
public static float EaseBackIn(float t, float b, float c, float d)
{
float s = 1.70158f;
float postFix = t /= d;
return (c * (postFix) * t * ((s + 1) * t - s) + b);
}
public static float EaseBackOut(float t, float b, float c, float d)
{
float s = 1.70158f;
return (c * ((t = t / d - 1) * t * ((s + 1) * t + s) + 1) + b);
}
public static float EaseBackInOut(float t, float b, float c, float d)
{
float s = 1.70158f;
if ((t /= d / 2) < 1)
{
return (c / 2 * (t * t * (((s *= (1.525f)) + 1) * t - s)) + b);
}
float postFix = t -= 2;
return (c / 2 * ((postFix) * t * (((s *= (1.525f)) + 1) * t + s) + 2) + b);
}
// Bounce Easing functions
public static float EaseBounceOut(float t, float b, float c, float d)
{
if ((t /= d) < (1 / 2.75f))
{
return (c * (7.5625f * t * t) + b);
}
else if (t < (2 / 2.75f))
{
float postFix = t -= (1.5f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.75f) + b);
}
else if (t < (2.5 / 2.75))
{
float postFix = t -= (2.25f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.9375f) + b);
}
else
{
float postFix = t -= (2.625f / 2.75f);
return (c * (7.5625f * (postFix) * t + 0.984375f) + b);
}
}
public static float EaseBounceIn(float t, float b, float c, float d)
{
return (c - EaseBounceOut(d - t, 0, c, d) + b);
}
public static float EaseBounceInOut(float t, float b, float c, float d)
{
if (t < d / 2)
{
return (EaseBounceIn(t * 2, 0, c, d) * 0.5f + b);
}
else
{
return (EaseBounceOut(t * 2 - d, 0, c, d) * 0.5f + c * 0.5f + b);
}
}
// Elastic Easing functions
public static float EaseElasticIn(float t, float b, float c, float d)
{
if (t == 0)
{
return b;
}
if ((t /= d) == 1)
{
return (b + c);
}
float p = d * 0.3f;
float a = c;
float s = p / 4;
float postFix = a * MathF.Pow(2, 10 * (t -= 1));
return (-(postFix * MathF.Sin((t * d - s) * (2 * MathF.PI) / p)) + b);
}
public static float EaseElasticOut(float t, float b, float c, float d)
{
if (t == 0)
{
return b;
}
if ((t /= d) == 1)
{
return (b + c);
}
float p = d * 0.3f;
float a = c;
float s = p / 4;
return (a * MathF.Pow(2, -10 * t) * MathF.Sin((t * d - s) * (2 * MathF.PI) / p) + c + b);
}
public static float EaseElasticInOut(float t, float b, float c, float d)
{
if (t == 0)
{
return b;
}
if ((t /= d / 2) == 2)
{
return (b + c);
}
float p = d * (0.3f * 1.5f);
float a = c;
float s = p / 4;
float postFix = 0f;
if (t < 1)
{
postFix = a * MathF.Pow(2, 10 * (t -= 1));
return -0.5f * (postFix * MathF.Sin((t * d - s) * (2 * MathF.PI) / p)) + b;
}
postFix = a * MathF.Pow(2, -10 * (t -= 1));
return (postFix * MathF.Sin((t * d - s) * (2 * MathF.PI) / p) * 0.5f + c + b);
}
}

24
Examples/Examples.csproj Normal file
View File

@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net5.0;net6.0</TargetFrameworks>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<StartupObject>Examples.Program</StartupObject>
<RunWorkingDirectory>$(MSBuildThisFileDirectory)</RunWorkingDirectory>
<LangVersion>10</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Compile Remove="Core/LoadingThread.cs"/>
<Compile Remove="Text/Unicode.cs"/>
</ItemGroup>
<ItemGroup>
<Using Include="Raylib_cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Raylib-cs\Raylib-cs.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,126 @@
/*******************************************************************************************
*
* raylib [models] example - Load 3d model with animations and play them
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Culacant (@culacant) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Culacant (@culacant) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* To export a model from blender, make sure it is not posed, the vertices need to be in the
* same position as they would be in edit mode.
* and that the scale of your models is set to 0. Scaling can be done from the export menu.
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class AnimationDemo
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - model animation");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(10.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/iqm/guy.iqm");
Texture2D texture = LoadTexture("resources/models/iqm/guytex.png");
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
// Load animation data
uint animsCount = 0;
var anims = LoadModelAnimations("resources/models/iqm/guyanim.iqm", ref animsCount);
int animFrameCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
// Play animation when spacebar is held down
if (IsKeyDown(KeyboardKey.KEY_SPACE))
{
animFrameCounter++;
UpdateModelAnimation(model, anims[0], animFrameCounter);
if (animFrameCounter >= anims[0].FrameCount)
{
animFrameCounter = 0;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModelEx(
model,
position,
new Vector3(1.0f, 0.0f, 0.0f),
-90.0f,
new Vector3(1.0f, 1.0f, 1.0f),
Color.WHITE
);
for (int i = 0; i < model.BoneCount; i++)
{
var framePoses = anims[0].FramePoses;
DrawCube(framePoses[animFrameCounter][i].Translation, 0.2f, 0.2f, 0.2f, Color.RED);
}
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("PRESS SPACE to PLAY MODEL ANIMATION", 10, 10, 20, Color.MAROON);
DrawText("(c) Guy IQM 3D model by @culacant", screenWidth - 200, screenHeight - 20, 10, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
for (int i = 0; i < animsCount; i++)
{
UnloadModelAnimation(anims[i]);
}
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,134 @@
/*******************************************************************************************
*
* raylib [models] example - Drawing billboards
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class BillboardDemo
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - drawing billboards");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(5.0f, 4.0f, 5.0f);
camera.Target = new Vector3(0.0f, 2.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Our texture billboard
Texture2D bill = LoadTexture("resources/billboard.png");
// Position of billboard billboard
Vector3 billPositionStatic = new(0.0f, 2.0f, 0.0f);
Vector3 billPositionRotating = new(1.0f, 2.0f, 1.0f);
// Entire billboard texture, source is used to take a segment from a larger texture.
Rectangle source = new(0.0f, 0.0f, (float)bill.Width, (float)bill.Height);
// NOTE: Billboard locked on axis-Y
Vector3 billUp = new(0.0f, 1.0f, 0.0f);
// Rotate around origin
// Here we choose to rotate around the image center
// NOTE: (-1, 1) is the range where origin.X, origin.Y is inside the texture
Vector2 rotateOrigin = Vector2.Zero;
// Distance is needed for the correct billboard draw order
// Larger distance (further away from the camera) should be drawn prior to smaller distance.
float distanceStatic = 0.0f;
float distanceRotating = 0.0f;
float rotation = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
rotation += 0.4f;
distanceStatic = Vector3.Distance(camera.Position, billPositionStatic);
distanceRotating = Vector3.Distance(camera.Position, billPositionRotating);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawGrid(10, 1.0f);
// Draw order matters!
if (distanceStatic > distanceRotating)
{
DrawBillboard(camera, bill, billPositionStatic, 2.0f, Color.WHITE);
DrawBillboardPro(
camera,
bill,
source,
billPositionRotating,
billUp,
new Vector2(1.0f, 1.0f),
rotateOrigin,
rotation,
Color.WHITE
);
}
else
{
DrawBillboardPro(
camera,
bill,
source,
billPositionRotating,
billUp,
new Vector2(1.0f, 1.0f),
rotateOrigin,
rotation,
Color.WHITE
);
DrawBillboard(camera, bill, billPositionStatic, 2.0f, Color.WHITE);
}
EndMode3D();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(bill);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,144 @@
/*******************************************************************************************
*
* raylib [models] example - Detect basic 3d collisions (box vs sphere vs box)
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class BoxCollisions
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - box collisions");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Vector3 playerPosition = new(0.0f, 1.0f, 2.0f);
Vector3 playerSize = new(1.0f, 2.0f, 1.0f);
Color playerColor = Color.GREEN;
Vector3 enemyBoxPos = new(-4.0f, 1.0f, 0.0f);
Vector3 enemyBoxSize = new(2.0f, 2.0f, 2.0f);
Vector3 enemySpherePos = new(4.0f, 0.0f, 0.0f);
float enemySphereSize = 1.5f;
bool collision = false;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Move player
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
playerPosition.X += 0.2f;
}
else if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
playerPosition.X -= 0.2f;
}
else if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
playerPosition.Z += 0.2f;
}
else if (IsKeyDown(KeyboardKey.KEY_UP))
{
playerPosition.Z -= 0.2f;
}
collision = false;
// Check collisions player vs enemy-box
BoundingBox box1 = new(
playerPosition - (playerSize / 2),
playerPosition + (playerSize / 2)
);
BoundingBox box2 = new(
enemyBoxPos - (enemyBoxSize / 2),
enemyBoxPos + (enemyBoxSize / 2)
);
if (CheckCollisionBoxes(box1, box2))
{
collision = true;
}
// Check collisions player vs enemy-sphere
if (CheckCollisionBoxSphere(box1, enemySpherePos, enemySphereSize))
{
collision = true;
}
if (collision)
{
playerColor = Color.RED;
}
else
{
playerColor = Color.GREEN;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
// Draw enemy-box
DrawCube(enemyBoxPos, enemyBoxSize.X, enemyBoxSize.Y, enemyBoxSize.Z, Color.GRAY);
DrawCubeWires(enemyBoxPos, enemyBoxSize.X, enemyBoxSize.Y, enemyBoxSize.Z, Color.DARKGRAY);
// Draw enemy-sphere
DrawSphere(enemySpherePos, enemySphereSize, Color.GRAY);
DrawSphereWires(enemySpherePos, enemySphereSize, 16, 16, Color.DARKGRAY);
// Draw player
DrawCubeV(playerPosition, playerSize, playerColor);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("Move player with cursors to collide", 220, 40, 20, Color.GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,104 @@
/*******************************************************************************************
*
* raylib [models] example - Cubicmap loading and drawing
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class CubicmapDemo
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - cubesmap loading and drawing");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(16.0f, 14.0f, 16.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Image image = LoadImage("resources/cubicmap.png");
Texture2D cubicmap = LoadTextureFromImage(image);
Mesh mesh = GenMeshCubicmap(image, new Vector3(1.0f, 1.0f, 1.0f));
Model model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 mapPosition = new(-16.0f, 0.0f, -8.0f);
UnloadImage(image);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, mapPosition, 1.0f, Color.WHITE);
EndMode3D();
Vector2 position = new(screenWidth - cubicmap.Width * 4 - 20, 20);
DrawTextureEx(cubicmap, position, 0.0f, 4.0f, Color.WHITE);
DrawRectangleLines(
screenWidth - cubicmap.Width * 4 - 20,
20,
cubicmap.Width * 4,
cubicmap.Height * 4,
Color.GREEN
);
DrawText("cubicmap image used to", 658, 90, 10, Color.GRAY);
DrawText("generate map 3d model", 658, 104, 10, Color.GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(cubicmap);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,155 @@
/*******************************************************************************************
*
* raylib [models] example - first person maze
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class FirstPersonMaze
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - first person maze");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.2f, 0.4f, 0.2f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Image imMap = LoadImage("resources/cubicmap.png");
Texture2D cubicmap = LoadTextureFromImage(imMap);
Mesh mesh = GenMeshCubicmap(imMap, new Vector3(1.0f, 1.0f, 1.0f));
Model model = LoadModelFromMesh(mesh);
// NOTE: By default each cube is mapped to one part of texture atlas
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
// Get map image data to be used for collision detection
Color* mapPixels = LoadImageColors(imMap);
UnloadImage(imMap);
Vector3 mapPosition = new(-16.0f, 0.0f, -8.0f);
Vector3 playerPosition = camera.Position;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
Vector3 oldCamPos = camera.Position;
UpdateCamera(ref camera, CameraMode.CAMERA_FIRST_PERSON);
// Check player collision (we simplify to 2D collision detection)
Vector2 playerPos = new(camera.Position.X, camera.Position.Z);
// Collision radius (player is modelled as a cilinder for collision)
float playerRadius = 0.1f;
int playerCellX = (int)(playerPos.X - mapPosition.X + 0.5f);
int playerCellY = (int)(playerPos.Y - mapPosition.Z + 0.5f);
// Out-of-limits security check
if (playerCellX < 0)
{
playerCellX = 0;
}
else if (playerCellX >= cubicmap.Width)
{
playerCellX = cubicmap.Width - 1;
}
if (playerCellY < 0)
{
playerCellY = 0;
}
else if (playerCellY >= cubicmap.Height)
{
playerCellY = cubicmap.Height - 1;
}
// Check map collisions using image data and player position
// TODO: Improvement: Just check player surrounding cells for collision
for (int y = 0; y < cubicmap.Height; y++)
{
for (int x = 0; x < cubicmap.Width; x++)
{
Color* mapPixelsData = mapPixels;
// Collision: Color.white pixel, only check R channel
Rectangle rec = new(
mapPosition.X - 0.5f + x * 1.0f,
mapPosition.Z - 0.5f + y * 1.0f,
1.0f,
1.0f
);
bool collision = CheckCollisionCircleRec(playerPos, playerRadius, rec);
if ((mapPixelsData[y * cubicmap.Width + x].R == 255) && collision)
{
// Collision detected, reset camera position
camera.Position = oldCamPos;
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Draw maze map
BeginMode3D(camera);
DrawModel(model, mapPosition, 1.0f, Color.WHITE);
EndMode3D();
DrawTextureEx(cubicmap, new Vector2(GetScreenWidth() - cubicmap.Width * 4 - 20, 20), 0.0f, 4.0f, Color.WHITE);
DrawRectangleLines(GetScreenWidth() - cubicmap.Width * 4 - 20, 20, cubicmap.Width * 4, cubicmap.Height * 4, Color.GREEN);
// Draw player position radar
DrawRectangle(GetScreenWidth() - cubicmap.Width * 4 - 20 + playerCellX * 4, 20 + playerCellY * 4, 4, 4, Color.RED);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadImageColors(mapPixels);
UnloadTexture(cubicmap);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,85 @@
/*******************************************************************************************
*
* raylib [models] example - Draw some basic geometric shapes (cube, sphere, cylinder...)
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class GeometricShapes
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawCube(new Vector3(-4.0f, 0.0f, 2.0f), 2.0f, 5.0f, 2.0f, Color.RED);
DrawCubeWires(new Vector3(-4.0f, 0.0f, 2.0f), 2.0f, 5.0f, 2.0f, Color.GOLD);
DrawCubeWires(new Vector3(-4.0f, 0.0f, -2.0f), 3.0f, 6.0f, 2.0f, Color.MAROON);
DrawSphere(new Vector3(-1.0f, 0.0f, -2.0f), 1.0f, Color.GREEN);
DrawSphereWires(new Vector3(1.0f, 0.0f, 2.0f), 2.0f, 16, 16, Color.LIME);
DrawCylinder(new Vector3(4.0f, 0.0f, -2.0f), 1.0f, 2.0f, 3.0f, 4, Color.SKYBLUE);
DrawCylinderWires(new Vector3(4.0f, 0.0f, -2.0f), 1.0f, 2.0f, 3.0f, 4, Color.DARKBLUE);
DrawCylinderWires(new Vector3(4.5f, -1.0f, 2.0f), 1.0f, 1.0f, 2.0f, 6, Color.BROWN);
DrawCylinder(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.GOLD);
DrawCylinderWires(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.PINK);
DrawGrid(10, 1.0f);
EndMode3D();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,92 @@
/*******************************************************************************************
*
* raylib [models] example - Heightmap loading and drawing
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class HeightmapDemo
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - heightmap loading and drawing");
// Define our custom camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(18.0f, 16.0f, 18.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Image image = LoadImage("resources/heightmap.png");
Texture2D texture = LoadTextureFromImage(image);
Mesh mesh = GenMeshHeightmap(image, new Vector3(16, 8, 16));
Model model = LoadModelFromMesh(mesh);
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 mapPosition = new(-8.0f, 0.0f, -8.0f);
UnloadImage(image);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, mapPosition, 1.0f, Color.RED);
DrawGrid(20, 1.0f);
EndMode3D();
DrawTexture(texture, screenWidth - texture.Width - 20, 20, Color.WHITE);
DrawRectangleLines(screenWidth - texture.Width - 20, 20, texture.Width, texture.Height, Color.GREEN);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,140 @@
/*******************************************************************************************
*
* raylib example - procedural mesh generation
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (Ray San)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class MeshGeneration
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh generation");
// We generate a isChecked image for texturing
Image isChecked = GenImageChecked(2, 2, 1, 1, Color.RED, Color.GREEN);
Texture2D texture = LoadTextureFromImage(isChecked);
UnloadImage(isChecked);
Model[] models = new Model[7];
models[0] = LoadModelFromMesh(GenMeshPlane(2, 2, 5, 5));
models[1] = LoadModelFromMesh(GenMeshCube(2.0f, 1.0f, 2.0f));
models[2] = LoadModelFromMesh(GenMeshSphere(2, 32, 32));
models[3] = LoadModelFromMesh(GenMeshHemiSphere(2, 16, 16));
models[4] = LoadModelFromMesh(GenMeshCylinder(1, 2, 16));
models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32));
models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128));
// Set isChecked texture as default diffuse component for all models material
for (int i = 0; i < models.Length; i++)
{
// Set map diffuse texture
Raylib.SetMaterialTexture(ref models[i], 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
}
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(5.0f, 5.0f, 5.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Model drawing position
Vector3 position = new(0.0f, 0.0f, 0.0f);
int currentModel = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
// Cycle between the textures
currentModel = (currentModel + 1) % models.Length;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(models[currentModel], position, 1.0f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawRectangle(30, 400, 310, 30, ColorAlpha(Color.SKYBLUE, 0.5f));
DrawRectangleLines(30, 400, 310, 30, ColorAlpha(Color.DARKBLUE, 0.5f));
DrawText("MOUSE LEFT BUTTON to CYCLE PROCEDURAL MODELS", 40, 410, 10, Color.BLUE);
switch (currentModel)
{
case 0:
DrawText("PLANE", 680, 10, 20, Color.DARKBLUE);
break;
case 1:
DrawText("CUBE", 680, 10, 20, Color.DARKBLUE);
break;
case 2:
DrawText("SPHERE", 680, 10, 20, Color.DARKBLUE);
break;
case 3:
DrawText("HEMISPHERE", 640, 10, 20, Color.DARKBLUE);
break;
case 4:
DrawText("CYLINDER", 680, 10, 20, Color.DARKBLUE);
break;
case 5:
DrawText("TORUS", 680, 10, 20, Color.DARKBLUE);
break;
case 6:
DrawText("KNOT", 680, 10, 20, Color.DARKBLUE);
break;
default:
break;
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < models.Length; i++)
{
UnloadModel(models[i]);
}
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,248 @@
/*******************************************************************************************
*
* raylib [models] example - Mesh picking in 3d mode, ground plane, triangle, mesh
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
* Example contributed by Joel Davis (@joeld42)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
namespace Examples.Models;
public class MeshPicking
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - mesh picking");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(20.0f, 20.0f, 20.0f);
camera.Target = new Vector3(0.0f, 8.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.6f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Picking ray
Ray ray = new();
Model tower = LoadModel("resources/models/obj/turret.obj");
Texture2D texture = LoadTexture("resources/models/obj/turret_diffuse.png");
Raylib.SetMaterialTexture(ref tower, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 towerPos = new(0.0f, 0.0f, 0.0f);
BoundingBox towerBBox = GetMeshBoundingBox(tower.Meshes[0]);
// Ground quad
Vector3 g0 = new(-50.0f, 0.0f, -50.0f);
Vector3 g1 = new(-50.0f, 0.0f, 50.0f);
Vector3 g2 = new(50.0f, 0.0f, 50.0f);
Vector3 g3 = new(50.0f, 0.0f, -50.0f);
// Test triangle
Vector3 ta = new(-25.0f, 0.5f, 0.0f);
Vector3 tb = new(-4.0f, 2.5f, 1.0f);
Vector3 tc = new(-8.0f, 6.5f, 0.0f);
Vector3 bary = new(0.0f, 0.0f, 0.0f);
// Test sphere
Vector3 sp = new(-30.0f, 5.0f, 5.0f);
float sr = 4.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Main game loop
//--------------------------------------------------------------------------------------
while (!WindowShouldClose())
{
//----------------------------------------------------------------------------------
// Update
//----------------------------------------------------------------------------------
if (IsCursorHidden())
{
UpdateCamera(ref camera, CameraMode.CAMERA_FIRST_PERSON);
}
// Toggle camera controls
if (IsMouseButtonPressed(MouseButton.MOUSE_BUTTON_RIGHT))
{
if (IsCursorHidden())
{
EnableCursor();
}
else
{
DisableCursor();
}
}
// Display information about closest hit
RayCollision collision = new();
string hitObjectName = "None";
collision.Distance = float.MaxValue;
collision.Hit = false;
Color cursorColor = Color.WHITE;
// Get ray and test against objects
ray = GetMouseRay(GetMousePosition(), camera);
// Check ray collision aginst ground quad
RayCollision groundHitInfo = GetRayCollisionQuad(ray, g0, g1, g2, g3);
if (groundHitInfo.Hit && (groundHitInfo.Distance < collision.Distance))
{
collision = groundHitInfo;
cursorColor = Color.GREEN;
hitObjectName = "Ground";
}
// Check ray collision against test triangle
RayCollision triHitInfo = GetRayCollisionTriangle(ray, ta, tb, tc);
if (triHitInfo.Hit && (triHitInfo.Distance < collision.Distance))
{
collision = triHitInfo;
cursorColor = Color.PURPLE;
hitObjectName = "Triangle";
bary = Vector3Barycenter(collision.Point, ta, tb, tc);
}
// Check ray collision against test sphere
RayCollision sphereHitInfo = GetRayCollisionSphere(ray, sp, sr);
if ((sphereHitInfo.Hit) && (sphereHitInfo.Distance < collision.Distance))
{
collision = sphereHitInfo;
cursorColor = Color.ORANGE;
hitObjectName = "Sphere";
}
// Check ray collision against bounding box first, before trying the full ray-mesh test
RayCollision boxHitInfo = GetRayCollisionBox(ray, towerBBox);
if (boxHitInfo.Hit && boxHitInfo.Distance < collision.Distance)
{
collision = boxHitInfo;
cursorColor = Color.ORANGE;
hitObjectName = "Box";
// Check ray collision against model meshes
RayCollision meshHitInfo = new();
for (int m = 0; m < tower.MeshCount; m++)
{
// NOTE: We consider the model.Transform for the collision check but
// it can be checked against any transform matrix, used when checking against same
// model drawn multiple times with multiple transforms
meshHitInfo = GetRayCollisionMesh(ray, tower.Meshes[m], tower.Transform);
if (meshHitInfo.Hit)
{
// Save the closest hit mesh
if ((!collision.Hit) || (collision.Distance > meshHitInfo.Distance))
{
collision = meshHitInfo;
}
break;
}
}
if (meshHitInfo.Hit)
{
collision = meshHitInfo;
cursorColor = Color.ORANGE;
hitObjectName = "Mesh";
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
// Draw the tower
DrawModel(tower, towerPos, 1.0f, Color.WHITE);
// Draw the test triangle
DrawLine3D(ta, tb, Color.PURPLE);
DrawLine3D(tb, tc, Color.PURPLE);
DrawLine3D(tc, ta, Color.PURPLE);
// Draw the test sphere
DrawSphereWires(sp, sr, 8, 8, Color.PURPLE);
// Draw the mesh bbox if we hit it
if (boxHitInfo.Hit)
{
DrawBoundingBox(towerBBox, Color.LIME);
}
// If we hit something, draw the cursor at the hit point
if (collision.Hit)
{
DrawCube(collision.Point, 0.3f, 0.3f, 0.3f, cursorColor);
DrawCubeWires(collision.Point, 0.3f, 0.3f, 0.3f, Color.RED);
Vector3 normalEnd = collision.Point + collision.Normal;
DrawLine3D(collision.Point, normalEnd, Color.RED);
}
DrawRay(ray, Color.MAROON);
DrawGrid(10, 10.0f);
EndMode3D();
// Draw some debug GUI text
DrawText($"Hit Object: {hitObjectName}", 10, 50, 10, Color.BLACK);
if (collision.Hit)
{
int ypos = 70;
DrawText($"Distance: {collision.Distance}", 10, ypos, 10, Color.BLACK);
DrawText($"Hit Pos: {collision.Point}", 10, ypos + 15, 10, Color.BLACK);
DrawText($"Hit Norm: {collision.Normal}", 10, ypos + 30, 10, Color.BLACK);
if (triHitInfo.Hit)
{
DrawText($"Barycenter: {bary}", 10, ypos + 45, 10, Color.BLACK);
}
}
DrawText("Right click mouse to toggle camera controls", 10, 430, 10, Color.GRAY);
DrawText("(c) Turret 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, Color.GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(tower);
UnloadTexture(texture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,316 @@
/*******************************************************************************************
*
* raylib [models] example - Draw textured cube
*
* Example originally created with raylib 4.5, last time updated with raylib 4.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class ModelCubeTexture
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - draw cube texture");
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Load texture to be applied to the cubes sides
Texture2D texture = LoadTexture("resources/cubicmap_atlas.png");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
// Draw cube with an applied texture
DrawCubeTexture(texture, new Vector3(-2.0f, 2.0f, 0.0f), 2.0f, 4.0f, 2.0f, Color.WHITE);
// Draw cube with an applied texture, but only a defined rectangle piece of the texture
DrawCubeTextureRec(
texture,
new Rectangle(0, texture.Height / 2, texture.Width / 2, texture.Height / 2),
new Vector3(2.0f, 1.0f, 0.0f),
2.0f,
2.0f,
2.0f,
Color.WHITE
);
DrawGrid(10, 1.0f);
EndMode3D();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Draw cube textured
// NOTE: Cube position is the center position
static void DrawCubeTexture(
Texture2D texture,
Vector3 position,
float width,
float height,
float length,
Color color
)
{
float x = position.X;
float y = position.Y;
float z = position.Z;
// Set desired texture to be enabled while drawing following vertex data
Rlgl.SetTexture(texture.Id);
// Vertex data transformation can be defined with the commented lines,
// but in this example we calculate the transformed vertex data directly when calling Rlgl.Vertex3f()
// Rlgl.PushMatrix();
// NOTE: Transformation is applied in inverse order (scale -> rotate -> translate)
// Rlgl.Translatef(2.0f, 0.0f, 0.0f);
// Rlgl.Rotatef(45, 0, 1, 0);
// Rlgl.Scalef(2.0f, 2.0f, 2.0f);
Rlgl.Begin(DrawMode.QUADS);
Rlgl.Color4ub(color.R, color.G, color.B, color.A);
// Front Face
// Normal Pointing Towards Viewer
Rlgl.Normal3f(0.0f, 0.0f, 1.0f);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
// Back Face
// Normal Pointing Away From Viewer
Rlgl.Normal3f(0.0f, 0.0f, -1.0f);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
// Top Face
// Normal Pointing Up
Rlgl.Normal3f(0.0f, 1.0f, 0.0f);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
// Bottom Face
// Normal Pointing Down
Rlgl.Normal3f(0.0f, -1.0f, 0.0f);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
// Right face
// Normal Pointing Right
Rlgl.Normal3f(1.0f, 0.0f, 0.0f);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
// Left Face
// Normal Pointing Left
Rlgl.Normal3f(-1.0f, 0.0f, 0.0f);
Rlgl.TexCoord2f(0.0f, 0.0f);
// Bottom Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(1.0f, 0.0f);
// Bottom Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f(1.0f, 1.0f);
// Top Right Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(0.0f, 1.0f);
// Top Left Of The Texture and Quad
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.End();
//rlPopMatrix();
Rlgl.SetTexture(0);
}
// Draw cube with texture piece applied to all faces
static void DrawCubeTextureRec(
Texture2D texture,
Rectangle source,
Vector3 position,
float width,
float height,
float length,
Color color
)
{
float x = position.X;
float y = position.Y;
float z = position.Z;
float texWidth = (float)texture.Width;
float texHeight = (float)texture.Height;
// Set desired texture to be enabled while drawing following vertex data
Rlgl.SetTexture(texture.Id);
// We calculate the normalized texture coordinates for the desired texture-source-rectangle
// It means converting from (tex.Width, tex.Height) coordinates to [0.0f, 1.0f] equivalent
Rlgl.Begin(DrawMode.QUADS);
Rlgl.Color4ub(color.R, color.G, color.B, color.A);
// Front face
Rlgl.Normal3f(0.0f, 0.0f, 1.0f);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
// Back face
Rlgl.Normal3f(0.0f, 0.0f, -1.0f);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
// Top face
Rlgl.Normal3f(0.0f, 1.0f, 0.0f);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
// Bottom face
Rlgl.Normal3f(0.0f, -1.0f, 0.0f);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
// Right face
Rlgl.Normal3f(1.0f, 0.0f, 0.0f);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z - length / 2);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x + width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x + width / 2, y - height / 2, z + length / 2);
// Left face
Rlgl.Normal3f(-1.0f, 0.0f, 0.0f);
Rlgl.TexCoord2f(source.X / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z - length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, (source.Y + source.Height) / texHeight);
Rlgl.Vertex3f(x - width / 2, y - height / 2, z + length / 2);
Rlgl.TexCoord2f((source.X + source.Width) / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z + length / 2);
Rlgl.TexCoord2f(source.X / texWidth, source.Y / texHeight);
Rlgl.Vertex3f(x - width / 2, y + height / 2, z - length / 2);
Rlgl.End();
Rlgl.SetTexture(0);
}
}

View File

@ -0,0 +1,157 @@
/*******************************************************************************************
*
* raylib [models] example - Models loading
*
* raylib supports multiple models file formats:
*
* - OBJ > Text file, must include vertex position-texcoords-normals information,
* if files references some .mtl materials file, it will be loaded (or try to)
* - GLTF > Modern text/binary file format, includes lot of information and it could
* also reference external files, raylib will try loading mesh and materials data
* - IQM > Binary file format including mesh vertex data but also animation data,
* raylib can load .iqm animations.
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class ModelLoading
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - models loading");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(50.0f, 50.0f, 50.0f);
camera.Target = new Vector3(0.0f, 10.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/obj/castle.obj");
Texture2D texture = LoadTexture("resources/models/obj/castle_diffuse.png");
// Set map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
BoundingBox bounds = GetMeshBoundingBox(model.Meshes[0]);
// NOTE: bounds are calculated from the original size of the model,
// if model is scaled on drawing, bounds must be also scaled
bool selected = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
if (IsFileDropped())
{
string[] files = Raylib.GetDroppedFiles();
if (files.Length == 1)
{
if (IsFileExtension(files[0], ".obj") ||
IsFileExtension(files[0], ".gltf") ||
IsFileExtension(files[0], ".iqm")
)
{
UnloadModel(model);
model = LoadModel(files[0]);
// Set current map diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
bounds = GetMeshBoundingBox(model.Meshes[0]);
// TODO: Move camera position from target enough distance to visualize model properly
}
else if (IsFileExtension(files[0], ".png"))
{
// Unload model texture and load new one
UnloadTexture(texture);
texture = LoadTexture(files[0]);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
}
}
}
// Select model on mouse click
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
// Check collision between ray and box
if (GetRayCollisionBox(GetMouseRay(GetMousePosition(), camera), bounds).Hit)
{
selected = !selected;
}
else
{
selected = false;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 1.0f, Color.WHITE);
DrawGrid(20, 10.0f);
if (selected)
{
DrawBoundingBox(bounds, Color.GREEN);
}
EndMode3D();
DrawText("Drag & drop model to load mesh/texture.", 10, GetScreenHeight() - 20, 10, Color.DARKGRAY);
if (selected)
{
DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, Color.GREEN);
}
DrawText("(c) Castle 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, Color.GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,113 @@
/*******************************************************************************************
*
* raylib [models] example - Show the difference between perspective and orthographic projection
*
* This program is heavily based on the geometric objects example
*
* This example has been created using raylib 1.9.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2018 Max Danielsson ref Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class OrthographicProjection
{
public const float FOVY_PERSPECTIVE = 45.0f;
public const float WIDTH_ORTHOGRAPHIC = 10.0f;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - geometric shapes");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 10.0f, 10.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = FOVY_PERSPECTIVE;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
if (camera.Projection == CameraProjection.CAMERA_PERSPECTIVE)
{
camera.FovY = WIDTH_ORTHOGRAPHIC;
camera.Projection = CameraProjection.CAMERA_ORTHOGRAPHIC;
}
else
{
camera.FovY = FOVY_PERSPECTIVE;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawCube(new Vector3(-4.0f, 0.0f, 2.0f), 2.0f, 5.0f, 2.0f, Color.RED);
DrawCubeWires(new Vector3(-4.0f, 0.0f, 2.0f), 2.0f, 5.0f, 2.0f, Color.GOLD);
DrawCubeWires(new Vector3(-4.0f, 0.0f, -2.0f), 3.0f, 6.0f, 2.0f, Color.MAROON);
DrawSphere(new Vector3(-1.0f, 0.0f, -2.0f), 1.0f, Color.GREEN);
DrawSphereWires(new Vector3(1.0f, 0.0f, 2.0f), 2.0f, 16, 16, Color.LIME);
DrawCylinder(new Vector3(4.0f, 0.0f, -2.0f), 1.0f, 2.0f, 3.0f, 4, Color.SKYBLUE);
DrawCylinderWires(new Vector3(4.0f, 0.0f, -2.0f), 1.0f, 2.0f, 3.0f, 4, Color.DARKBLUE);
DrawCylinderWires(new Vector3(4.5f, -1.0f, 2.0f), 1.0f, 1.0f, 2.0f, 6, Color.BROWN);
DrawCylinder(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.GOLD);
DrawCylinderWires(new Vector3(1.0f, 0.0f, -4.0f), 0.0f, 1.5f, 3.0f, 8, Color.PINK);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("Press Spacebar to switch camera type", 10, GetScreenHeight() - 30, 20, Color.DARKGRAY);
if (camera.Projection == CameraProjection.CAMERA_ORTHOGRAPHIC)
{
DrawText("ORTHOGRAPHIC", 10, 40, 20, Color.BLACK);
}
else if (camera.Projection == CameraProjection.CAMERA_PERSPECTIVE)
{
DrawText("PERSPECTIVE", 10, 40, 20, Color.BLACK);
}
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,138 @@
/*******************************************************************************************
*
* raylib [models] example - Skybox loading and drawing
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class SkyboxDemo
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - skybox loading and drawing");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(1.0f, 1.0f, 1.0f);
camera.Target = new Vector3(4.0f, 1.0f, 4.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Load skybox model
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Model skybox = LoadModelFromMesh(cube);
// Load skybox shader and set required locations
// NOTE: Some locations are automatically set at shader loading
Shader shader = LoadShader("resources/shaders/glsl330/skybox.vs", "resources/shaders/glsl330/skybox.fs");
Raylib.SetMaterialShader(ref skybox, 0, ref shader);
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "environmentMap"),
(int)MaterialMapIndex.MATERIAL_MAP_CUBEMAP,
ShaderUniformDataType.SHADER_UNIFORM_INT
);
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "vflipped"),
1,
ShaderUniformDataType.SHADER_UNIFORM_INT
);
// Load cubemap shader and setup required shader locations
Shader shdrCubemap = LoadShader(
"resources/shaders/glsl330/cubemap.vs",
"resources/shaders/glsl330/cubemap.fs"
);
Raylib.SetShaderValue(
shdrCubemap,
GetShaderLocation(shdrCubemap, "equirectangularMap"),
0,
ShaderUniformDataType.SHADER_UNIFORM_INT
);
// Load HDR panorama (sphere) texture
string panoFileName = "resources/dresden_square_2k.hdr";
Texture2D panorama = LoadTexture(panoFileName);
// Generate cubemap (texture with 6 quads-cube-mapping) from panorama HDR texture
// NOTE: New texture is generated rendering to texture, shader computes the sphre->cube coordinates mapping
// Texture2D cubemap = PBR.GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
// Raylib.SetMaterialTexture(ref skybox, 0, MaterialMapIndex.MATERIAL_MAP_CUBEMAP, ref cubemap);
// Texture not required anymore, cubemap already generated
UnloadTexture(panorama);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FIRST_PERSON);
// Load new cubemap texture on drag & drop
if (IsFileDropped())
{
string[] files = Raylib.GetDroppedFiles();
if (files.Length == 1)
{
if (IsFileExtension(files[0], ".png;.jpg;.hdr;.bmp;.tga"))
{
// Unload cubemap texture and load new one
UnloadTexture(Raylib.GetMaterialTexture(ref skybox, 0, MaterialMapIndex.MATERIAL_MAP_CUBEMAP));
panorama = LoadTexture(files[0]);
panoFileName = files[0];
// Generate cubemap from panorama texture
// cubemap = PBR.GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
// Raylib.SetMaterialTexture(ref skybox, 0, MaterialMapIndex.MATERIAL_MAP_CUBEMAP, ref cubemap);
UnloadTexture(panorama);
}
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(skybox, new Vector3(0, 0, 0), 1.0f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(skybox);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,196 @@
/*******************************************************************************************
*
* raylib [models] example - rlgl module usage with push/pop matrix transformations
*
* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2018 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class SolarSystem
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const float sunRadius = 4.0f;
const float earthRadius = 0.6f;
const float earthOrbitRadius = 8.0f;
const float moonRadius = 0.16f;
const float moonOrbitRadius = 1.5f;
InitWindow(screenWidth, screenHeight, "raylib [models] example - rlgl module usage with push/pop matrix transformations");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(16.0f, 16.0f, 16.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// General system rotation speed
float rotationSpeed = 0.2f;
// Rotation of earth around itself (days) in degrees
float earthRotation = 0.0f;
// Rotation of earth around the Sun (years) in degrees
float earthOrbitRotation = 0.0f;
// Rotation of moon around itself
float moonRotation = 0.0f;
// Rotation of moon around earth in degrees
float moonOrbitRotation = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
earthRotation += (5.0f * rotationSpeed);
earthOrbitRotation += (365 / 360.0f * (5.0f * rotationSpeed) * rotationSpeed);
moonRotation += (2.0f * rotationSpeed);
moonOrbitRotation += (8.0f * rotationSpeed);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
Rlgl.PushMatrix();
// Scale Sun
Rlgl.Scalef(sunRadius, sunRadius, sunRadius);
// Draw the Sun
DrawSphereBasic(Color.GOLD);
Rlgl.PopMatrix();
Rlgl.PushMatrix();
// Rotation for Earth orbit around Sun
Rlgl.Rotatef(earthOrbitRotation, 0.0f, 1.0f, 0.0f);
// Translation for Earth orbit
Rlgl.Translatef(earthOrbitRadius, 0.0f, 0.0f);
// Rotation for Earth orbit around Sun inverted
Rlgl.Rotatef(-earthOrbitRotation, 0.0f, 1.0f, 0.0f);
Rlgl.PushMatrix();
// Rotation for Earth itself
Rlgl.Rotatef(earthRotation, 0.25f, 1.0f, 0.0f);
// Scale Earth
Rlgl.Scalef(earthRadius, earthRadius, earthRadius);
// Draw the Earth
DrawSphereBasic(Color.BLUE);
Rlgl.PopMatrix();
// Rotation for Moon orbit around Earth
Rlgl.Rotatef(moonOrbitRotation, 0.0f, 1.0f, 0.0f);
// Translation for Moon orbit
Rlgl.Translatef(moonOrbitRadius, 0.0f, 0.0f);
// Rotation for Moon orbit around Earth inverted
Rlgl.Rotatef(-moonOrbitRotation, 0.0f, 1.0f, 0.0f);
// Rotation for Moon itself
Rlgl.Rotatef(moonRotation, 0.0f, 1.0f, 0.0f);
// Scale Moon
Rlgl.Scalef(moonRadius, moonRadius, moonRadius);
// Draw the Moon
DrawSphereBasic(Color.LIGHTGRAY);
Rlgl.PopMatrix();
// Some reference elements (not affected by previous matrix transformations)
DrawCircle3D(
new Vector3(0.0f, 0.0f, 0.0f),
earthOrbitRadius,
new Vector3(1, 0, 0),
90.0f,
ColorAlpha(Color.RED, 0.5f)
);
DrawGrid(20, 1.0f);
EndMode3D();
DrawText("EARTH ORBITING AROUND THE SUN!", 400, 10, 20, Color.MAROON);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Draw sphere without any matrix transformation
// NOTE: Sphere is drawn in world position ( 0, 0, 0 ) with radius 1.0f
static void DrawSphereBasic(Color color)
{
int rings = 16;
int slices = 16;
Rlgl.Begin(DrawMode.TRIANGLES);
Rlgl.Color4ub(color.R, color.G, color.B, color.A);
for (int i = 0; i < (rings + 2); i++)
{
for (int j = 0; j < slices; j++)
{
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * i)) * MathF.Sin(DEG2RAD * (j * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * i)),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * i)) * MathF.Cos(DEG2RAD * (j * 360 / slices))
);
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Sin(DEG2RAD * ((j + 1) * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Cos(DEG2RAD * ((j + 1) * 360 / slices))
);
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Sin(DEG2RAD * (j * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Cos(DEG2RAD * (j * 360 / slices))
);
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * i)) * MathF.Sin(DEG2RAD * (j * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * i)),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * i)) * MathF.Cos(DEG2RAD * (j * 360 / slices))
);
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i))) * MathF.Sin(DEG2RAD * ((j + 1) * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * (i))),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i))) * MathF.Cos(DEG2RAD * ((j + 1) * 360 / slices))
);
Rlgl.Vertex3f(
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Sin(DEG2RAD * ((j + 1) * 360 / slices)),
MathF.Sin(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))),
MathF.Cos(DEG2RAD * (270 + (180 / (rings + 1)) * (i + 1))) * MathF.Cos(DEG2RAD * ((j + 1) * 360 / slices))
);
}
}
Rlgl.End();
}
}

View File

@ -0,0 +1,117 @@
/*******************************************************************************************
*
* raylib [models] example - Waving cubes
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Codecat (@codecat) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Codecat (@codecat) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Models;
public class WavingCubes
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - waving cubes");
// Initialize the camera
Camera3D camera = new();
camera.Position = new Vector3(30.0f, 20.0f, 30.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 70.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Specify the amount of blocks in each direction
const int numBlocks = 15;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
double time = GetTime();
// Calculate time scale for cube position and size
float scale = (2.0f + (float)Math.Sin(time)) * 0.7f;
// Move camera around the scene
double cameraTime = time * 0.3;
camera.Position.X = (float)Math.Cos(cameraTime) * 40.0f;
camera.Position.Z = (float)Math.Sin(cameraTime) * 40.0f;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawGrid(10, 5.0f);
for (int x = 0; x < numBlocks; x++)
{
for (int y = 0; y < numBlocks; y++)
{
for (int z = 0; z < numBlocks; z++)
{
// Scale of the blocks depends on x/y/z positions
float blockScale = (x + y + z) / 30.0f;
// Scatter makes the waving effect by adding blockScale over time
float scatter = (float)Math.Sin(blockScale * 20.0f + (float)(time * 4.0f));
// Calculate the cube position
Vector3 cubePos = new(
(float)(x - numBlocks / 2) * (scale * 3.0f) + scatter,
(float)(y - numBlocks / 2) * (scale * 2.0f) + scatter,
(float)(z - numBlocks / 2) * (scale * 3.0f) + scatter
);
// Pick a color with a hue depending on cube position for the rainbow color effect
Color cubeColor = ColorFromHSV((float)(((x + y + z) * 18) % 360), 0.75f, 0.9f);
// Calculate cube size
float cubeSize = (2.4f - scale) * blockScale;
// And finally, draw the cube!
DrawCube(cubePos, cubeSize, cubeSize, cubeSize, cubeColor);
}
}
}
EndMode3D();
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,164 @@
/*******************************************************************************************
*
* raylib [models] example - Plane rotations (yaw, pitch, roll)
*
* This example has been created using raylib 1.8 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Berni (@Berni8k) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2017-2021 Berni (@Berni8k) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
namespace Examples.Models;
public class YawPitchRoll
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [models] example - plane rotations (yaw, pitch, roll)");
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 50.0f, -120.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 30.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Model loading
Model model = LoadModel("resources/models/obj/plane.obj");
Texture2D texture = LoadTexture("resources/models/obj/plane_diffuse.png");
model.Materials[0].Maps[(int)MaterialMapIndex.MATERIAL_MAP_DIFFUSE].Texture = texture;
float pitch = 0.0f;
float roll = 0.0f;
float yaw = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Plane roll (x-axis) controls
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
pitch += 0.6f;
}
else if (IsKeyDown(KeyboardKey.KEY_UP))
{
pitch -= 0.6f;
}
else
{
if (pitch > 0.3f)
{
pitch -= 0.3f;
}
else if (pitch < -0.3f)
{
pitch += 0.3f;
}
}
// Plane yaw (y-axis) controls
if (IsKeyDown(KeyboardKey.KEY_S))
{
yaw += 1.0f;
}
else if (IsKeyDown(KeyboardKey.KEY_A))
{
yaw -= 1.0f;
}
else
{
if (yaw > 0.0f)
{
yaw -= 0.5f;
}
else if (yaw < 0.0f)
{
yaw += 0.5f;
}
}
// Plane pitch (z-axis) controls
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
roll += 1.0f;
}
else if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
roll -= 1.0f;
}
else
{
if (roll > 0.0f)
{
roll -= 0.5f;
}
else if (roll < 0.0f)
{
roll += 0.5f;
}
}
// Tranformation matrix for rotations
model.Transform = MatrixRotateXYZ(new Vector3(DEG2RAD * pitch, DEG2RAD * yaw, DEG2RAD * roll));
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Draw 3D model (recomended to draw 3D always before 2D)
BeginMode3D(camera);
// Draw 3d model with texture
DrawModel(model, new Vector3(0.0f, -8.0f, 0.0f), 1.0f, Color.WHITE);
DrawGrid(10, 10.0f);
EndMode3D();
// Draw controls info
DrawRectangle(30, 370, 260, 70, Fade(Color.GREEN, 0.5f));
DrawRectangleLines(30, 370, 260, 70, Fade(Color.DARKGREEN, 0.5f));
DrawText("Pitch controlled with: KEY_UP / KEY_DOWN", 40, 380, 10, Color.DARKGRAY);
DrawText("Roll controlled with: KEY_LEFT / KEY_RIGHT", 40, 400, 10, Color.DARKGRAY);
DrawText("Yaw controlled with: KEY_A / KEY_S", 40, 420, 10, Color.DARKGRAY);
DrawText(
"(c) WWI Plane Model created by GiaHanLam",
screenWidth - 240,
screenHeight - 20,
10,
Color.DARKGRAY
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

176
Examples/Program.cs Normal file
View File

@ -0,0 +1,176 @@
using System;
using Examples.Core;
using Examples.Shapes;
using Examples.Textures;
using Examples.Text;
using Examples.Models;
using Examples.Shaders;
using Examples.Audio;
namespace Examples;
public class ExampleList
{
public static Func<int>[] CoreExamples = new Func<int>[]
{
Camera2dPlatformer.Main,
Camera2dDemo.Main,
Camera3dFirstPerson.Main,
Camera3dFree.Main,
Camera3dMode.Main,
Picking3d.Main,
BasicScreenManager.Main,
BasicWindow.Main,
CustomLogging.Main,
DropFiles.Main,
InputGamepad.Main,
InputGestures.Main,
InputKeys.Main,
InputMouseWheel.Main,
InputMouse.Main,
InputMultitouch.Main,
RandomValues.Main,
ScissorTest.Main,
SmoothPixelPerfect.Main,
SplitScreen.Main,
StorageValues.Main,
VrSimulator.Main,
WindowFlags.Main,
WindowLetterbox.Main,
WorldScreen.Main,
};
public static Func<int>[] ShapesExamples = new Func<int>[]
{
BasicShapes.Main,
BouncingBall.Main,
CollisionArea.Main,
ColorsPalette.Main,
EasingsBallAnim.Main,
EasingsBoxAnim.Main,
EasingsRectangleArray.Main,
FollowingEyes.Main,
LinesBezier.Main,
LogoRaylibAnim.Main,
LogoRaylibShape.Main,
RectangleScaling.Main,
};
public static Func<int>[] TexturesExamples = new Func<int>[]
{
BackgroundScrolling.Main,
BlendModes.Main,
Bunnymark.Main,
DrawTiled.Main,
ImageDrawing.Main,
ImageGeneration.Main,
ImageLoading.Main,
ImageProcessing.Main,
ImageText.Main,
LogoRaylibTexture.Main,
MousePainting.Main,
NpatchDrawing.Main,
ParticlesBlending.Main,
TexturedCurve.Main,
Polygon.Main,
RawData.Main,
SpriteAnim.Main,
SpriteButton.Main,
SpriteExplosion.Main,
SrcRecDstRec.Main,
ToImage.Main,
};
public static Func<int>[] TextExamples = new Func<int>[]
{
CodepointsLoading.Main,
FontFilters.Main,
FontLoading.Main,
FontSdf.Main,
FontSpritefont.Main,
FormatText.Main,
InputBox.Main,
RaylibFonts.Main,
RectangleBounds.Main,
WritingAnim.Main,
};
public static Func<int>[] ModelsExamples = new Func<int>[]
{
AnimationDemo.Main,
BillboardDemo.Main,
BoxCollisions.Main,
CubicmapDemo.Main,
ModelCubeTexture.Main,
FirstPersonMaze.Main,
GeometricShapes.Main,
HeightmapDemo.Main,
ModelLoading.Main,
MeshGeneration.Main,
MeshPicking.Main,
OrthographicProjection.Main,
SolarSystem.Main,
SkyboxDemo.Main,
WavingCubes.Main,
YawPitchRoll.Main,
};
public static Func<int>[] ShadersExamples = new Func<int>[]
{
BasicLighting.Main,
CustomUniform.Main,
Eratosthenes.Main,
Fog.Main,
HotReloading.Main,
HybridRender.Main,
JuliaSet.Main,
ModelShader.Main,
MultiSample2d.Main,
PaletteSwitch.Main,
PostProcessing.Main,
Raymarching.Main,
MeshInstancing.Main,
ShapesTextures.Main,
SimpleMask.Main,
Spotlight.Main,
TextureDrawing.Main,
TextureOutline.Main,
TextureWaves.Main,
WriteDepth.Main,
};
public static Func<int>[] AudioExamples = new Func<int>[]
{
ModulePlaying.Main,
MusicStreamDemo.Main,
SoundLoading.Main,
};
}
class Program
{
static unsafe void Main(string[] args)
{
Raylib.SetTraceLogCallback(&Logging.LogConsole);
RunExamples(ExampleList.CoreExamples);
RunExamples(ExampleList.ShapesExamples);
RunExamples(ExampleList.TexturesExamples);
RunExamples(ExampleList.TextExamples);
RunExamples(ExampleList.ModelsExamples);
RunExamples(ExampleList.ShadersExamples);
RunExamples(ExampleList.AudioExamples);
}
static void RunExamples(Func<int>[] examples)
{
var configFlags = Enum.GetValues(typeof(ConfigFlags));
foreach (var example in examples)
{
example.Invoke();
foreach (ConfigFlags flag in configFlags)
{
Raylib.ClearWindowState(flag);
}
}
}
}

90
Examples/Rlights.cs Normal file
View File

@ -0,0 +1,90 @@
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples;
public struct Light
{
public bool Enabled;
public LightType Type;
public Vector3 Position;
public Vector3 Target;
public Color Color;
public int EnabledLoc;
public int TypeLoc;
public int PosLoc;
public int TargetLoc;
public int ColorLoc;
}
public enum LightType
{
Directorional,
Point
}
public static class Rlights
{
public static Light CreateLight(
int lightsCount,
LightType type,
Vector3 pos,
Vector3 target,
Color color,
Shader shader
)
{
Light light = new();
light.Enabled = true;
light.Type = type;
light.Position = pos;
light.Target = target;
light.Color = color;
string enabledName = "lights[" + lightsCount + "].enabled";
string typeName = "lights[" + lightsCount + "].type";
string posName = "lights[" + lightsCount + "].position";
string targetName = "lights[" + lightsCount + "].target";
string colorName = "lights[" + lightsCount + "].color";
light.EnabledLoc = GetShaderLocation(shader, enabledName);
light.TypeLoc = GetShaderLocation(shader, typeName);
light.PosLoc = GetShaderLocation(shader, posName);
light.TargetLoc = GetShaderLocation(shader, targetName);
light.ColorLoc = GetShaderLocation(shader, colorName);
UpdateLightValues(shader, light);
return light;
}
public static void UpdateLightValues(Shader shader, Light light)
{
// Send to shader light enabled state and type
Raylib.SetShaderValue(
shader,
light.EnabledLoc,
light.Enabled ? 1 : 0,
ShaderUniformDataType.SHADER_UNIFORM_INT
);
Raylib.SetShaderValue(shader, light.TypeLoc, (int)light.Type, ShaderUniformDataType.SHADER_UNIFORM_INT);
// Send to shader light target position values
Raylib.SetShaderValue(shader, light.PosLoc, light.Position, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
// Send to shader light target position values
Raylib.SetShaderValue(shader, light.TargetLoc, light.Target, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
// Send to shader light color values
float[] color = new[]
{
(float)light.Color.R / (float)255,
(float)light.Color.G / (float)255,
(float)light.Color.B / (float)255,
(float)light.Color.A / (float)255
};
Raylib.SetShaderValue(shader, light.ColorLoc, color, ShaderUniformDataType.SHADER_UNIFORM_VEC4);
}
}

View File

@ -0,0 +1,224 @@
/*******************************************************************************************
*
* raylib [shaders] example - basic lighting
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Examples.Rlights;
namespace Examples.Shaders;
public class BasicLighting
{
const int GLSL_VERSION = 330;
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - basic lighting");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 4.0f, 6.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Load plane model from a generated mesh
Model model = LoadModelFromMesh(GenMeshPlane(10.0f, 10.0f, 3, 3));
Model cube = LoadModelFromMesh(GenMeshCube(2.0f, 4.0f, 2.0f));
Shader shader = LoadShader(
"resources/shaders/glsl330/lighting.vs",
"resources/shaders/glsl330/lighting.fs"
);
// Get some required shader loactions
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
// ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
float[] ambient = new[] { 0.1f, 0.1f, 0.1f, 1.0f };
Raylib.SetShaderValue(shader, ambientLoc, ambient, ShaderUniformDataType.SHADER_UNIFORM_VEC4);
// Assign out lighting shader to model
model.Materials[0].Shader = shader;
cube.Materials[0].Shader = shader;
// Using 4 point lights: Color.gold, Color.red, Color.green and Color.blue
Light[] lights = new Light[4];
lights[0] = CreateLight(
0,
LightType.Point,
new Vector3(-2, 1, -2),
Vector3.Zero,
Color.YELLOW,
shader
);
lights[1] = CreateLight(
1,
LightType.Point,
new Vector3(2, 1, 2),
Vector3.Zero,
Color.RED,
shader
);
lights[2] = CreateLight(
2,
LightType.Point,
new Vector3(-2, 1, 2),
Vector3.Zero,
Color.GREEN,
shader
);
lights[3] = CreateLight(
3,
LightType.Point,
new Vector3(2, 1, -2),
Vector3.Zero,
Color.BLUE,
shader
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyPressed(KeyboardKey.KEY_Y))
{
lights[0].Enabled = !lights[0].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_R))
{
lights[1].Enabled = !lights[1].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_G))
{
lights[2].Enabled = !lights[2].Enabled;
}
if (IsKeyPressed(KeyboardKey.KEY_B))
{
lights[3].Enabled = !lights[3].Enabled;
}
// Update light values (actually, only enable/disable them)
UpdateLightValues(shader, lights[0]);
UpdateLightValues(shader, lights[1]);
UpdateLightValues(shader, lights[2]);
UpdateLightValues(shader, lights[3]);
// Update the light shader with the camera view position
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW],
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, Vector3.Zero, 1.0f, Color.WHITE);
DrawModel(cube, Vector3.Zero, 1.0f, Color.WHITE);
// Draw markers to show where the lights are
if (lights[0].Enabled)
{
DrawSphereEx(lights[0].Position, 0.2f, 8, 8, Color.YELLOW);
}
else
{
DrawSphereWires(lights[0].Position, 0.2f, 8, 8, ColorAlpha(Color.YELLOW, 0.3f));
}
if (lights[1].Enabled)
{
DrawSphereEx(lights[1].Position, 0.2f, 8, 8, Color.RED);
}
else
{
DrawSphereWires(lights[1].Position, 0.2f, 8, 8, ColorAlpha(Color.RED, 0.3f));
}
if (lights[2].Enabled)
{
DrawSphereEx(lights[2].Position, 0.2f, 8, 8, Color.GREEN);
}
else
{
DrawSphereWires(lights[2].Position, 0.2f, 8, 8, ColorAlpha(Color.GREEN, 0.3f));
}
if (lights[3].Enabled)
{
DrawSphereEx(lights[3].Position, 0.2f, 8, 8, Color.BLUE);
}
else
{
DrawSphereWires(lights[3].Position, 0.2f, 8, 8, ColorAlpha(Color.BLUE, 0.3f));
}
DrawGrid(10, 1.0f);
EndMode3D();
DrawFPS(10, 10);
DrawText("Use keys [Y][R][G][B] to toggle lights", 10, 40, 20, Color.DARKGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model);
UnloadModel(cube);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,145 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader and connect a custom uniform variable
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class CustomUniform
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - custom uniform variable");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(8.0f, 8.0f, 8.0f);
camera.Target = new Vector3(0.0f, 1.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/barracks.obj");
Texture2D texture = LoadTexture("resources/models/barracks_diffuse.png");
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
// Load postpro shader
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/swirl.fs");
// Get variable (uniform) location on the shader to connect with the program
// NOTE: If uniform variable could not be found in the shader, function returns -1
int swirlCenterLoc = GetShaderLocation(shader, "center");
float[] swirlCenter = new float[2] { (float)screenWidth / 2, (float)screenHeight / 2 };
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
Vector2 mousePosition = GetMousePosition();
swirlCenter[0] = mousePosition.X;
swirlCenter[1] = screenHeight - mousePosition.Y;
// Send new value to the shader to be used on drawing
Raylib.SetShaderValue(shader, swirlCenterLoc, swirlCenter, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.5f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText("TEXT DRAWN IN RENDER TEXTURE", 200, 10, 30, Color.RED);
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0, 0),
Color.WHITE
);
EndShaderMode();
DrawText(
"(c) Barracks 3D model by Alberto Cano",
screenWidth - 220,
screenHeight - 20,
10,
Color.GRAY
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,103 @@
/*******************************************************************************************
*
* raylib [shaders] example - Sieve of Eratosthenes
*
* Sieve of Eratosthenes, the earliest known (ancient Greek) prime number sieve.
*
* "Sift the twos and sift the threes,
* The Sieve of Eratosthenes.
* When the multiples sublime,
* the numbers that are left are prime."
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by ProfJski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 ProfJski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Eratosthenes
{
const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes");
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Load Eratosthenes shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/eratosthenes.fs");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Nothing to do here, everything is happening in the shader
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.BLACK);
// Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font white character texture coordinates,
// so shader can not be applied here directly because input vertexTexCoord
// do not represent full screen coordinates (space where want to apply shader)
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color.BLACK);
// End drawing to texture (now we have a blank texture available for the shader)
EndTextureMode();
BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0.0f, 0.0f),
Color.WHITE
);
EndShaderMode();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

181
Examples/Shaders/Fog.cs Normal file
View File

@ -0,0 +1,181 @@
/*******************************************************************************************
*
* raylib [shaders] example - fog
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Chris Camacho (@codifies - http://bedroomcoders.co.uk/) notes:
*
* This is based on the PBR lighting example, but greatly simplified to aid learning...
* actually there is very little of the PBR example left!
* When I first looked at the bewildering complexity of the PBR example I feared
* I would never understand how I could do simple lighting with raylib however its
* a testement to the authors of raylib (including rlights.h) that the example
* came together fairly quickly.
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
using static Examples.Rlights;
namespace Examples.Shaders;
public class Fog
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 2.0f, 6.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Load models and texture
Model modelA = LoadModelFromMesh(GenMeshTorus(0.4f, 1.0f, 16, 32));
Model modelB = LoadModelFromMesh(GenMeshCube(1.0f, 1.0f, 1.0f));
Model modelC = LoadModelFromMesh(GenMeshSphere(0.5f, 32, 32));
Texture2D texture = LoadTexture("resources/texel_checker.png");
// Assign texture to default model material
Raylib.SetMaterialTexture(ref modelA, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Raylib.SetMaterialTexture(ref modelB, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Raylib.SetMaterialTexture(ref modelC, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
// Load shader and set up some uniforms
Shader shader = LoadShader("resources/shaders/glsl330/lighting.vs", "resources/shaders/glsl330/fog.fs");
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel");
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
new float[] { 0.2f, 0.2f, 0.2f, 1.0f },
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
float fogDensity = 0.15f;
int fogDensityLoc = GetShaderLocation(shader, "fogDensity");
Raylib.SetShaderValue(shader, fogDensityLoc, fogDensity, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// NOTE: All models share the same shader
Raylib.SetMaterialShader(ref modelA, 0, ref shader);
Raylib.SetMaterialShader(ref modelB, 0, ref shader);
Raylib.SetMaterialShader(ref modelC, 0, ref shader);
// Using just 1 point lights
CreateLight(0, LightType.Point, new Vector3(0, 2, 6), Vector3.Zero, Color.WHITE, shader);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyDown(KeyboardKey.KEY_UP))
{
fogDensity += 0.001f;
if (fogDensity > 1.0f)
{
fogDensity = 1.0f;
}
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
fogDensity -= 0.001f;
if (fogDensity < 0.0f)
{
fogDensity = 0.0f;
}
}
Raylib.SetShaderValue(shader, fogDensityLoc, fogDensity, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// Rotate the torus
modelA.Transform = MatrixMultiply(modelA.Transform, MatrixRotateX(-0.025f));
modelA.Transform = MatrixMultiply(modelA.Transform, MatrixRotateZ(0.012f));
// Update the light shader with the camera view position
Raylib.SetShaderValue(
shader,
shader.Locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW],
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.GRAY);
BeginMode3D(camera);
// Draw the three models
DrawModel(modelA, Vector3.Zero, 1.0f, Color.WHITE);
DrawModel(modelB, new Vector3(-2.6f, 0, 0), 1.0f, Color.WHITE);
DrawModel(modelC, new Vector3(2.6f, 0, 0), 1.0f, Color.WHITE);
for (int i = -20; i < 20; i += 2)
{
DrawModel(modelA, new Vector3(i, 0, 2), 1.0f, Color.WHITE);
}
EndMode3D();
DrawText(
$"Use up/down to change fog density [{fogDensity:F2}]",
10,
10,
20,
Color.RAYWHITE
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(modelA);
UnloadModel(modelB);
UnloadModel(modelC);
UnloadTexture(texture);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,138 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hot reloading
*
* NOTE: This example requires raylib OpenGL 3.3 for shaders support and only #version 330
* is currently supported. OpenGL ES 2.0 platforms are not supported at the moment.
*
* This example has been created using raylib 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HotReloading
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hot reloading");
string fragShaderFileName = "resources/shaders/glsl330/reload.fs";
long fragShaderFileModTime = GetFileModTime(fragShaderFileName);
// Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, fragShaderFileName);
// Get shader locations for required uniforms
int resolutionLoc = GetShaderLocation(shader, "resolution");
int mouseLoc = GetShaderLocation(shader, "mouse");
int timeLoc = GetShaderLocation(shader, "time");
float[] resolution = new[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
float totalTime = 0.0f;
bool shaderAutoReloading = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
totalTime += GetFrameTime();
Vector2 mouse = GetMousePosition();
float[] mousePos = new[] { mouse.X, mouse.Y };
// Set shader required uniform values
Raylib.SetShaderValue(shader, timeLoc, totalTime, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, mouseLoc, mousePos, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Hot shader reloading
if (shaderAutoReloading || (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON)))
{
long currentFragShaderModTime = GetFileModTime(fragShaderFileName);
// Check if shader file has been modified
if (currentFragShaderModTime != fragShaderFileModTime)
{
// Try reloading updated shader
Shader updatedShader = LoadShader(null, fragShaderFileName);
// It was correctly loaded
if (updatedShader.Id != 0) //rlGetShaderIdDefault())
{
UnloadShader(shader);
shader = updatedShader;
// Get shader locations for required uniforms
resolutionLoc = GetShaderLocation(shader, "resolution");
mouseLoc = GetShaderLocation(shader, "mouse");
timeLoc = GetShaderLocation(shader, "time");
// Reset required uniforms
Raylib.SetShaderValue(
shader,
resolutionLoc,
resolution,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
}
fragShaderFileModTime = currentFragShaderModTime;
}
}
if (IsKeyPressed(KeyboardKey.KEY_A))
{
shaderAutoReloading = !shaderAutoReloading;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// We only draw a white full-screen rectangle, frame is generated in shader
BeginShaderMode(shader);
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
string info = $"PRESS [A] to TOGGLE SHADER AUTOLOADING: {(shaderAutoReloading ? "AUTO" : "MANUAL")}";
DrawText(info, 10, 10, 10, shaderAutoReloading ? Color.RED : Color.BLACK);
if (!shaderAutoReloading)
{
DrawText("MOUSE CLICK to SHADER RE-LOADING", 10, 30, 10, Color.BLACK);
}
// DrawText($"Shader last modification: ", 10, 430, 10, Color.BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,235 @@
/*******************************************************************************************
*
* raylib [shaders] example - Hybrid Rendering
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
* Example contributed by Buğra Alptekin Sarı (@BugraAlptekinSari) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class HybridRender
{
struct RayLocs
{
public int CamPos;
public int CamDir;
public int ScreenCenter;
}
const int GLSL_VERSION = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - hybrid render");
// This shader calculates pixel depth and color using raymarch
Shader shdrRaymarch = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/hybrid_raymarch.fs");
// This Shader is a standard rasterization fragment shader with the addition of depth writing
// You are required to write depth for all shaders if one shader does it
Shader shdrRaster = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/hybrid_raster.fs");
// Declare struct used to store camera locs
RayLocs marchLocs = new();
// Fill the struct with shader locs.
marchLocs.CamPos = GetShaderLocation(shdrRaymarch, "camPos");
marchLocs.CamDir = GetShaderLocation(shdrRaymarch, "camDir");
marchLocs.ScreenCenter = GetShaderLocation(shdrRaymarch, "screenCenter");
// Transfer screenCenter position to shader. Which is used to calculate ray direction.
Vector2 screenCenter = new(screenWidth / 2, screenHeight / 2);
SetShaderValue(
shdrRaymarch,
marchLocs.ScreenCenter,
screenCenter,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
// Use customized function to create writable depth texture buffer
RenderTexture2D target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(0.5f, 1.0f, 1.5f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Camera FOV is pre-calculated in the camera Distance.
float camDist = 1.0f / (MathF.Tan(camera.FovY * 0.5f * Raylib.DEG2RAD));
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
// Update Camera Postion in the ray march shader.
SetShaderValue(
shdrRaymarch,
marchLocs.CamPos,
camera.Position,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
// Update Camera Looking Vector. Vector length determines FOV.
Vector3 camDir = Vector3.Normalize(camera.Target - camera.Position) * camDist;
SetShaderValue(shdrRaymarch, marchLocs.CamDir, camDir, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Draw into our custom render texture (framebuffer)
BeginTextureMode(target);
ClearBackground(Color.WHITE);
// Raymarch Scene
// Manually enable Depth Test to handle multiple rendering methods.
Rlgl.EnableDepthTest();
BeginShaderMode(shdrRaymarch);
DrawRectangleRec(new Rectangle(0, 0, screenWidth, screenHeight), Color.WHITE);
EndShaderMode();
// Rasterize Scene
BeginMode3D(camera);
BeginShaderMode(shdrRaster);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.RED);
DrawCubeV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.PURPLE);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.DARKGREEN);
DrawCubeV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.YELLOW);
DrawGrid(10, 1.0f);
EndShaderMode();
EndMode3D();
EndTextureMode();
// Draw custom render texture
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, screenWidth, -screenHeight),
Vector2.Zero,
Color.WHITE
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTextureDepthTex(target);
UnloadShader(shdrRaymarch);
UnloadShader(shdrRaster);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Load custom render texture, create a writable depth texture buffer
private static unsafe RenderTexture2D LoadRenderTextureDepthTex(int width, int height)
{
RenderTexture2D target = new();
// Load an empty framebuffer
target.Id = Rlgl.LoadFramebuffer(width, height);
if (target.Id > 0)
{
Rlgl.EnableFramebuffer(target.Id);
// Create color texture (default to RGBA)
target.Texture.Id = Rlgl.LoadTexture(
null,
width,
height,
PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
1
);
target.Texture.Width = width;
target.Texture.Height = height;
target.Texture.Format = PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.Texture.Mipmaps = 1;
// Create depth texture buffer (instead of raylib default renderbuffer)
target.Depth.Id = Rlgl.LoadTextureDepth(width, height, false);
target.Depth.Width = width;
target.Depth.Height = height;
target.Depth.Format = PixelFormat.PIXELFORMAT_COMPRESSED_PVRT_RGBA;
target.Depth.Mipmaps = 1;
// Attach color texture and depth texture to FBO
Rlgl.FramebufferAttach(
target.Id,
target.Texture.Id,
FramebufferAttachType.RL_ATTACHMENT_COLOR_CHANNEL0,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
Rlgl.FramebufferAttach(
target.Id,
target.Depth.Id,
FramebufferAttachType.RL_ATTACHMENT_DEPTH,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
{
TraceLog(TraceLogLevel.LOG_INFO, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}
Rlgl.DisableFramebuffer();
}
else
{
TraceLog(TraceLogLevel.LOG_WARNING, "FBO: Framebuffer object can not be created");
}
return target;
}
// Unload render texture from GPU memory (VRAM)
private static void UnloadRenderTextureDepthTex(RenderTexture2D target)
{
if (target.Id > 0)
{
// Color texture attached to FBO is deleted
Rlgl.UnloadTexture(target.Texture.Id);
Rlgl.UnloadTexture(target.Depth.Id);
// NOTE: Depth texture is automatically
// queried and deleted before deleting framebuffer
Rlgl.UnloadFramebuffer(target.Id);
}
}
}

View File

@ -0,0 +1,248 @@
/*******************************************************************************************
*
* raylib [shaders] example - julia sets
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3).
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by eggmund (@eggmund) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 eggmund (@eggmund) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class JuliaSet
{
const int GlslVersion = 330;
// A few good julia sets
static float[][] PointsOfInterest = new float[][] {
new float[] { -0.348827f, 0.607167f },
new float[] { -0.786268f, 0.169728f },
new float[] { -0.8f, 0.156f },
new float[] { 0.285f, 0.0f },
new float[] { -0.835f, -0.2321f },
new float[] { -0.70176f, -0.3842f },
};
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - julia sets");
// Load julia set shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/julia_set.fs");
// c constant to use in z^2 + c
float[] c = { PointsOfInterest[0][0], PointsOfInterest[0][1] };
// Offset and zoom to draw the julia set at. (centered on screen and default size)
float[] offset = { -(float)screenWidth / 2, -(float)screenHeight / 2 };
float zoom = 1.0f;
Vector2 offsetSpeed = new(0.0f, 0.0f);
// Get variable (uniform) locations on the shader to connect with the program
// NOTE: If uniform variable could not be found in the shader, function returns -1
int cLoc = GetShaderLocation(shader, "c");
int zoomLoc = GetShaderLocation(shader, "zoom");
int offsetLoc = GetShaderLocation(shader, "offset");
// Tell the shader what the screen dimensions, zoom, offset and c are
float[] screenDims = { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "screenDims"),
screenDims,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
Raylib.SetShaderValue(shader, zoomLoc, zoomLoc, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Multiplier of speed to change c value
int incrementSpeed = 0;
// Show controls
bool showControls = true;
// Pause animation
bool pause = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// Press [1 - 6] to reset c to a point of interest
if (IsKeyPressed(KeyboardKey.KEY_ONE) ||
IsKeyPressed(KeyboardKey.KEY_TWO) ||
IsKeyPressed(KeyboardKey.KEY_THREE) ||
IsKeyPressed(KeyboardKey.KEY_FOUR) ||
IsKeyPressed(KeyboardKey.KEY_FIVE) ||
IsKeyPressed(KeyboardKey.KEY_SIX))
{
if (IsKeyPressed(KeyboardKey.KEY_ONE))
{
c[0] = PointsOfInterest[0][0];
c[1] = PointsOfInterest[0][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_TWO))
{
c[0] = PointsOfInterest[1][0];
c[1] = PointsOfInterest[1][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_THREE))
{
c[0] = PointsOfInterest[2][0];
c[1] = PointsOfInterest[2][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_FOUR))
{
c[0] = PointsOfInterest[3][0];
c[1] = PointsOfInterest[3][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_FIVE))
{
c[0] = PointsOfInterest[4][0];
c[1] = PointsOfInterest[4][1];
}
else if (IsKeyPressed(KeyboardKey.KEY_SIX))
{
c[0] = PointsOfInterest[5][0];
c[1] = PointsOfInterest[5][1];
}
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
}
// Pause animation (c change)
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
pause = !pause;
}
// Toggle whether or not to show controls
if (IsKeyPressed(KeyboardKey.KEY_F1))
{
showControls = !showControls;
}
if (!pause)
{
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
incrementSpeed++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
incrementSpeed--;
}
// TODO: The idea is to zoom and move around with mouse
// Probably offset movement should be proportional to zoom level
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON) || IsMouseButtonDown(MouseButton.MOUSE_RIGHT_BUTTON))
{
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON))
{
zoom += zoom * 0.003f;
}
if (IsMouseButtonDown(MouseButton.MOUSE_RIGHT_BUTTON))
{
zoom -= zoom * 0.003f;
}
Vector2 mousePos = GetMousePosition();
offsetSpeed.X = mousePos.X - (float)screenWidth / 2;
offsetSpeed.Y = mousePos.Y - (float)screenHeight / 2;
// Slowly move camera to targetOffset
offset[0] += GetFrameTime() * offsetSpeed.X * 0.8f;
offset[1] += GetFrameTime() * offsetSpeed.Y * 0.8f;
}
else
{
offsetSpeed = new Vector2(0.0f, 0.0f);
}
Raylib.SetShaderValue(shader, zoomLoc, zoom, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, offsetLoc, offset, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
// Increment c value with time
float amount = GetFrameTime() * incrementSpeed * 0.0005f;
c[0] += amount;
c[1] += amount;
Raylib.SetShaderValue(shader, cLoc, c, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.BLACK);
// Using a render texture to draw Julia set
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.BLACK);
// Draw a rectangle in shader mode to be used as shader canvas
// NOTE: Rectangle uses font Color.white character texture coordinates,
// so shader can not be applied here directly because input vertexTexCoord
// do not represent full screen coordinates (space where want to apply shader)
DrawRectangle(0, 0, GetScreenWidth(), GetScreenHeight(), Color.BLACK);
EndTextureMode();
// Draw the saved texture and rendered julia set with shader
// NOTE: We do not invert texture on Y, already considered inside shader
BeginShaderMode(shader);
DrawTexture(target.Texture, 0, 0, Color.WHITE);
EndShaderMode();
if (showControls)
{
DrawText("Press Mouse buttons right/left to zoom in/out and move", 10, 15, 10, Color.RAYWHITE);
DrawText("Press KEY_F1 to toggle these controls", 10, 30, 10, Color.RAYWHITE);
DrawText("Press KEYS [1 - 6] to change point of interest", 10, 45, 10, Color.RAYWHITE);
DrawText("Press KEY_LEFT | KEY_RIGHT to change speed", 10, 60, 10, Color.RAYWHITE);
DrawText("Press KEY_SPACE to pause movement animation", 10, 75, 10, Color.RAYWHITE);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,326 @@
/*******************************************************************************************
*
* raylib [shaders] example - rlgl module usage for instanced meshes
*
* This example uses [rlgl] module funtionality (pseudo-OpenGL 1.1 style coding)
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by @seanpringle and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2020 @seanpringle
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class MeshInstancing
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int fps = 60;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - rlgl mesh instanced");
// Speed of jump animation
int speed = 30;
// Count of separate groups jumping around
int groups = 2;
// Maximum amplitude of jump
float amp = 10;
// Global variance in jump height
float variance = 0.8f;
// Individual cube's computed loop timer
float loop = 0.0f;
// Used for various 3D coordinate & vector ops
float x = 0.0f;
float y = 0.0f;
float z = 0.0f;
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(-125.0f, 125.0f, -125.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Number of instances to display
const int instances = 10000;
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
// Rotation state of instances
Matrix4x4[] rotations = new Matrix4x4[instances];
// Per-frame rotation animation of instances
Matrix4x4[] rotationsInc = new Matrix4x4[instances];
// Locations of instances
Matrix4x4[] translations = new Matrix4x4[instances];
// Scatter random cubes around
for (int i = 0; i < instances; i++)
{
x = GetRandomValue(-50, 50);
y = GetRandomValue(-50, 50);
z = GetRandomValue(-50, 50);
translations[i] = Matrix4x4.CreateTranslation(x, y, z);
x = GetRandomValue(0, 360);
y = GetRandomValue(0, 360);
z = GetRandomValue(0, 360);
Vector3 axis = Vector3.Normalize(new Vector3(x, y, z));
float angle = (float)GetRandomValue(0, 10) * DEG2RAD;
rotationsInc[i] = Matrix4x4.CreateFromAxisAngle(axis, angle);
rotations[i] = Matrix4x4.Identity;
}
// Pre-multiplied transformations passed to rlgl
Matrix4x4[] transforms = new Matrix4x4[instances];
Shader shader = LoadShader(
"resources/shaders/glsl330/lighting_instancing.vs",
"resources/shaders/glsl330/lighting.fs"
);
// Get some shader loactions
unsafe
{
int* locs = (int*)shader.Locs;
locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MVP] = GetShaderLocation(shader, "mvp");
locs[(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
locs[(int)ShaderLocationIndex.SHADER_LOC_MATRIX_MODEL] = GetShaderLocationAttrib(
shader,
"instanceTransform"
);
}
// Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient");
Raylib.SetShaderValue(
shader,
ambientLoc,
new float[] { 0.2f, 0.2f, 0.2f, 1.0f },
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
Rlights.CreateLight(
0,
LightType.Directorional,
new Vector3(50, 50, 0),
Vector3.Zero,
Color.WHITE,
shader
);
Material material = LoadMaterialDefault();
material.Shader = shader;
unsafe
{
material.Maps[(int)MaterialMapIndex.MATERIAL_MAP_DIFFUSE].Color = Color.RED;
}
int textPositionY = 300;
// Simple frames counter to manage animation
int framesCounter = 0;
SetTargetFPS(fps);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
textPositionY = 300;
framesCounter += 1;
if (IsKeyDown(KeyboardKey.KEY_UP))
{
amp += 0.5f;
}
if (IsKeyDown(KeyboardKey.KEY_DOWN))
{
amp = (amp <= 1) ? 1.0f : (amp - 1.0f);
}
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
variance = (variance <= 0.0f) ? 0.0f : (variance - 0.01f);
}
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
variance = (variance >= 1.0f) ? 1.0f : (variance + 0.01f);
}
if (IsKeyDown(KeyboardKey.KEY_ONE))
{
groups = 1;
}
if (IsKeyDown(KeyboardKey.KEY_TWO))
{
groups = 2;
}
if (IsKeyDown(KeyboardKey.KEY_THREE))
{
groups = 3;
}
if (IsKeyDown(KeyboardKey.KEY_FOUR))
{
groups = 4;
}
if (IsKeyDown(KeyboardKey.KEY_FIVE))
{
groups = 5;
}
if (IsKeyDown(KeyboardKey.KEY_SIX))
{
groups = 6;
}
if (IsKeyDown(KeyboardKey.KEY_SEVEN))
{
groups = 7;
}
if (IsKeyDown(KeyboardKey.KEY_EIGHT))
{
groups = 8;
}
if (IsKeyDown(KeyboardKey.KEY_NINE))
{
groups = 9;
}
if (IsKeyDown(KeyboardKey.KEY_W))
{
groups = 7;
amp = 25;
speed = 18;
variance = 0.70f;
}
if (IsKeyDown(KeyboardKey.KEY_EQUAL))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.KEY_KP_ADD))
{
speed = (speed <= (int)(fps * 0.25f)) ? (int)(fps * 0.25f) : (int)(speed * 0.95f);
}
if (IsKeyDown(KeyboardKey.KEY_MINUS))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
if (IsKeyDown(KeyboardKey.KEY_KP_SUBTRACT))
{
speed = (int)MathF.Max(speed * 1.02f, speed + 1);
}
// Update the light shader with the camera view position
float[] cameraPos = { camera.Position.X, camera.Position.Y, camera.Position.Z };
Raylib.SetShaderValue(
shader,
(int)ShaderLocationIndex.SHADER_LOC_VECTOR_VIEW,
cameraPos,
ShaderUniformDataType.SHADER_UNIFORM_VEC3
);
// Apply per-instance transformations
for (int i = 0; i < instances; i++)
{
rotations[i] = Matrix4x4.Multiply(rotations[i], rotationsInc[i]);
transforms[i] = Matrix4x4.Multiply(rotations[i], translations[i]);
// Get the animation cycle's framesCounter for this instance
loop = (float)((framesCounter + (int)(((float)(i % groups) / groups) * speed)) % speed) / speed;
// Calculate the y according to loop cycle
y = (MathF.Sin(loop * MathF.PI * 2)) * amp * ((1 - variance) + (variance * (float)(i % (groups * 10)) / (groups * 10)));
// Clamp to floor
y = (y < 0) ? 0.0f : y;
transforms[i] = Matrix4x4.Multiply(transforms[i], Matrix4x4.CreateTranslation(0.0f, y, 0.0f));
transforms[i] = Matrix4x4.Transpose(transforms[i]);
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawMeshInstanced(cube, material, transforms, instances);
EndMode3D();
DrawText("A CUBE OF DANCING CUBES!", 490, 10, 20, Color.MAROON);
DrawText("PRESS KEYS:", 10, textPositionY, 20, Color.BLACK);
DrawText("1 - 9", 10, textPositionY += 25, 10, Color.BLACK);
DrawText(": Number of groups", 50, textPositionY, 10, Color.BLACK);
DrawText($": {groups}", 160, textPositionY, 10, Color.BLACK);
DrawText("UP", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": increase amplitude", 50, textPositionY, 10, Color.BLACK);
DrawText($": {amp}%.2f", 160, textPositionY, 10, Color.BLACK);
DrawText("DOWN", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": decrease amplitude", 50, textPositionY, 10, Color.BLACK);
DrawText("LEFT", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": decrease variance", 50, textPositionY, 10, Color.BLACK);
DrawText($": {variance}.2f", 160, textPositionY, 10, Color.BLACK);
DrawText("RIGHT", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": increase variance", 50, textPositionY, 10, Color.BLACK);
DrawText("+/=", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": increase speed", 50, textPositionY, 10, Color.BLACK);
DrawText($": {speed} = {((float)fps / speed)} loops/sec", 160, textPositionY, 10, Color.BLACK);
DrawText("-", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": decrease speed", 50, textPositionY, 10, Color.BLACK);
DrawText("W", 10, textPositionY += 15, 10, Color.BLACK);
DrawText(": Wild setup!", 50, textPositionY, 10, Color.BLACK);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,108 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to a 3d model
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ModelShader
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - model shader");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(4.0f, 4.0f, 4.0f);
camera.Target = new Vector3(0.0f, 1.0f, -1.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/watermill.obj");
Texture2D texture = LoadTexture("resources/models/watermill_diffuse.png");
Shader shader = LoadShader("resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/grayscale.fs");
Raylib.SetMaterialShader(ref model, 0, ref shader);
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.2f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
DrawText(
"(c) Watermill 3D model by Alberto Cano",
screenWidth - 210,
screenHeight - 20,
10,
Color.GRAY
);
DrawText($"Camera3D position: ({camera.Position})", 600, 20, 10, Color.BLACK);
DrawText($"Camera3D target: ({camera.Position})", 600, 40, 10, Color.GRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
UnloadModel(model);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,116 @@
/*******************************************************************************************
*
* raylib [shaders] example - Multiple sample2D with default batch system
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2020 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class MultiSample2d
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - multiple sample2D");
Image imRed = GenImageColor(800, 450, new Color(255, 0, 0, 255));
Texture2D texRed = LoadTextureFromImage(imRed);
UnloadImage(imRed);
Image imBlue = GenImageColor(800, 450, new Color(0, 0, 255, 255));
Texture2D texBlue = LoadTextureFromImage(imBlue);
UnloadImage(imBlue);
Shader shader = LoadShader(null, "resources/shaders/glsl330/color_mix.fs");
// Get an additional sampler2D location to be enabled on drawing
int texBlueLoc = GetShaderLocation(shader, "texture1");
// Get shader uniform for divider
int dividerLoc = GetShaderLocation(shader, "divider");
float dividerValue = 0.5f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
dividerValue += 0.01f;
}
else if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
dividerValue -= 0.01f;
}
if (dividerValue < 0.0f)
{
dividerValue = 0.0f;
}
else if (dividerValue > 1.0f)
{
dividerValue = 1.0f;
}
Raylib.SetShaderValue(shader, dividerLoc, dividerValue, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shader);
// WARNING: Additional samplers are enabled for all draw calls in the batch,
// EndShaderMode() forces batch drawing and consequently resets active textures
// to let other sampler2D to be activated on consequent drawings (if required)
SetShaderValueTexture(shader, texBlueLoc, texBlue);
// We are drawing texRed using default sampler2D texture0 but
// an additional texture units is enabled for texBlue (sampler2D texture1)
DrawTexture(texRed, 0, 0, Color.WHITE);
EndShaderMode();
int y = GetScreenHeight() - 40;
DrawText("Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", 80, y, 20, Color.RAYWHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texRed);
UnloadTexture(texBlue);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,166 @@
/*******************************************************************************************
*
* raylib [shaders] example - Color palette switch
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 2.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Marco Lizza (@MarcoLizza) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Marco Lizza (@MarcoLizza) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PaletteSwitch
{
const int GlslVersion = 330;
const int ColorsPerPalette = 8;
const int VALUES_PER_COLOR = 3;
static int[][] Palettes = new int[][] {
// 3-BIT RGB
new int[] {
0, 0, 0,
255, 0, 0,
0, 255, 0,
0, 0, 255,
0, 255, 255,
255, 0, 255,
255, 255, 0,
255, 255, 255,
},
// AMMO-8 (GameBoy-like)
new int[] {
4, 12, 6,
17, 35, 24,
30, 58, 41,
48, 93, 66,
77, 128, 97,
137, 162, 87,
190, 220, 127,
238, 255, 204,
},
// RKBV (2-strip film)
new int[] {
21, 25, 26,
138, 76, 88,
217, 98, 117,
230, 184, 193,
69, 107, 115,
75, 151, 166,
165, 189, 194,
255, 245, 247,
}
};
static string[] PaletteText = new string[] {
"3-BIT RGB",
"AMMO-8 (GameBoy-like)",
"RKBV (2-strip film)"
};
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - color palette switch");
// Load shader to be used on some parts drawing
// NOTE 1: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
// NOTE 2: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/palette_switch.fs");
// Get variable (uniform) location on the shader to connect with the program
// NOTE: If uniform variable could not be found in the shader, function returns -1
int paletteLoc = GetShaderLocation(shader, "palette");
int currentPalette = 0;
int lineHeight = screenHeight / ColorsPerPalette;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
currentPalette++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
currentPalette--;
}
if (currentPalette >= Palettes.Length)
{
currentPalette = 0;
}
else if (currentPalette < 0)
{
currentPalette = Palettes.Length - 1;
}
// Send new value to the shader to be used on drawing.
// NOTE: We are sending RGB triplets w/o the alpha channel
Raylib.SetShaderValueV(
shader,
paletteLoc,
Palettes[currentPalette],
ShaderUniformDataType.SHADER_UNIFORM_IVEC3,
ColorsPerPalette
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shader);
for (int i = 0; i < ColorsPerPalette; i++)
{
// Draw horizontal screen-wide rectangles with increasing "palette index"
// The used palette index is encoded in the RGB components of the pixel
DrawRectangle(0, lineHeight * i, GetScreenWidth(), lineHeight, new Color(i, i, i, 255));
}
EndShaderMode();
DrawText("< >", 10, 10, 30, Color.DARKBLUE);
DrawText("CURRENT PALETTE:", 60, 15, 20, Color.RAYWHITE);
DrawText(PaletteText[currentPalette], 300, 15, 20, Color.RED);
DrawFPS(700, 15);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,206 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a postprocessing shader to a scene
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 1.3 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class PostProcessing
{
public const int GLSL_VERSION = 330;
enum PostproShader
{
FxGrayScale = 0,
FxPosterization,
FxDreamVision,
FxPixelizer,
FxCrossHatching,
FxCrossStiching,
FxPredatorView,
FxScanLines,
FxFishEye,
FxSobel,
FxBloom,
FxBlur,
//FX_FXAA
Max
}
static string[] postproShaderText = new string[] {
"GRAYSCALE",
"POSTERIZATION",
"DREAM_VISION",
"PIXELIZER",
"CROSS_HATCHING",
"CROSS_STITCHING",
"PREDATOR_VIEW",
"SCANLINES",
"FISHEYE",
"SOBEL",
"BLOOM",
"BLUR",
//"FXAA"
};
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
// Enable Multi Sampling Anti Aliasing 4x (if available)
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - postprocessing shader");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(2.0f, 3.0f, 2.0f);
camera.Target = new Vector3(0.0f, 1.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
Model model = LoadModel("resources/models/church.obj");
Texture2D texture = LoadTexture("resources/models/church_diffuse.png");
// Set model diffuse texture
Raylib.SetMaterialTexture(ref model, 0, MaterialMapIndex.MATERIAL_MAP_ALBEDO, ref texture);
Vector3 position = new(0.0f, 0.0f, 0.0f);
// Load all postpro shaders
// NOTE 1: All postpro shader use the base vertex shader (DEFAULT_VERTEX_SHADER)
// NOTE 2: We load the correct shader depending on GLSL version
Shader[] shaders = new Shader[(int)PostproShader.Max];
// NOTE: Defining null (NULL) for vertex shader forces usage of internal default vertex shader
string shaderPath = "resources/shaders/glsl330";
shaders[(int)PostproShader.FxGrayScale] = LoadShader(null, $"{shaderPath}/grayscale.fs");
shaders[(int)PostproShader.FxPosterization] = LoadShader(null, $"{shaderPath}/posterization.fs");
shaders[(int)PostproShader.FxDreamVision] = LoadShader(null, $"{shaderPath}/dream_vision.fs");
shaders[(int)PostproShader.FxPixelizer] = LoadShader(null, $"{shaderPath}/pixelizer.fs");
shaders[(int)PostproShader.FxCrossHatching] = LoadShader(null, $"{shaderPath}/cross_hatching.fs");
shaders[(int)PostproShader.FxCrossStiching] = LoadShader(null, $"{shaderPath}/cross_stitching.fs");
shaders[(int)PostproShader.FxPredatorView] = LoadShader(null, $"{shaderPath}/predator.fs");
shaders[(int)PostproShader.FxScanLines] = LoadShader(null, $"{shaderPath}/scanlines.fs");
shaders[(int)PostproShader.FxFishEye] = LoadShader(null, $"{shaderPath}/fisheye.fs");
shaders[(int)PostproShader.FxSobel] = LoadShader(null, $"{shaderPath}/sobel.fs");
shaders[(int)PostproShader.FxBloom] = LoadShader(null, $"{shaderPath}/bloom.fs");
shaders[(int)PostproShader.FxBlur] = LoadShader(null, $"{shaderPath}/blur.fs");
int currentShader = (int)PostproShader.FxGrayScale;
// Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
currentShader++;
}
else if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
currentShader--;
}
if (currentShader >= (int)PostproShader.Max)
{
currentShader = 0;
}
else if (currentShader < 0)
{
currentShader = (int)PostproShader.Max - 1;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable drawing to texture
BeginTextureMode(target);
ClearBackground(Color.RAYWHITE);
BeginMode3D(camera);
DrawModel(model, position, 0.1f, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
// End drawing to texture (now we have a texture available for next passes)
EndTextureMode();
// Render previously generated texture using selected postpro shader
BeginShaderMode(shaders[currentShader]);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, target.Texture.Width, -target.Texture.Height),
new Vector2(0, 0),
Color.WHITE
);
EndShaderMode();
DrawRectangle(0, 9, 580, 30, ColorAlpha(Color.LIGHTGRAY, 0.7f));
DrawText("(c) Church 3D model by Alberto Cano", screenWidth - 200, screenHeight - 20, 10, Color.GRAY);
DrawText("CURRENT POSTPRO SHADER:", 10, 15, 20, Color.BLACK);
DrawText(postproShaderText[currentShader], 330, 15, 20, Color.RED);
DrawText("< >", 540, 10, 30, Color.DARKBLUE);
DrawFPS(700, 15);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < (int)PostproShader.Max; i++)
{
UnloadShader(shaders[i]);
}
UnloadTexture(texture);
UnloadModel(model);
UnloadRenderTexture(target);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,121 @@
/*******************************************************************************************
*
* raylib [shaders] example - Raymarching shapes generation
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2018 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.ConfigFlags;
namespace Examples.Shaders;
public class Raymarching
{
public const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE);
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - raymarching shapes");
Camera3D camera = new();
camera.Position = new Vector3(2.5f, 2.5f, 3.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.7f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 65.0f;
// Load raymarching shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/raymarching.fs");
// Get shader locations for required uniforms
int viewEyeLoc = GetShaderLocation(shader, "viewEye");
int viewCenterLoc = GetShaderLocation(shader, "viewCenter");
int runTimeLoc = GetShaderLocation(shader, "runTime");
int resolutionLoc = GetShaderLocation(shader, "resolution");
float[] resolution = { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
float runTime = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Check if screen is resized
//----------------------------------------------------------------------------------
if (IsWindowResized())
{
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
resolution = new float[] { (float)screenWidth, (float)screenHeight };
Raylib.SetShaderValue(shader, resolutionLoc, resolution, ShaderUniformDataType.SHADER_UNIFORM_VEC2);
}
// Update
//----------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_FREE);
float deltaTime = GetFrameTime();
runTime += deltaTime;
// Set shader required uniform values
Raylib.SetShaderValue(shader, viewEyeLoc, camera.Position, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
Raylib.SetShaderValue(shader, viewCenterLoc, camera.Target, ShaderUniformDataType.SHADER_UNIFORM_VEC3);
Raylib.SetShaderValue(shader, runTimeLoc, runTime, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// We only draw a white full-screen rectangle,
// frame is generated in shader using raymarching
BeginShaderMode(shader);
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
DrawText(
"(c) Raymarching shader by Iñigo Quilez. MIT License.",
screenWidth - 280,
screenHeight - 20,
10,
Color.BLACK
);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,121 @@
/*******************************************************************************************
*
* raylib [shaders] example - Apply a shader to some shape or texture
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class ShapesTextures
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - shapes and texture shaders");
Texture2D fudesumi = LoadTexture("resources/fudesumi.png");
// NOTE: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
Shader shader = LoadShader(
"resources/shaders/glsl330/base.vs",
"resources/shaders/glsl330/grayscale.fs"
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Start drawing with default shader
DrawText("USING DEFAULT SHADER", 20, 40, 10, Color.RED);
DrawCircle(80, 120, 35, Color.DARKBLUE);
DrawCircleGradient(80, 220, 60, Color.GREEN, Color.SKYBLUE);
DrawCircleLines(80, 340, 80, Color.DARKBLUE);
// Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader);
DrawText("USING CUSTOM SHADER", 190, 40, 10, Color.RED);
DrawRectangle(250 - 60, 90, 120, 60, Color.RED);
DrawRectangleGradientH(250 - 90, 170, 180, 130, Color.MAROON, Color.GOLD);
DrawRectangleLines(250 - 40, 320, 80, 60, Color.ORANGE);
// Activate our default shader for next drawings
EndShaderMode();
DrawText("USING DEFAULT SHADER", 370, 40, 10, Color.RED);
DrawTriangle(
new Vector2(430, 80),
new Vector2(430 - 60, 150),
new Vector2(430 + 60, 150), Color.VIOLET
);
DrawTriangleLines(
new Vector2(430, 160),
new Vector2(430 - 20, 230),
new Vector2(430 + 20, 230), Color.DARKBLUE
);
DrawPoly(new Vector2(430, 320), 6, 80, 0, Color.BROWN);
// Activate our custom shader to be applied on next shapes/textures drawings
BeginShaderMode(shader);
// Using custom shader
DrawTexture(fudesumi, 500, -30, Color.WHITE);
// Activate our default shader for next drawings
EndShaderMode();
DrawText("(c) Fudesumi sprite by Eiden Marsal", 380, screenHeight - 20, 10, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(fudesumi);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,164 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@codifies) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* After a model is loaded it has a default material, this material can be
* modified in place rather than creating one from scratch...
* While all of the maps have particular names, they can be used for any purpose
* except for three maps that are applied as cubic maps (see below)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
using static Raylib_cs.Raymath;
namespace Examples.Shaders;
public class SimpleMask
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - simple shader mask");
// Define the camera to look into our 3d world
Camera3D camera = new();
camera.Position = new Vector3(0.0f, 1.0f, 2.0f);
camera.Target = new Vector3(0.0f, 0.0f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
// Define our three models to show the shader on
Mesh torus = GenMeshTorus(.3f, 1, 16, 32);
Model model1 = LoadModelFromMesh(torus);
Mesh cube = GenMeshCube(.8f, .8f, .8f);
Model model2 = LoadModelFromMesh(cube);
// Generate model to be shaded just to see the gaps in the other two
Mesh sphere = GenMeshSphere(1, 16, 16);
Model model3 = LoadModelFromMesh(sphere);
// Load the shader
Shader shader = LoadShader("resources/shaders/glsl330/mask.vs", "resources/shaders/glsl330/mask.fs");
// Load and apply the diffuse texture (colour map)
Texture2D texDiffuse = LoadTexture("resources/plasma.png");
Material* materials = model1.Materials;
MaterialMap* maps = materials[0].Maps;
model1.Materials[0].Maps[(int)MaterialMapIndex.MATERIAL_MAP_ALBEDO].Texture = texDiffuse;
materials = model2.Materials;
maps = materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_ALBEDO].Texture = texDiffuse;
// Using MAP_EMISSION as a spare slot to use for 2nd texture
// NOTE: Don't use MAP_IRRADIANCE, MAP_PREFILTER or MAP_CUBEMAP
// as they are bound as cube maps
Texture2D texMask = LoadTexture("resources/mask.png");
materials = model1.Materials;
maps = (MaterialMap*)materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_EMISSION].Texture = texMask;
materials = model2.Materials;
maps = (MaterialMap*)materials[0].Maps;
maps[(int)MaterialMapIndex.MATERIAL_MAP_EMISSION].Texture = texMask;
int* locs = shader.Locs;
locs[(int)ShaderLocationIndex.SHADER_LOC_MAP_EMISSION] = GetShaderLocation(shader, "mask");
// Frame is incremented each frame to animate the shader
int shaderFrame = GetShaderLocation(shader, "framesCounter");
// Apply the shader to the two models
materials = model1.Materials;
materials[0].Shader = shader;
materials = (Material*)model2.Materials;
materials[0].Shader = shader;
int framesCounter = 0;
// Model rotation angles
Vector3 rotation = new(0, 0, 0);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
framesCounter++;
rotation.X += 0.01f;
rotation.Y += 0.005f;
rotation.Z -= 0.0025f;
// Send frames counter to shader for animation
Raylib.SetShaderValue(shader, shaderFrame, framesCounter, ShaderUniformDataType.SHADER_UNIFORM_INT);
// Rotate one of the models
model1.Transform = MatrixRotateXYZ(rotation);
UpdateCamera(ref camera, CameraMode.CAMERA_CUSTOM);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.DARKBLUE);
BeginMode3D(camera);
DrawModel(model1, new Vector3(0.5f, 0, 0), 1, Color.WHITE);
DrawModelEx(model2, new Vector3(-.5f, 0, 0), new Vector3(1, 1, 0), 50, new Vector3(1, 1, 1), Color.WHITE);
DrawModel(model3, new Vector3(0, 0, -1.5f), 1, Color.WHITE);
DrawGrid(10, 1.0f);
EndMode3D();
string frameText = $"Frame: {framesCounter}";
DrawRectangle(16, 698, MeasureText(frameText, 20) + 8, 42, Color.BLUE);
DrawText(frameText, 20, 700, 20, Color.WHITE);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadModel(model1);
UnloadModel(model2);
UnloadModel(model3);
UnloadTexture(texDiffuse);
UnloadTexture(texMask);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,286 @@
/*******************************************************************************************
*
* raylib [shaders] example - Simple shader mask
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Chris Camacho (@chriscamacho - http://bedroomcoders.co.uk/)
* and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
*
********************************************************************************************
*
* The shader makes alpha holes in the forground to give the apearance of a top
* down look at a spotlight casting a pool of light...
*
* The right hand side of the screen there is just enough light to see whats
* going on without the spot light, great for a stealth type game where you
* have to avoid the spotlights.
*
* The left hand side of the screen is in pitch dark except for where the spotlights are.
*
* Although this example doesn't scale like the letterbox example, you could integrate
* the two techniques, but by scaling the actual colour of the render texture rather
* than using alpha as a mask.
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class Spotlight
{
// NOTE: It must be the same as define in shader
const int MaxSpots = 3;
const int MaxStars = 400;
// Spot data
struct Spot
{
public Vector2 pos;
public Vector2 vel;
public float inner;
public float radius;
// Shader locations
public int posLoc;
public int innerLoc;
public int radiusLoc;
}
// Stars in the star field have a position and velocity
struct Star
{
public Vector2 pos;
public Vector2 vel;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib - shader spotlight");
HideCursor();
Texture2D texRay = LoadTexture("resources/raysan.png");
Star[] stars = new Star[MaxStars];
for (int n = 0; n < MaxStars; n++)
{
ResetStar(ref stars[n]);
}
// Progress all the stars on, so they don't all start in the centre
for (int m = 0; m < screenWidth / 2.0; m++)
{
for (int n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
}
int frameCounter = 0;
// Use default vert shader
Shader shdrSpot = LoadShader(null, "resources/shaders/glsl330/spotlight.fs");
// Get the locations of spots in the shader
Spot[] spots = new Spot[MaxSpots];
for (int i = 0; i < MaxSpots; i++)
{
string posName = $"spots[{i}].pos";
string innerName = $"spots[{i}].inner";
string radiusName = $"spots[{i}].radius";
spots[i].posLoc = GetShaderLocation(shdrSpot, posName);
spots[i].innerLoc = GetShaderLocation(shdrSpot, innerName);
spots[i].radiusLoc = GetShaderLocation(shdrSpot, radiusName);
}
// Tell the shader how wide the screen is so we can have
// a pitch Color.black half and a dimly lit half.
int wLoc = GetShaderLocation(shdrSpot, "screenWidth");
float sw = (float)GetScreenWidth();
Raylib.SetShaderValue(shdrSpot, wLoc, sw, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
// Randomise the locations and velocities of the spotlights
// and initialise the shader locations
for (int i = 0; i < MaxSpots; i++)
{
spots[i].pos.X = GetRandomValue(64, screenWidth - 64);
spots[i].pos.Y = GetRandomValue(64, screenHeight - 64);
spots[i].vel = new Vector2(0, 0);
while ((MathF.Abs(spots[i].vel.X) + MathF.Abs(spots[i].vel.Y)) < 2)
{
spots[i].vel.X = GetRandomValue(-40, 40) / 10.0f;
spots[i].vel.Y = GetRandomValue(-40, 40) / 10.0f;
}
spots[i].inner = 28.0f * (i + 1);
spots[i].radius = 48.0f * (i + 1);
Raylib.SetShaderValue(
shdrSpot,
spots[i].posLoc,
spots[i].pos,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(
shdrSpot,
spots[i].innerLoc,
spots[i].inner,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
Raylib.SetShaderValue(
shdrSpot,
spots[i].radiusLoc,
spots[i].radius,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
}
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
frameCounter++;
// Move the stars, resetting them if the go offscreen
for (int n = 0; n < MaxStars; n++)
{
UpdateStar(ref stars[n]);
}
// Update the spots, send them to the shader
for (int i = 0; i < MaxSpots; i++)
{
if (i == 0)
{
Vector2 mp = GetMousePosition();
spots[i].pos.X = mp.X;
spots[i].pos.Y = screenHeight - mp.Y;
}
else
{
spots[i].pos.X += spots[i].vel.X;
spots[i].pos.Y += spots[i].vel.Y;
if (spots[i].pos.X < 64)
{
spots[i].vel.X = -spots[i].vel.X;
}
if (spots[i].pos.X > (screenWidth - 64))
{
spots[i].vel.X = -spots[i].vel.X;
}
if (spots[i].pos.Y < 64)
{
spots[i].vel.Y = -spots[i].vel.Y;
}
if (spots[i].pos.Y > (screenHeight - 64))
{
spots[i].vel.Y = -spots[i].vel.Y;
}
}
Raylib.SetShaderValue(
shdrSpot,
spots[i].posLoc,
spots[i].pos,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
}
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.DARKBLUE);
// Draw stars and bobs
for (int n = 0; n < MaxStars; n++)
{
// MathF.Single pixel is just too small these days!
DrawRectangle((int)stars[n].pos.X, (int)stars[n].pos.Y, 2, 2, Color.WHITE);
}
for (int i = 0; i < 16; i++)
{
DrawTexture(
texRay,
(int)((screenWidth / 2.0) + MathF.Cos((frameCounter + i * 8) / 51.45f) * (screenWidth / 2.2) - 32),
(int)((screenHeight / 2.0) + MathF.Sin((frameCounter + i * 8) / 17.87f) * (screenHeight / 4.2)),
Color.WHITE
);
}
// Draw spot lights
BeginShaderMode(shdrSpot);
// Instead of a blank rectangle you could render a render texture of the full screen used to do screen
// scaling (slight adjustment to shader would be required to actually pay attention to the colour!)
DrawRectangle(0, 0, screenWidth, screenHeight, Color.WHITE);
EndShaderMode();
DrawFPS(10, 10);
DrawText("Move the mouse!", 10, 30, 20, Color.GREEN);
DrawText("Pitch Color.Black", (int)(screenWidth * 0.2f), screenHeight / 2, 20, Color.GREEN);
DrawText("Dark", (int)(screenWidth * 0.66f), screenHeight / 2, 20, Color.GREEN);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texRay);
UnloadShader(shdrSpot);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
static void ResetStar(ref Star s)
{
s.pos = new Vector2(GetScreenWidth() / 2.0f, GetScreenHeight() / 2.0f);
do
{
s.vel.X = (float)GetRandomValue(-1000, 1000) / 100.0f;
s.vel.Y = (float)GetRandomValue(-1000, 1000) / 100.0f;
} while (!((MathF.Abs(s.vel.X) + (MathF.Abs(s.vel.Y)) > 1)));
s.pos += s.pos + (s.vel * new Vector2(8.0f, 8.0f));
}
static void UpdateStar(ref Star s)
{
s.pos += s.vel;
if ((s.pos.X < 0) || (s.pos.X > GetScreenWidth()) ||
(s.pos.Y < 0) || (s.pos.Y > GetScreenHeight()))
{
ResetStar(ref s);
}
}
}

View File

@ -0,0 +1,86 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
*
* This example illustrates how to draw on a blank texture using a shader
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureDrawing
{
const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture drawing");
// Load blank texture to fill on shader
Image imBlank = GenImageColor(1024, 1024, Color.BLANK);
Texture2D texture = LoadTextureFromImage(imBlank);
UnloadImage(imBlank);
// NOTE: Using GLSL 330 shader version, on OpenGL ES 2.0 use GLSL 100 shader version
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/cubes_panning.fs");
float time = 0.0f;
int timeLoc = GetShaderLocation(shader, "uTime");
Raylib.SetShaderValue(shader, timeLoc, time, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
time = (float)GetTime();
Raylib.SetShaderValue(shader, timeLoc, time, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Enable our custom shader for next shapes/textures drawings
BeginShaderMode(shader);
// Drawing blank texture, all magic happens on shader
DrawTexture(texture, 0, 0, Color.WHITE);
// Disable our custom shader, return to default shader
EndShaderMode();
DrawText("BACKGROUND is PAINTED and ANIMATED on SHADER!", 10, 10, 20, Color.MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,119 @@
/*******************************************************************************************
*
* raylib [textures] example - Texture drawing
*
* This example illustrates how to draw on a blank texture using a shader
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Michał Ciesielski and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Michał Ciesielski and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureOutline
{
const int GLSL_VERSION = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Apply an outline to a texture");
Texture2D texture = LoadTexture("resources/fudesumi.png");
Shader shdrOutline = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/outline.fs");
float outlineSize = 2.0f;
// Normalized red color
float[] outlineColor = new[] { 1.0f, 0.0f, 0.0f, 1.0f };
float[] textureSize = { (float)texture.Width, (float)texture.Height };
// Get shader locations
int outlineSizeLoc = GetShaderLocation(shdrOutline, "outlineSize");
int outlineColorLoc = GetShaderLocation(shdrOutline, "outlineColor");
int textureSizeLoc = GetShaderLocation(shdrOutline, "textureSize");
// Set shader values (they can be changed later)
Raylib.SetShaderValue(
shdrOutline,
outlineSizeLoc,
outlineSize,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
Raylib.SetShaderValue(
shdrOutline,
outlineColorLoc,
outlineColor,
ShaderUniformDataType.SHADER_UNIFORM_VEC4
);
Raylib.SetShaderValue(
shdrOutline,
textureSizeLoc,
textureSize,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
outlineSize += GetMouseWheelMove();
if (outlineSize < 1.0f)
{
outlineSize = 1.0f;
}
Raylib.SetShaderValue(
shdrOutline,
outlineSizeLoc,
outlineSize,
ShaderUniformDataType.SHADER_UNIFORM_FLOAT
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shdrOutline);
DrawTexture(texture, GetScreenWidth() / 2 - texture.Width / 2, -30, Color.WHITE);
EndShaderMode();
DrawText("Shader-based\ntexture\noutline", 10, 10, 20, Color.GRAY);
DrawText($"Outline size: {outlineSize} px", 10, 120, 20, Color.MAROON);
DrawFPS(710, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texture);
UnloadShader(shdrOutline);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,115 @@
/*******************************************************************************************
*
* raylib [shaders] example - Texture Waves
*
* NOTE: This example requires raylib OpenGL 3.3 or ES2 versions for shaders support,
* OpenGL 1.1 does not support shaders, recompile raylib to OpenGL 3.3 version.
*
* NOTE: Shaders used in this example are #version 330 (OpenGL 3.3), to test this example
* on OpenGL ES 2.0 platforms (Android, Raspberry Pi, HTML5), use #version 100 shaders
* raylib comes with shaders ready for both versions, check raylib/shaders install folder
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Anata (@anatagawa) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Anata (@anatagawa) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class TextureWaves
{
const int GlslVersion = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture waves");
// Load texture texture to apply shaders
Texture2D texture = LoadTexture("resources/space.png");
// Load shader and setup location points and values
Shader shader = LoadShader(null, $"resources/shaders/glsl{GlslVersion}/wave.fs");
int secondsLoc = GetShaderLocation(shader, "secondes");
int freqXLoc = GetShaderLocation(shader, "freqX");
int freqYLoc = GetShaderLocation(shader, "freqY");
int ampXLoc = GetShaderLocation(shader, "ampX");
int ampYLoc = GetShaderLocation(shader, "ampY");
int speedXLoc = GetShaderLocation(shader, "speedX");
int speedYLoc = GetShaderLocation(shader, "speedY");
// Shader uniform values that can be updated at any time
float freqX = 25.0f;
float freqY = 25.0f;
float ampX = 5.0f;
float ampY = 5.0f;
float speedX = 8.0f;
float speedY = 8.0f;
float[] screenSize = { (float)GetScreenWidth(), (float)GetScreenHeight() };
Raylib.SetShaderValue(
shader,
GetShaderLocation(shader, "size"),
screenSize,
ShaderUniformDataType.SHADER_UNIFORM_VEC2
);
Raylib.SetShaderValue(shader, freqXLoc, freqX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, freqYLoc, freqY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, ampXLoc, ampX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, ampYLoc, ampY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, speedXLoc, speedX, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
Raylib.SetShaderValue(shader, speedYLoc, speedY, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
float seconds = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
seconds += GetFrameTime();
Raylib.SetShaderValue(shader, secondsLoc, seconds, ShaderUniformDataType.SHADER_UNIFORM_FLOAT);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
BeginShaderMode(shader);
DrawTexture(texture, 0, 0, Color.WHITE);
DrawTexture(texture, texture.Width, 0, Color.WHITE);
EndShaderMode();
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadShader(shader);
UnloadTexture(texture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,177 @@
/*******************************************************************************************
*
* raylib [shaders] example - Depth buffer writing
*
* Example originally created with raylib 4.2, last time updated with raylib 4.2
*
* Example contributed by Buğra Alptekin Sarı (@BugraAlptekinSari) and reviewed by Ramon Santamaria (@raysan5)
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Buğra Alptekin Sarı (@BugraAlptekinSari)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shaders;
public class WriteDepth
{
const int GLSL_VERSION = 330;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - write depth buffer");
// The shader inverts the depth buffer by writing into it by `gl_FragDepth = 1 - gl_FragCoord.z;`
Shader shader = LoadShader(null, $"resources/shaders/glsl{GLSL_VERSION}/write_depth.fs");
// Use customized function to create writable depth texture buffer
RenderTexture2D target = LoadRenderTextureDepthTex(screenWidth, screenHeight);
// Define the camera to look into our 3d world
Camera3D camera;
camera.Position = new Vector3(2.0f, 2.0f, 3.0f);
camera.Target = new Vector3(0.0f, 0.5f, 0.0f);
camera.Up = new Vector3(0.0f, 1.0f, 0.0f);
camera.FovY = 45.0f;
camera.Projection = CameraProjection.CAMERA_PERSPECTIVE;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
UpdateCamera(ref camera, CameraMode.CAMERA_ORBITAL);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
// Draw into our custom render texture (framebuffer)
BeginTextureMode(target);
ClearBackground(Color.WHITE);
BeginMode3D(camera);
BeginShaderMode(shader);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.RED);
DrawCubeV(new Vector3(0.0f, 0.5f, 1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.PURPLE);
DrawCubeWiresV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.DARKGREEN);
DrawCubeV(new Vector3(0.0f, 0.5f, -1.0f), new Vector3(1.0f, 1.0f, 1.0f), Color.YELLOW);
DrawGrid(10, 1.0f);
EndShaderMode();
EndMode3D();
EndTextureMode();
// Draw custom render texture
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawTextureRec(
target.Texture,
new Rectangle(0, 0, screenWidth, -screenHeight),
Vector2.Zero,
Color.WHITE
);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTextureDepthTex(target);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Load custom render texture, create a writable depth texture buffer
private static unsafe RenderTexture2D LoadRenderTextureDepthTex(int width, int height)
{
RenderTexture2D target = new();
// Load an empty framebuffer
target.Id = Rlgl.LoadFramebuffer(width, height);
if (target.Id > 0)
{
Rlgl.EnableFramebuffer(target.Id);
// Create color texture (default to RGBA)
target.Texture.Id = Rlgl.LoadTexture(
null,
width,
height,
PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
1
);
target.Texture.Width = width;
target.Texture.Height = height;
target.Texture.Format = PixelFormat.PIXELFORMAT_UNCOMPRESSED_R8G8B8A8;
target.Texture.Mipmaps = 1;
// Create depth texture buffer (instead of raylib default renderbuffer)
target.Depth.Id = Rlgl.LoadTextureDepth(width, height, false);
target.Depth.Width = width;
target.Depth.Height = height;
target.Depth.Format = PixelFormat.PIXELFORMAT_COMPRESSED_PVRT_RGBA;
target.Depth.Mipmaps = 1;
// Attach color texture and depth texture to FBO
Rlgl.FramebufferAttach(
target.Id,
target.Texture.Id,
FramebufferAttachType.RL_ATTACHMENT_COLOR_CHANNEL0,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
Rlgl.FramebufferAttach(
target.Id,
target.Depth.Id,
FramebufferAttachType.RL_ATTACHMENT_DEPTH,
FramebufferAttachTextureType.RL_ATTACHMENT_TEXTURE2D,
0
);
// Check if fbo is complete with attachments (valid)
if (Rlgl.FramebufferComplete(target.Id))
{
TraceLog(TraceLogLevel.LOG_INFO, $"FBO: [ID {target.Id}] Framebuffer object created successfully");
}
Rlgl.DisableFramebuffer();
}
else
{
TraceLog(TraceLogLevel.LOG_WARNING, "FBO: Framebuffer object can not be created");
}
return target;
}
// Unload render texture from GPU memory (VRAM)
private static void UnloadRenderTextureDepthTex(RenderTexture2D target)
{
if (target.Id > 0)
{
// Color texture attached to FBO is deleted
Rlgl.UnloadTexture(target.Texture.Id);
Rlgl.UnloadTexture(target.Depth.Id);
// NOTE: Depth texture is automatically
// queried and deleted before deleting framebuffer
Rlgl.UnloadFramebuffer(target.Id);
}
}
}

View File

@ -0,0 +1,81 @@
/*******************************************************************************************
*
* raylib [shapes] example - Draw basic shapes 2d (rectangle, circle, line...)
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class BasicShapes
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - basic shapes drawing");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("some basic shapes available on raylib", 20, 20, 20, Color.DARKGRAY);
DrawLine(18, 42, screenWidth - 18, 42, Color.BLACK);
DrawCircle(screenWidth / 4, 120, 35, Color.DARKBLUE);
DrawCircleGradient(screenWidth / 4, 220, 60, Color.GREEN, Color.SKYBLUE);
DrawCircleLines(screenWidth / 4, 340, 80, Color.DARKBLUE);
DrawRectangle(screenWidth / 4 * 2 - 60, 100, 120, 60, Color.RED);
DrawRectangleGradientH(screenWidth / 4 * 2 - 90, 170, 180, 130, Color.MAROON, Color.GOLD);
DrawRectangleLines(screenWidth / 4 * 2 - 40, 320, 80, 60, Color.ORANGE);
DrawTriangle(
new Vector2(screenWidth / 4 * 3, 80),
new Vector2(screenWidth / 4 * 3 - 60, 150),
new Vector2(screenWidth / 4 * 3 + 60, 150), Color.VIOLET
);
DrawTriangleLines(
new Vector2(screenWidth / 4 * 3, 160),
new Vector2(screenWidth / 4 * 3 - 20, 230),
new Vector2(screenWidth / 4 * 3 + 20, 230), Color.DARKBLUE
);
DrawPoly(new Vector2(screenWidth / 4 * 3, 320), 6, 80, 0, Color.BROWN);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,96 @@
/*******************************************************************************************
*
* raylib [shapes] example - bouncing ball
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class BouncingBall
{
public static int Main()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - bouncing ball");
Vector2 ballPosition = new(GetScreenWidth() / 2, GetScreenHeight() / 2);
Vector2 ballSpeed = new(5.0f, 4.0f);
int ballRadius = 20;
bool pause = false;
int framesCounter = 0;
SetTargetFPS(60);
//----------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//-----------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
pause = !pause;
}
if (!pause)
{
ballPosition.X += ballSpeed.X;
ballPosition.Y += ballSpeed.Y;
// Check walls collision for bouncing
if ((ballPosition.X >= (GetScreenWidth() - ballRadius)) || (ballPosition.X <= ballRadius))
{
ballSpeed.X *= -1.0f;
}
if ((ballPosition.Y >= (GetScreenHeight() - ballRadius)) || (ballPosition.Y <= ballRadius))
{
ballSpeed.Y *= -1.0f;
}
}
else
{
framesCounter += 1;
}
//-----------------------------------------------------
// Draw
//-----------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawCircleV(ballPosition, ballRadius, Color.MAROON);
DrawText("PRESS SPACE to PAUSE BALL MOVEMENT", 10, GetScreenHeight() - 25, 20, Color.LIGHTGRAY);
// On pause, we draw a blinking message
if (pause && ((framesCounter / 30) % 2) == 0)
{
DrawText("PAUSED", 350, 200, 30, Color.GRAY);
}
DrawFPS(10, 10);
EndDrawing();
//-----------------------------------------------------
}
// De-Initialization
//---------------------------------------------------------
CloseWindow();
//----------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,138 @@
/*******************************************************************************************
*
* raylib [shapes] example - collision area
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class CollisionArea
{
public static int Main()
{
// Initialization
//---------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - collision area");
// Box A: Moving box
Rectangle boxA = new(10, GetScreenHeight() / 2 - 50, 200, 100);
int boxASpeedX = 4;
// Box B: Mouse moved box
Rectangle boxB = new(GetScreenWidth() / 2 - 30, GetScreenHeight() / 2 - 30, 60, 60);
Rectangle boxCollision = new();
int screenUpperLimit = 40;
// Movement pause
bool pause = false;
bool collision = false;
SetTargetFPS(60);
//----------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//-----------------------------------------------------
// Move box if not paused
if (!pause)
{
boxA.X += boxASpeedX;
}
// Bounce box on x screen limits
if (((boxA.X + boxA.Width) >= GetScreenWidth()) || (boxA.X <= 0))
{
boxASpeedX *= -1;
}
// Update player-controlled-box (box02)
boxB.X = GetMouseX() - boxB.Width / 2;
boxB.Y = GetMouseY() - boxB.Height / 2;
// Make sure Box B does not go out of move area limits
if ((boxB.X + boxB.Width) >= GetScreenWidth())
{
boxB.X = GetScreenWidth() - boxB.Width;
}
else if (boxB.X <= 0)
{
boxB.X = 0;
}
if ((boxB.Y + boxB.Height) >= GetScreenHeight())
{
boxB.Y = GetScreenHeight() - boxB.Height;
}
else if (boxB.Y <= screenUpperLimit)
{
boxB.Y = screenUpperLimit;
}
// Check boxes collision
collision = CheckCollisionRecs(boxA, boxB);
// Get collision rectangle (only on collision)
if (collision)
{
boxCollision = GetCollisionRec(boxA, boxB);
}
// Pause Box A movement
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
pause = !pause;
}
//-----------------------------------------------------
// Draw
//-----------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectangle(0, 0, screenWidth, screenUpperLimit, collision ? Color.RED : Color.BLACK);
DrawRectangleRec(boxA, Color.GOLD);
DrawRectangleRec(boxB, Color.BLUE);
if (collision)
{
// Draw collision area
DrawRectangleRec(boxCollision, Color.LIME);
// Draw collision message
int cx = GetScreenWidth() / 2 - MeasureText("COLLISION!", 20) / 2;
int cy = screenUpperLimit / 2 - 10;
DrawText("COLLISION!", cx, cy, 20, Color.BLACK);
// Draw collision area
string text = $"Collision Area: {(int)boxCollision.Width * (int)boxCollision.Height}";
DrawText(text, GetScreenWidth() / 2 - 100, screenUpperLimit + 10, 20, Color.BLACK);
}
DrawFPS(10, 10);
EndDrawing();
//-----------------------------------------------------
}
// De-Initialization
//---------------------------------------------------------
CloseWindow();
//----------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,169 @@
/*******************************************************************************************
*
* raylib [shapes] example - Colors palette
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class ColorsPalette
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - colors palette");
Color[] colors = new[]
{
Color.DARKGRAY,
Color.MAROON,
Color.ORANGE,
Color.DARKGREEN,
Color.DARKBLUE,
Color.DARKPURPLE,
Color.DARKBROWN,
Color.GRAY,
Color.RED,
Color.GOLD,
Color.LIME,
Color.BLUE,
Color.VIOLET,
Color.BROWN,
Color.LIGHTGRAY,
Color.PINK,
Color.YELLOW,
Color.GREEN,
Color.SKYBLUE,
Color.PURPLE,
Color.BEIGE
};
string[] colorNames = new[]
{
"DARKGRAY",
"MAROON",
"ORANGE",
"DARKGREEN",
"DARKBLUE",
"DARKPURPLE",
"DARKBROWN",
"GRAY",
"RED",
"GOLD",
"LIME",
"BLUE",
"VIOLET",
"BROWN",
"LIGHTGRAY",
"PINK",
"YELLOW",
"GREEN",
"SKYBLUE",
"PURPLE",
"BEIGE"
};
// Rectangles array
Rectangle[] colorsRecs = new Rectangle[colors.Length];
// Fills colorsRecs data (for every rectangle)
for (int i = 0; i < colorsRecs.Length; i++)
{
colorsRecs[i].X = 20 + 100 * (i % 7) + 10 * (i % 7);
colorsRecs[i].Y = 80 + 100 * (i / 7) + 10 * (i / 7);
colorsRecs[i].Width = 100;
colorsRecs[i].Height = 100;
}
// Color state: 0-DEFAULT, 1-MOUSE_HOVER
int[] colorState = new int[colors.Length];
Vector2 mousePoint = new(0.0f, 0.0f);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
mousePoint = GetMousePosition();
for (int i = 0; i < colors.Length; i++)
{
if (CheckCollisionPointRec(mousePoint, colorsRecs[i]))
{
colorState[i] = 1;
}
else
{
colorState[i] = 0;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("raylib colors palette", 28, 42, 20, Color.BLACK);
DrawText(
"press SPACE to see all colors",
GetScreenWidth() - 180,
GetScreenHeight() - 40,
10,
Color.GRAY
);
// Draw all rectangles
for (int i = 0; i < colorsRecs.Length; i++)
{
DrawRectangleRec(colorsRecs[i], ColorAlpha(colors[i], colorState[i] != 0 ? 0.6f : 1.0f));
if (IsKeyDown(KeyboardKey.KEY_SPACE) || colorState[i] != 0)
{
DrawRectangle(
(int)colorsRecs[i].X,
(int)(colorsRecs[i].Y + colorsRecs[i].Height - 26),
(int)colorsRecs[i].Width,
20,
Color.BLACK
);
DrawRectangleLinesEx(colorsRecs[i], 6, ColorAlpha(Color.BLACK, 0.3f));
DrawText(
colorNames[i],
(int)(colorsRecs[i].X + colorsRecs[i].Width - MeasureText(colorNames[i], 10) - 12),
(int)(colorsRecs[i].Y + colorsRecs[i].Height - 20),
10,
colors[i]
);
}
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,95 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw circle sector (with gui options)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawCircleSector
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw circle sector");
Vector2 center = new((GetScreenWidth() - 300) / 2, GetScreenHeight() / 2);
float outerRadius = 180.0f;
int startAngle = 0;
int endAngle = 180;
int segments = 0;
int minSegments = 4;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// NOTE: All variables update happens inside GUI control functions
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawLine(500, 0, 500, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.3f));
DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, ColorAlpha(Color.MAROON, 0.3f));
DrawCircleSectorLines(
center,
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.MAROON, 0.6f)
);
// Draw GUI controls
//------------------------------------------------------------------------------
/*startAngle = GuiSliderBar(new Rectangle( 600, 40, 120, 20), "StartAngle", startAngle, 0, 720, true );
endAngle = GuiSliderBar(new Rectangle( 600, 70, 120, 20), "EndAngle", endAngle, 0, 720, true);
outerRadius = GuiSliderBar(new Rectangle( 600, 140, 120, 20), "Radius", outerRadius, 0, 200, true);
segments = GuiSliderBar(new Rectangle( 600, 170, 120, 20), "Segments", segments, 0, 100, true);*/
//------------------------------------------------------------------------------
minSegments = (int)MathF.Ceiling((endAngle - startAngle) / 90);
Color color = (segments >= minSegments) ? Color.MAROON : Color.DARKGRAY;
DrawText($"MODE: {((segments >= minSegments) ? "MANUAL" : "AUTO")}", 600, 270, 10, color);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,105 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw rectangle rounded (with gui options)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawRectangleRounded
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw rectangle rounded");
float roundness = 0.2f;
int width = 400;
int height = 200;
int segments = 0;
int lineThick = 10;
bool drawRect = false;
bool drawRoundedRect = false;
bool drawRoundedLines = true;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
Rectangle rec = new(
(GetScreenWidth() - width - 250) / 2.0f,
(GetScreenHeight() - height) / 2.0f,
(float)width,
(float)height
);
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawLine(560, 0, 560, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.6f));
DrawRectangle(560, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.3f));
if (drawRect)
{
DrawRectangleRec(rec, ColorAlpha(Color.GOLD, 0.6f));
}
if (drawRoundedRect)
{
DrawRectangleRounded(rec, roundness, segments, ColorAlpha(Color.MAROON, 0.2f));
}
if (drawRoundedLines)
{
DrawRectangleRoundedLines(rec, roundness, segments, (float)lineThick, ColorAlpha(Color.MAROON, 0.4f));
}
// Draw GUI controls
//------------------------------------------------------------------------------
/*width = GuiSliderBar(new Rectangle( 640, 40, 105, 20 ), "Width", width, 0, GetScreenWidth() - 300, true );
height = GuiSliderBar(new Rectangle( 640, 70, 105, 20 ), "Height", height, 0, GetScreenHeight() - 50, true);
roundness = GuiSliderBar(new Rectangle( 640, 140, 105, 20 ), "Roundness", roundness, 0.0f, 1.0f, true);
lineThick = GuiSliderBar(new Rectangle( 640, 170, 105, 20 ), "Thickness", lineThick, 0, 20, true);
segments = GuiSliderBar(new Rectangle( 640, 240, 105, 20), "Segments", segments, 0, 60, true);
drawRoundedRect = GuiCheckBox(new Rectangle( 640, 320, 20, 20 ), "DrawRoundedRect", drawRoundedRect);
drawRoundedLines = GuiCheckBox(new Rectangle( 640, 350, 20, 20 ), "DrawRoundedLines", drawRoundedLines);
drawRect = GuiCheckBox(new Rectangle( 640, 380, 20, 20), "DrawRect", drawRect);*/
//------------------------------------------------------------------------------
string text = $"MODE: {((segments >= 4) ? "MANUAL" : "AUTO")}";
DrawText(text, 640, 280, 10, (segments >= 4) ? Color.MAROON : Color.DARKGRAY);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

132
Examples/Shapes/DrawRing.cs Normal file
View File

@ -0,0 +1,132 @@
/*******************************************************************************************
*
* raylib [shapes] example - draw ring (with gui options)
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class DrawRing
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - draw ring");
Vector2 center = new((GetScreenWidth() - 300) / 2, GetScreenHeight() / 2);
float innerRadius = 80.0f;
float outerRadius = 190.0f;
int startAngle = 0;
int endAngle = 360;
int segments = 0;
int minSegments = 4;
bool drawRing = true;
bool drawRingLines = false;
bool drawCircleLines = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// NOTE: All variables update happens inside GUI control functions
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawLine(500, 0, 500, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), ColorAlpha(Color.LIGHTGRAY, 0.3f));
if (drawRing)
{
DrawRing(
center,
innerRadius,
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.MAROON, 0.3f)
);
}
if (drawRingLines)
{
DrawRingLines(
center,
innerRadius,
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.BLACK, 0.4f)
);
}
if (drawCircleLines)
{
DrawCircleSectorLines(
center,
outerRadius,
startAngle,
endAngle,
segments,
ColorAlpha(Color.BLACK, 0.4f)
);
}
// Draw GUI controls
//------------------------------------------------------------------------------
/*startAngle = GuiSliderBar(new Rectangle( 600, 40, 120, 20 ), "StartAngle", startAngle, -450, 450, true);
endAngle = GuiSliderBar(new Rectangle( 600, 70, 120, 20 ), "EndAngle", endAngle, -450, 450, true);
innerRadius = GuiSliderBar(new Rectangle( 600, 140, 120, 20 ), "InnerRadius", innerRadius, 0, 100, true);
outerRadius = GuiSliderBar(new Rectangle( 600, 170, 120, 20 ), "OuterRadius", outerRadius, 0, 200, true);
segments = GuiSliderBar(new Rectangle( 600, 240, 120, 20 ), "Segments", segments, 0, 100, true);
drawRing = GuiCheckBox(new Rectangle( 600, 320, 20, 20 ), "Draw Ring", drawRing);
drawRingLines = GuiCheckBox(new Rectangle( 600, 350, 20, 20 ), "Draw RingLines", drawRingLines);
drawCircleLines = GuiCheckBox(new Rectangle( 600, 380, 20, 20 ), "Draw CircleLines", drawCircleLines);*/
//------------------------------------------------------------------------------
minSegments = (int)MathF.Ceiling((endAngle - startAngle) / 90);
Color color = (segments >= minSegments) ? Color.MAROON : Color.DARKGRAY;
DrawText($"MODE: {((segments >= minSegments) ? "MANUAL" : "AUTO")}", 600, 270, 10, color);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,126 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings ball anim
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class EasingsBallAnim
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings ball anim");
// Ball variable value to be animated with easings
int ballPositionX = -100;
int ballRadius = 20;
float ballAlpha = 0.0f;
int state = 0;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (state == 0) // Move ball position X with easing
{
framesCounter += 1;
ballPositionX = (int)Easings.EaseElasticOut(framesCounter, -100, screenWidth / 2 + 100, 120);
if (framesCounter >= 120)
{
framesCounter = 0;
state = 1;
}
}
// Increase ball radius with easing
else if (state == 1)
{
framesCounter += 1;
ballRadius = (int)Easings.EaseElasticIn(framesCounter, 20, 500, 200);
if (framesCounter >= 200)
{
framesCounter = 0;
state = 2;
}
}
// Change ball alpha with easing (background color blending)
else if (state == 2)
{
framesCounter += 1;
ballAlpha = Easings.EaseCubicOut(framesCounter, 0.0f, 1.0f, 200);
if (framesCounter >= 200)
{
framesCounter = 0;
state = 3;
}
}
// Reset state to play again
else if (state == 3)
{
if (IsKeyPressed(KeyboardKey.KEY_ENTER))
{
// Reset required variables to play again
ballPositionX = -100;
ballRadius = 20;
ballAlpha = 0.0f;
state = 0;
}
}
if (IsKeyPressed(KeyboardKey.KEY_R))
{
framesCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (state >= 2)
{
DrawRectangle(0, 0, screenWidth, screenHeight, Color.GREEN);
}
DrawCircle(ballPositionX, 200, ballRadius, ColorAlpha(Color.RED, 1.0f - ballAlpha));
if (state == 3)
{
DrawText("PRESS [ENTER] TO PLAY AGAIN!", 240, 200, 20, Color.BLACK);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,144 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings box anim
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class EasingsBoxAnim
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings box anim");
// Box variables to be animated with easings
Rectangle rec = new(GetScreenWidth() / 2, -100, 100, 100);
float rotation = 0.0f;
float alpha = 1.0f;
int state = 0;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
switch (state)
{
// Move box down to center of screen
case 0:
framesCounter += 1;
// NOTE: Remember that 3rd parameter of easing function refers to
// desired value variation, do not confuse it with expected final value!
rec.Y = Easings.EaseElasticOut(framesCounter, -100, GetScreenHeight() / 2 + 100, 120);
if (framesCounter >= 120)
{
framesCounter = 0;
state = 1;
}
break;
// Scale box to an horizontal bar
case 1:
framesCounter += 1;
rec.Height = Easings.EaseBounceOut(framesCounter, 100, -90, 120);
rec.Width = Easings.EaseBounceOut(framesCounter, 100, GetScreenWidth(), 120);
if (framesCounter >= 120)
{
framesCounter = 0;
state = 2;
}
break;
// Rotate horizontal bar rectangle
case 2:
framesCounter += 1;
rotation = Easings.EaseQuadOut(framesCounter, 0.0f, 270.0f, 240);
if (framesCounter >= 240)
{
framesCounter = 0;
state = 3;
}
break;
// Increase bar size to fill all screen
case 3:
framesCounter += 1;
rec.Height = Easings.EaseCircOut(framesCounter, 10, GetScreenWidth(), 120);
if (framesCounter >= 120)
{
framesCounter = 0;
state = 4;
}
break;
// Fade out animation
case 4:
framesCounter++;
alpha = Easings.EaseSineOut(framesCounter, 1.0f, -1.0f, 160);
if (framesCounter >= 160)
{
framesCounter = 0;
state = 5;
}
break;
default:
break;
}
// Reset animation at any moment
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
rec = new Rectangle(GetScreenWidth() / 2, -100, 100, 100);
rotation = 0.0f;
alpha = 1.0f;
state = 0;
framesCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectanglePro(
rec,
new Vector2(rec.Width / 2, rec.Height / 2),
rotation,
ColorAlpha(Color.BLACK, alpha)
);
DrawText("PRESS [SPACE] TO RESET BOX ANIMATION!", 10, GetScreenHeight() - 25, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,140 @@
/*******************************************************************************************
*
* raylib [shapes] example - easings rectangle array
*
* NOTE: This example requires 'easings.h' library, provided on raylib/src. Just copy
* the library to same directory as example or make sure it's available on include path.
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class EasingsRectangleArray
{
public const int RecsWidth = 50;
public const int RecsHeight = 50;
public const int MaxRecsX = 800 / RecsWidth;
public const int MaxRecsY = 450 / RecsHeight;
// At 60 fps = 4 seconds
public const int PlayTimeInFrames = 240;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - easings rectangle array");
Rectangle[] recs = new Rectangle[MaxRecsX * MaxRecsY];
for (int y = 0; y < MaxRecsY; y++)
{
for (int x = 0; x < MaxRecsX; x++)
{
recs[y * MaxRecsX + x].X = RecsWidth / 2 + RecsWidth * x;
recs[y * MaxRecsX + x].Y = RecsHeight / 2 + RecsHeight * y;
recs[y * MaxRecsX + x].Width = RecsWidth;
recs[y * MaxRecsX + x].Height = RecsHeight;
}
}
float rotation = 0.0f;
int framesCounter = 0;
// Rectangles animation state: 0-Playing, 1-Finished
int state = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (state == 0)
{
framesCounter++;
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
{
recs[i].Height = Easings.EaseCircOut(framesCounter, RecsHeight, -RecsHeight, PlayTimeInFrames);
recs[i].Width = Easings.EaseCircOut(framesCounter, RecsWidth, -RecsWidth, PlayTimeInFrames);
if (recs[i].Height < 0)
{
recs[i].Height = 0;
}
if (recs[i].Width < 0)
{
recs[i].Width = 0;
}
// Finish playing
if ((recs[i].Height == 0) && (recs[i].Width == 0))
{
state = 1;
}
rotation = Easings.EaseLinearIn(framesCounter, 0.0f, 360.0f, PlayTimeInFrames);
}
}
else if ((state == 1) && IsKeyPressed(KeyboardKey.KEY_SPACE))
{
// When animation has finished, press space to restart
framesCounter = 0;
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
{
recs[i].Height = RecsHeight;
recs[i].Width = RecsWidth;
}
state = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (state == 0)
{
for (int i = 0; i < MaxRecsX * MaxRecsY; i++)
{
DrawRectanglePro(
recs[i],
new Vector2(recs[i].Width / 2, recs[i].Height / 2),
rotation,
Color.RED
);
}
}
else if (state == 1)
{
DrawText("PRESS [SPACE] TO PLAY AGAIN!", 240, 200, 20, Color.GRAY);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,108 @@
/*******************************************************************************************
*
* raylib [shapes] example - following eyes
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2013-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class FollowingEyes
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes");
Vector2 scleraLeftPosition = new(GetScreenWidth() / 2 - 100, GetScreenHeight() / 2);
Vector2 scleraRightPosition = new(GetScreenWidth() / 2 + 100, GetScreenHeight() / 2);
float scleraRadius = 80;
Vector2 irisLeftPosition = new(GetScreenWidth() / 2 - 100, GetScreenHeight() / 2);
Vector2 irisRightPosition = new(GetScreenWidth() / 2 + 100, GetScreenHeight() / 2);
float irisRadius = 24;
float angle = 0.0f;
float dx = 0.0f, dy = 0.0f, dxx = 0.0f, dyy = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
irisLeftPosition = GetMousePosition();
irisRightPosition = GetMousePosition();
// Check not inside the left eye sclera
if (!CheckCollisionPointCircle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20))
{
dx = irisLeftPosition.X - scleraLeftPosition.X;
dy = irisLeftPosition.Y - scleraLeftPosition.Y;
angle = MathF.Atan2(dy, dx);
dxx = (scleraRadius - irisRadius) * MathF.Cos(angle);
dyy = (scleraRadius - irisRadius) * MathF.Sin(angle);
irisLeftPosition.X = scleraLeftPosition.X + dxx;
irisLeftPosition.Y = scleraLeftPosition.Y + dyy;
}
// Check not inside the right eye sclera
if (!CheckCollisionPointCircle(irisRightPosition, scleraRightPosition, scleraRadius - 20))
{
dx = irisRightPosition.X - scleraRightPosition.X;
dy = irisRightPosition.Y - scleraRightPosition.Y;
angle = MathF.Atan2(dy, dx);
dxx = (scleraRadius - irisRadius) * MathF.Cos(angle);
dyy = (scleraRadius - irisRadius) * MathF.Sin(angle);
irisRightPosition.X = scleraRightPosition.X + dxx;
irisRightPosition.Y = scleraRightPosition.Y + dyy;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawCircleV(scleraLeftPosition, scleraRadius, Color.LIGHTGRAY);
DrawCircleV(irisLeftPosition, irisRadius, Color.BROWN);
DrawCircleV(irisLeftPosition, 10, Color.BLACK);
DrawCircleV(scleraRightPosition, scleraRadius, Color.LIGHTGRAY);
DrawCircleV(irisRightPosition, irisRadius, Color.DARKGREEN);
DrawCircleV(irisRightPosition, 10, Color.BLACK);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,69 @@
/*******************************************************************************************
*
* raylib [shapes] example - Cubic-bezier lines
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LinesBezier
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(ConfigFlags.FLAG_MSAA_4X_HINT);
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines");
Vector2 start = new(0, 0);
Vector2 end = new(screenWidth, screenHeight);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON))
{
start = GetMousePosition();
}
else if (IsMouseButtonDown(MouseButton.MOUSE_RIGHT_BUTTON))
{
end = GetMousePosition();
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("USE MOUSE LEFT-RIGHT CLICK to DEFINE LINE START and END POINTS", 15, 20, 20, Color.GRAY);
DrawLineBezier(start, end, 2.0f, Color.RED);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,193 @@
/*******************************************************************************************
*
* raylib [shapes] example - raylib logo animation
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LogoRaylibAnim
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo animation");
int logoPositionX = screenWidth / 2 - 128;
int logoPositionY = screenHeight / 2 - 128;
int framesCounter = 0;
int lettersCount = 0;
int topSideRecWidth = 16;
int leftSideRecHeight = 16;
int bottomSideRecWidth = 16;
int rightSideRecHeight = 16;
// Tracking animation states (State Machine)
int state = 0;
// Useful for fading
float alpha = 1.0f;
Color outline = new(139, 71, 135, 255);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// State 0: Small box blinking
if (state == 0)
{
framesCounter++;
// Reset counter... will be used later...
if (framesCounter == 120)
{
state = 1;
framesCounter = 0;
}
}
// State 1: Top and left bars growing
else if (state == 1)
{
topSideRecWidth += 4;
leftSideRecHeight += 4;
if (topSideRecWidth == 256)
{
state = 2;
}
}
// State 2: Bottom and right bars growing
else if (state == 2)
{
bottomSideRecWidth += 4;
rightSideRecHeight += 4;
if (bottomSideRecWidth == 256)
{
state = 3;
}
}
// State 3: Letters appearing (one by one)
else if (state == 3)
{
framesCounter++;
// Every 12 frames, one more letter!
if (framesCounter / 12 != 0)
{
lettersCount++;
framesCounter = 0;
}
// When all letters have appeared, just fade out everything
if (lettersCount >= 10)
{
alpha -= 0.02f;
if (alpha <= 0.0f)
{
alpha = 0.0f;
state = 4;
}
}
}
// State 4: Reset and Replay
else if (state == 4)
{
if (IsKeyPressed(KeyboardKey.KEY_R))
{
framesCounter = 0;
lettersCount = 0;
topSideRecWidth = 16;
leftSideRecHeight = 16;
bottomSideRecWidth = 16;
rightSideRecHeight = 16;
// Return to State 0
alpha = 1.0f;
state = 0;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (state == 0)
{
if ((framesCounter / 15) % 2 != 0)
{
DrawRectangle(logoPositionX, logoPositionY, 16, 16, outline);
}
}
else if (state == 1)
{
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, outline);
DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, outline);
}
else if (state == 2)
{
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, outline);
DrawRectangle(logoPositionX, logoPositionY, 16, leftSideRecHeight, outline);
DrawRectangle(logoPositionX + 240, logoPositionY, 16, rightSideRecHeight, outline);
DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, outline);
}
else if (state == 3)
{
Color outlineFade = ColorAlpha(outline, alpha);
DrawRectangle(logoPositionX, logoPositionY, topSideRecWidth, 16, outlineFade);
DrawRectangle(logoPositionX, logoPositionY + 16, 16, leftSideRecHeight - 32, outlineFade);
DrawRectangle(logoPositionX + 240, logoPositionY + 16, 16, rightSideRecHeight - 32, outlineFade);
DrawRectangle(logoPositionX, logoPositionY + 240, bottomSideRecWidth, 16, outlineFade);
Color whiteFade = ColorAlpha(Color.RAYWHITE, alpha);
DrawRectangle(screenWidth / 2 - 112, screenHeight / 2 - 112, 224, 224, whiteFade);
Color label = ColorAlpha(new Color(155, 79, 151, 255), alpha);
string text = "raylib".SubText(0, lettersCount);
DrawText(text, screenWidth / 2 - 44, screenHeight / 2 + 28, 50, label);
DrawText("cs".SubText(0, lettersCount), screenWidth / 2 - 44, screenHeight / 2 + 58, 50, label);
}
else if (state == 4)
{
DrawText("[R] REPLAY", 340, 200, 20, Color.GRAY);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,61 @@
/*******************************************************************************************
*
* raylib [shapes] example - Draw raylib logo using basic shapes
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class LogoRaylibShape
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - raylib logo using shapes");
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectangle(screenWidth / 2 - 128, screenHeight / 2 - 128, 256, 256, new Color(139, 71, 135, 255));
DrawRectangle(screenWidth / 2 - 112, screenHeight / 2 - 112, 224, 224, Color.RAYWHITE);
DrawText("raylib", screenWidth / 2 - 44, screenHeight / 2 + 28, 50, new Color(155, 79, 151, 255));
DrawText("cs", screenWidth / 2 - 44, screenHeight / 2 + 58, 50, new Color(155, 79, 151, 255));
DrawText("this is NOT a texture!", 350, 370, 10, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,122 @@
/*******************************************************************************************
*
* raylib [shapes] example - rectangle scaling by mouse
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Shapes;
public class RectangleScaling
{
public const int MOUSE_SCALE_MARK_SIZE = 12;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - rectangle scaling mouse");
Rectangle rec = new(100, 100, 200, 80);
Vector2 mousePosition = new(0, 0);
bool mouseScaleReady = false;
bool mouseScaleMode = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
mousePosition = GetMousePosition();
Rectangle area = new(
rec.X + rec.Width - MOUSE_SCALE_MARK_SIZE,
rec.Y + rec.Height - MOUSE_SCALE_MARK_SIZE,
MOUSE_SCALE_MARK_SIZE,
MOUSE_SCALE_MARK_SIZE
);
if (CheckCollisionPointRec(mousePosition, rec) &&
CheckCollisionPointRec(mousePosition, area))
{
mouseScaleReady = true;
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
mouseScaleMode = true;
}
}
else
{
mouseScaleReady = false;
}
if (mouseScaleMode)
{
mouseScaleReady = true;
rec.Width = (mousePosition.X - rec.X);
rec.Height = (mousePosition.Y - rec.Y);
if (rec.Width < MOUSE_SCALE_MARK_SIZE)
{
rec.Width = MOUSE_SCALE_MARK_SIZE;
}
if (rec.Height < MOUSE_SCALE_MARK_SIZE)
{
rec.Height = MOUSE_SCALE_MARK_SIZE;
}
if (IsMouseButtonReleased(MouseButton.MOUSE_LEFT_BUTTON))
{
mouseScaleMode = false;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Scale rectangle dragging from bottom-right corner!", 10, 10, 20, Color.GRAY);
DrawRectangleRec(rec, ColorAlpha(Color.GREEN, 0.5f));
if (mouseScaleReady)
{
DrawRectangleLinesEx(rec, 1, Color.RED);
DrawTriangle(
new Vector2(rec.X + rec.Width - MOUSE_SCALE_MARK_SIZE, rec.Y + rec.Height),
new Vector2(rec.X + rec.Width, rec.Y + rec.Height),
new Vector2(rec.X + rec.Width, rec.Y + rec.Height - MOUSE_SCALE_MARK_SIZE),
Color.RED
);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,132 @@
/*******************************************************************************************
*
* raylib [text] example - Codepoints loading
*
* Example originally created with raylib 4.2, last time updated with raylib 2.5
*
* Example licensed under an unmodified zlib/libpng license, which is an OSI-certified,
* BSD-like license that allows static linking with closed source software
*
* Copyright (c) 2022-2023 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using System.Linq;
using System.Globalization;
using System.Collections.Generic;
using static Raylib_cs.Raylib;
namespace Examples.Text;
class CodepointsLoading
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - codepoints loading");
// Text to be displayed, must be UTF-8 (save this code file as UTF-8)
// NOTE: It can contain all the required text for the game,
// this text will be scanned to get all the required codepoints
const string text =
"いろはにほへと ちりぬるを\nわかよたれそ つねならむ\nうゐのおくやま けふこえて\nあさきゆめみし ゑひもせす";
// Get codepoints from text
List<int> codepoints = GetCodePoints(text);
// Remove duplicate codepoints to generate smaller font atlas
int[] codepointsNoDuplicates = codepoints.Distinct().ToArray();
// Load font containing all the provided codepoint glyphs
// A texture font atlas is automatically generated
Font font = LoadFontEx(
"resources/DotGothic16-Regular.ttf",
36,
codepointsNoDuplicates,
codepointsNoDuplicates.Length
);
// Set bilinear scale filter for better font scaling
SetTextureFilter(font.Texture, TextureFilter.TEXTURE_FILTER_BILINEAR);
bool showFontAtlas = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
showFontAtlas = !showFontAtlas;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawRectangle(0, 0, GetScreenWidth(), 70, Color.BLACK);
DrawText($"Total codepoints contained in provided text: {codepoints.Count}", 10, 10, 20, Color.GREEN);
DrawText(
$"Total codepoints required for font atlas (duplicates excluded): {codepointsNoDuplicates.Length}",
10,
40,
20,
Color.GREEN
);
if (showFontAtlas)
{
// Draw generated font texture atlas containing provided codepoints
DrawTexture(font.Texture, 150, 100, Color.BLACK);
DrawRectangleLines(150, 100, font.Texture.Width, font.Texture.Height, Color.BLACK);
}
else
{
// Draw provided text with laoded font, containing all required codepoint glyphs
DrawTextEx(font, text, new Vector2(160, 110), 48, 5, Color.BLACK);
}
DrawText("Press SPACE to toggle font atlas view!", 10, GetScreenHeight() - 30, 20, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
private static List<int> GetCodePoints(string text)
{
List<int> codePoints = new();
StringInfo stringInfo = new(text);
TextElementEnumerator enumerator = StringInfo.GetTextElementEnumerator(text);
while (enumerator.MoveNext())
{
int codePoint = char.ConvertToUtf32(enumerator.Current.ToString(), 0);
codePoints.Add(codePoint);
}
return codePoints;
}
}

View File

@ -0,0 +1,146 @@
/*******************************************************************************************
*
* raylib [text] example - Font filters
*
* After font loading, font texture atlas filter could be configured for a softer
* display of the font when scaling it to different sizes, that way, it's not required
* to generate multiple fonts at multiple sizes (as long as the scaling is not very different)
*
* This example has been created using raylib 1.3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontFilters
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - font filters");
string msg = "Loaded Font";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
// TTF Font loading with custom generation parameters
Font font = LoadFontEx("resources/fonts/KAISG.ttf", 96, null, 0);
// Generate mipmap levels to use trilinear filtering
// NOTE: On 2D drawing it won't be noticeable, it looks like TEXTURE_FILTER_BILINEAR
GenTextureMipmaps(ref font.Texture);
float fontSize = font.BaseSize;
Vector2 fontPosition = new(40, screenHeight / 2 - 80);
Vector2 textSize = new(0.0f, 0.0f);
// Setup texture scaling filter
SetTextureFilter(font.Texture, TextureFilter.TEXTURE_FILTER_POINT);
TextureFilter currentFontFilter = TextureFilter.TEXTURE_FILTER_POINT;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
fontSize += GetMouseWheelMove() * 4.0f;
// Choose font texture filter method
if (IsKeyPressed(KeyboardKey.KEY_ONE))
{
SetTextureFilter(font.Texture, TextureFilter.TEXTURE_FILTER_POINT);
currentFontFilter = TextureFilter.TEXTURE_FILTER_POINT;
}
else if (IsKeyPressed(KeyboardKey.KEY_TWO))
{
SetTextureFilter(font.Texture, TextureFilter.TEXTURE_FILTER_BILINEAR);
currentFontFilter = TextureFilter.TEXTURE_FILTER_BILINEAR;
}
else if (IsKeyPressed(KeyboardKey.KEY_THREE))
{
// NOTE: Trilinear filter won't be noticed on 2D drawing
SetTextureFilter(font.Texture, TextureFilter.TEXTURE_FILTER_TRILINEAR);
currentFontFilter = TextureFilter.TEXTURE_FILTER_TRILINEAR;
}
textSize = MeasureTextEx(font, msg, fontSize, 0);
if (IsKeyDown(KeyboardKey.KEY_LEFT))
{
fontPosition.X -= 10;
}
else if (IsKeyDown(KeyboardKey.KEY_RIGHT))
{
fontPosition.X += 10;
}
// Load a dropped TTF file dynamically (at current fontSize)
if (IsFileDropped())
{
string[] files = Raylib.GetDroppedFiles();
// NOTE: We only support first ttf file dropped
if (IsFileExtension(files[0], ".ttf"))
{
UnloadFont(font);
font = LoadFontEx(files[0], (int)fontSize, null, 0);
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Use mouse wheel to change font size", 20, 20, 10, Color.GRAY);
DrawText("Use KEY_RIGHT and KEY_LEFT to move text", 20, 40, 10, Color.GRAY);
DrawText("Use 1, 2, 3 to change texture filter", 20, 60, 10, Color.GRAY);
DrawText("Drop a new TTF font for dynamic loading", 20, 80, 10, Color.DARKGRAY);
DrawTextEx(font, msg, fontPosition, fontSize, 0, Color.BLACK);
DrawRectangle(0, screenHeight - 80, screenWidth, 80, Color.LIGHTGRAY);
DrawText("CURRENT TEXTURE FILTER:", 250, 400, 20, Color.GRAY);
if (currentFontFilter == TextureFilter.TEXTURE_FILTER_POINT)
{
DrawText("POINT", 570, 400, 20, Color.BLACK);
}
else if (currentFontFilter == TextureFilter.TEXTURE_FILTER_POINT)
{
DrawText("BILINEAR", 570, 400, 20, Color.BLACK);
}
else if (currentFontFilter == TextureFilter.TEXTURE_FILTER_TRILINEAR)
{
DrawText("TRILINEAR", 570, 400, 20, Color.BLACK);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,102 @@
/*******************************************************************************************
*
* raylib [text] example - Font loading
*
* raylib can load fonts from multiple file formats:
*
* - TTF/OTF > Sprite font atlas is generated on loading, user can configure
* some of the generation parameters (size, characters to include)
* - BMFonts > Angel code font fileformat, sprite font image must be provided
* together with the .fnt file, font generation cna not be configured
* - XNA Spritefont > Sprite font image, following XNA Spritefont conventions,
* Characters in image must follow some spacing and order rules
*
* This example has been created using raylib 2.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontLoading
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - font loading");
// Define characters to draw
// NOTE: raylib supports UTF-8 encoding, following list is actually codified as UTF8 internally
string msg = "!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHI\nJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmn\nopqrstuvwxyz{|}~¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓ\nÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷\nøùúûüýþÿ";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
// BMFont (AngelCode) : Font data and image atlas have been generated using external program
Font fontBm = LoadFont("resources/fonts/pixantiqua.fnt");
// TTF font : Font data and atlas are generated directly from TTF
// NOTE: We define a font base size of 32 pixels tall and up-to 250 characters
Font fontTtf = LoadFontEx("resources/fonts/pixantiqua.ttf", 32, null, 250);
bool useTtf = false;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyDown(KeyboardKey.KEY_SPACE))
{
useTtf = true;
}
else
{
useTtf = false;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("Hold SPACE to use TTF generated font", 20, 20, 20, Color.LIGHTGRAY);
if (!useTtf)
{
DrawTextEx(fontBm, msg, new Vector2(20.0f, 100.0f), fontBm.BaseSize, 2, Color.MAROON);
DrawText("Using BMFont (Angelcode) imported", 20, GetScreenHeight() - 30, 20, Color.GRAY);
}
else
{
DrawTextEx(fontTtf, msg, new Vector2(20.0f, 100.0f), fontTtf.BaseSize, 2, Color.LIME);
DrawText("Using TTF font generated", 20, GetScreenHeight() - 30, 20, Color.GRAY);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(fontBm);
UnloadFont(fontTtf);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

162
Examples/Text/FontSdf.cs Normal file
View File

@ -0,0 +1,162 @@
/*******************************************************************************************
*
* raylib [text] example - TTF loading and usage
*
* This example has been created using raylib 1.3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2015 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System;
using System.Numerics;
using System.Runtime.InteropServices;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontSdf
{
public unsafe static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - SDF fonts");
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
string msg = "Signed Distance Fields";
// Loading file to memory
uint fileSize = 0;
byte* fileData = LoadFileData("resources/fonts/anonymous_pro_bold.ttf", ref fileSize);
// Default font generation from TTF font
Font fontDefault = new();
fontDefault.BaseSize = 16;
fontDefault.GlyphCount = 95;
// Loading font data from memory data
// Parameters > font size: 16, no chars array provided (0), chars count: 95 (autogenerate chars array)
fontDefault.Glyphs = LoadFontData(fileData, (int)fileSize, 16, null, 95, FontType.FONT_DEFAULT);
// Parameters > chars count: 95, font size: 16, chars padding in image: 4 px, pack method: 0 (default)
Image atlas = GenImageFontAtlas(fontDefault.Glyphs, &fontDefault.Recs, 95, 16, 4, 0);
fontDefault.Texture = LoadTextureFromImage(atlas);
UnloadImage(atlas);
// SDF font generation from TTF font
Font fontSDF = new();
fontSDF.BaseSize = 16;
fontSDF.GlyphCount = 95;
// Parameters > font size: 16, no chars array provided (0), chars count: 0 (defaults to 95)
fontSDF.Glyphs = LoadFontData(fileData, (int)fileSize, 16, null, 0, FontType.FONT_SDF);
// Parameters > chars count: 95, font size: 16, chars padding in image: 0 px, pack method: 1 (Skyline algorythm)
atlas = GenImageFontAtlas(fontSDF.Glyphs, &fontSDF.Recs, 95, 16, 0, 1);
fontSDF.Texture = LoadTextureFromImage(atlas);
UnloadImage(atlas);
// Free memory from loaded file
UnloadFileData(fileData);
// Load SDF required shader (we use default vertex shader)
Shader shader = LoadShader(null, "resources/shaders/glsl330/sdf.fs");
// Required for SDF font
SetTextureFilter(fontSDF.Texture, TextureFilter.TEXTURE_FILTER_BILINEAR);
Vector2 fontPosition = new(40, screenHeight / 2 - 50);
Vector2 textSize = new(0.0f);
float fontSize = 16.0f;
// 0 - fontDefault, 1 - fontSDF
int currentFont = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
fontSize += GetMouseWheelMove() * 8.0f;
if (fontSize < 6)
{
fontSize = 6;
}
if (IsKeyDown(KeyboardKey.KEY_SPACE))
{
currentFont = 1;
}
else
{
currentFont = 0;
}
if (currentFont == 0)
{
textSize = MeasureTextEx(fontDefault, msg, fontSize, 0);
}
else
{
textSize = MeasureTextEx(fontSDF, msg, fontSize, 0);
}
fontPosition.X = GetScreenWidth() / 2 - textSize.X / 2;
fontPosition.Y = GetScreenHeight() / 2 - textSize.Y / 2 + 80;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
if (currentFont == 1)
{
// NOTE: SDF fonts require a custom SDf shader to compute fragment color
BeginShaderMode(shader);
DrawTextEx(fontSDF, msg, fontPosition, fontSize, 0, Color.BLACK);
EndShaderMode();
DrawTexture(fontSDF.Texture, 10, 10, Color.BLACK);
}
else
{
DrawTextEx(fontDefault, msg, fontPosition, fontSize, 0, Color.BLACK);
DrawTexture(fontDefault.Texture, 10, 10, Color.BLACK);
}
if (currentFont == 1)
{
DrawText("SDF!", 320, 20, 80, Color.RED);
}
else
{
DrawText("default font", 315, 40, 30, Color.GRAY);
}
DrawText("FONT SIZE: 16.0", GetScreenWidth() - 240, 20, 20, Color.DARKGRAY);
DrawText($"RENDER SIZE: {fontSize:2F}", GetScreenWidth() - 240, 50, 20, Color.DARKGRAY);
DrawText("Use MOUSE WHEEL to SCALE TEXT!", GetScreenWidth() - 240, 90, 10, Color.DARKGRAY);
DrawText("PRESS SPACE to USE SDF FONT VERSION!", 340, GetScreenHeight() - 30, 20, Color.MAROON);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(fontDefault);
UnloadFont(fontSDF);
UnloadShader(shader);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,96 @@
/*******************************************************************************************
*
* raylib [text] example - Sprite font loading
*
* Loaded sprite fonts have been generated following XNA SpriteFont conventions:
* - Characters must be ordered starting with character 32 (Space)
* - Every character must be contained within the same Rectangle height
* - Every character and every line must be separated the same distance
* - Rectangles must be defined by a magenta color background
*
* If following this constraints, a font can be provided just by an image,
* this is quite handy to avoid additional information files (like BMFonts use).
*
* This example has been created using raylib 1.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FontSpritefont
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - sprite font loading");
string msg1 = "THIS IS A custom SPRITE FONT...";
string msg2 = "...and this is ANOTHER CUSTOM font...";
string msg3 = "...and a THIRD one! GREAT! :D";
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
Font font1 = LoadFont("resources/fonts/custom_mecha.png");
Font font2 = LoadFont("resources/fonts/custom_alagard.png");
Font font3 = LoadFont("resources/fonts/custom_jupiter_crash.png");
Vector2 fontPosition1 = new(
screenWidth / 2 - MeasureTextEx(font1, msg1, font1.BaseSize, -3).X / 2,
screenHeight / 2 - font1.BaseSize / 2 - 80
);
Vector2 fontPosition2 = new(
screenWidth / 2 - MeasureTextEx(font2, msg2, font2.BaseSize, -2).X / 2,
screenHeight / 2 - font2.BaseSize / 2 - 10
);
Vector2 fontPosition3 = new(
screenWidth / 2 - MeasureTextEx(font3, msg3, font3.BaseSize, 2).X / 2,
screenHeight / 2 - font3.BaseSize / 2 + 50
);
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update variables here...
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawTextEx(font1, msg1, fontPosition1, font1.BaseSize, -3, Color.WHITE);
DrawTextEx(font2, msg2, fontPosition2, font2.BaseSize, -2, Color.WHITE);
DrawTextEx(font3, msg3, fontPosition3, font3.BaseSize, 2, Color.WHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(font1);
UnloadFont(font2);
UnloadFont(font3);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,63 @@
/*******************************************************************************************
*
* raylib [text] example - Text formatting
*
* This example has been created using raylib 1.1 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class FormatText
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - text formatting");
int score = 100020;
int hiscore = 200450;
int lives = 5;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText($"Score: {score}", 200, 80, 20, Color.RED);
DrawText($"HiScore: {hiscore}", 200, 120, 20, Color.GREEN);
DrawText($"Lives: {lives}", 200, 160, 40, Color.BLUE);
DrawText($"Elapsed Time: {GetFrameTime() * 1000} ms", 200, 220, 20, Color.BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

166
Examples/Text/InputBox.cs Normal file
View File

@ -0,0 +1,166 @@
/*******************************************************************************************
*
* raylib [text] example - Input Box
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class InputBox
{
public const int MaxInputChars = 9;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - input box");
// NOTE: One extra space required for line ending char '\0'
char[] name = new char[MaxInputChars];
int letterCount = 0;
Rectangle textBox = new(screenWidth / 2 - 100, 180, 225, 50);
bool mouseOnText = false;
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (CheckCollisionPointRec(GetMousePosition(), textBox))
{
mouseOnText = true;
}
else
{
mouseOnText = false;
}
if (mouseOnText)
{
// Set the window's cursor to the I-Beam
SetMouseCursor(MouseCursor.MOUSE_CURSOR_IBEAM);
// Check if more characters have been pressed on the same frame
int key = GetCharPressed();
while (key > 0)
{
// NOTE: Only allow keys in range [32..125]
if ((key >= 32) && (key <= 125) && (letterCount < MaxInputChars))
{
name[letterCount] = (char)key;
letterCount++;
}
// Check next character in the queue
key = GetCharPressed();
}
if (IsKeyPressed(KeyboardKey.KEY_BACKSPACE))
{
letterCount -= 1;
if (letterCount < 0)
{
letterCount = 0;
}
name[letterCount] = '\0';
}
}
else
{
SetMouseCursor(MouseCursor.MOUSE_CURSOR_DEFAULT);
}
if (mouseOnText)
{
framesCounter += 1;
}
else
{
framesCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("PLACE MOUSE OVER INPUT BOX!", 240, 140, 20, Color.GRAY);
DrawRectangleRec(textBox, Color.LIGHTGRAY);
if (mouseOnText)
{
DrawRectangleLines(
(int)textBox.X,
(int)textBox.Y,
(int)textBox.Width,
(int)textBox.Height,
Color.RED
);
}
else
{
DrawRectangleLines(
(int)textBox.X,
(int)textBox.Y,
(int)textBox.Width,
(int)textBox.Height,
Color.DARKGRAY
);
}
DrawText(new string(name), (int)textBox.X + 5, (int)textBox.Y + 8, 40, Color.MAROON);
DrawText($"INPUT CHARS: {letterCount}/{MaxInputChars}", 315, 250, 20, Color.DARKGRAY);
if (mouseOnText)
{
if (letterCount < MaxInputChars)
{
// Draw blinking underscore char
if ((framesCounter / 20 % 2) == 0)
{
DrawText(
"_",
(int)textBox.X + 8 + MeasureText(new string(name), 40),
(int)textBox.Y + 12,
40,
Color.MAROON
);
}
}
else
{
DrawText("Press BACKSPACE to delete chars...", 230, 300, 20, Color.GRAY);
}
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,121 @@
/*******************************************************************************************
*
* raylib [text] example - raylib font loading and usage
*
* NOTE: raylib is distributed with some free to use fonts (even for commercial pourposes!)
* To view details and credits for those fonts, check raylib license file
*
* This example has been created using raylib 1.7 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2017 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class RaylibFonts
{
public const int MaxFonts = 8;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - raylib fonts");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Font[] fonts = new Font[MaxFonts];
fonts[0] = LoadFont("resources/fonts/alagard.png");
fonts[1] = LoadFont("resources/fonts/pixelplay.png");
fonts[2] = LoadFont("resources/fonts/mecha.png");
fonts[3] = LoadFont("resources/fonts/setback.png");
fonts[4] = LoadFont("resources/fonts/romulus.png");
fonts[5] = LoadFont("resources/fonts/pixantiqua.png");
fonts[6] = LoadFont("resources/fonts/alpha_beta.png");
fonts[7] = LoadFont("resources/fonts/jupiter_crash.png");
string[] messages = new string[MaxFonts] {
"ALAGARD FONT designed by Hewett Tsoi",
"PIXELPLAY FONT designed by Aleksander Shevchuk",
"MECHA FONT designed by Captain Falcon",
"SETBACK FONT designed by Brian Kent (AEnigma)",
"ROMULUS FONT designed by Hewett Tsoi",
"PIXANTIQUA FONT designed by Gerhard Grossmann",
"ALPHA_BETA FONT designed by Brian Kent (AEnigma)",
"JUPITER_CRASH FONT designed by Brian Kent (AEnigma)"
};
int[] spacings = new int[MaxFonts] { 2, 4, 8, 4, 3, 4, 4, 1 };
Vector2[] positions = new Vector2[MaxFonts];
for (int i = 0; i < MaxFonts; i++)
{
float halfWidth = MeasureTextEx(fonts[i], messages[i], fonts[i].BaseSize * 2, spacings[i]).X / 2;
positions[i].X = screenWidth / 2 - halfWidth;
positions[i].Y = 60 + fonts[i].BaseSize + 45 * i;
}
// Small Y position corrections
positions[3].Y += 8;
positions[4].Y += 2;
positions[7].Y -= 8;
Color[] colors = new Color[MaxFonts] {
Color.MAROON,
Color.ORANGE,
Color.DARKGREEN,
Color.DARKBLUE,
Color.DARKPURPLE,
Color.LIME,
Color.GOLD,
Color.RED
};
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
// TODO: Update your variables here
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText("free fonts included with raylib", 250, 20, 20, Color.DARKGRAY);
DrawLine(220, 50, 590, 50, Color.DARKGRAY);
for (int i = 0; i < MaxFonts; i++)
{
DrawTextEx(fonts[i], messages[i], positions[i], fonts[i].BaseSize * 2, spacings[i], colors[i]);
}
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
for (int i = 0; i < MaxFonts; i++)
{
UnloadFont(fonts[i]);
}
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,357 @@
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class RectangleBounds
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - draw text inside a rectangle");
string text = "";
text += "Text cannot escape this container ...word wrap also works when active so here's a long text for testing.";
text += "\n\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor ";
text += "incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet risus nullam eget felis eget.";
bool resizing = false;
bool wordWrap = true;
Rectangle container = new(25, 25, screenWidth - 50, screenHeight - 250);
Rectangle resizer = new(
container.X + container.Width - 17,
container.Y + container.Height - 17,
14,
14
);
// Minimum width and heigh for the container rectangle
const int minWidth = 60;
const int minHeight = 60;
const int maxWidth = screenWidth - 50;
const int maxHeight = screenHeight - 160;
Vector2 lastMouse = new(0.0f, 0.0f);
Color borderColor = Color.MAROON;
Font font = GetFontDefault();
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
wordWrap = !wordWrap;
}
Vector2 mouse = GetMousePosition();
// Check if the mouse is inside the container and toggle border color
if (CheckCollisionPointRec(mouse, container))
{
borderColor = ColorAlpha(Color.MAROON, 0.4f);
}
else if (!resizing)
{
borderColor = Color.MAROON;
}
// Container resizing logic
if (resizing)
{
if (IsMouseButtonReleased(MouseButton.MOUSE_LEFT_BUTTON))
{
resizing = false;
}
int width = (int)(container.Width + (mouse.X - lastMouse.X));
container.Width = (width > minWidth) ? ((width < maxWidth) ? width : maxWidth) : minWidth;
int height = (int)(container.Height + (mouse.Y - lastMouse.Y));
container.Height = (height > minHeight) ? ((height < maxHeight) ? height : maxHeight) : minHeight;
}
else
{
// Check if we're resizing
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer))
{
resizing = true;
}
}
// Move resizer rectangle properly
resizer.X = container.X + container.Width - 17;
resizer.Y = container.Y + container.Height - 17;
lastMouse = mouse; // Update mouse
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Draw container border
DrawRectangleLinesEx(container, 3, borderColor);
// Draw text in container (add some padding)
DrawTextBoxed(
font,
text,
new Rectangle(container.X + 4, container.Y + 4, container.Width - 4, container.Height - 4),
20.0f,
2.0f,
wordWrap,
Color.GRAY
);
DrawRectangleRec(resizer, borderColor);
// Draw bottom info
DrawRectangle(0, screenHeight - 54, screenWidth, 54, Color.GRAY);
DrawRectangleRec(new Rectangle(382, screenHeight - 34, 12, 12), Color.MAROON);
DrawText("Word Wrap: ", 313, screenHeight - 115, 20, Color.BLACK);
if (wordWrap)
{
DrawText("ON", 447, screenHeight - 115, 20, Color.RED);
}
else
{
DrawText("OFF", 447, screenHeight - 115, 20, Color.BLACK);
}
DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 86, 20, Color.GRAY);
DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, Color.RAYWHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Draw text using font inside rectangle limits
static void DrawTextBoxed(
Font font,
string text,
Rectangle rec,
float fontSize,
float spacing,
bool wordWrap,
Color tint
)
{
DrawTextBoxedSelectable(font, text, rec, fontSize, spacing, wordWrap, tint, 0, 0, Color.WHITE, Color.WHITE);
}
// Draw text using font inside rectangle limits with support for text selection
static unsafe void DrawTextBoxedSelectable(
Font font,
string text,
Rectangle rec,
float fontSize,
float spacing,
bool wordWrap,
Color tint,
int selectStart,
int selectLength,
Color selectTint,
Color selectBackTint
)
{
int length = text.Length;
// Offset between lines (on line break '\n')
float textOffsetY = 0;
// Offset X to next character to draw
float textOffsetX = 0.0f;
// Character rectangle scaling factor
float scaleFactor = fontSize / (float)font.BaseSize;
// Word/character wrapping mechanism variables
bool shouldMeasure = wordWrap;
// Index where to begin drawing (where a line begins)
int startLine = -1;
// Index where to stop drawing (where a line ends)
int endLine = -1;
// Holds last value of the character position
int lastk = -1;
using var textNative = new Utf8Buffer(text);
for (int i = 0, k = 0; i < length; i++, k++)
{
// Get next codepoint from byte string and glyph index in font
int codepointByteCount = 0;
int codepoint = GetCodepoint(&textNative.AsPointer()[i], &codepointByteCount);
int index = GetGlyphIndex(font, codepoint);
// NOTE: Normally we exit the decoding sequence as soon as a bad byte is found (and return 0x3f)
// but we need to draw all of the bad bytes using the '?' symbol moving one byte
if (codepoint == 0x3f)
{
codepointByteCount = 1;
}
i += (codepointByteCount - 1);
float glyphWidth = 0;
if (codepoint != '\n')
{
glyphWidth = (font.Glyphs[index].AdvanceX == 0) ?
font.Recs[index].Width * scaleFactor :
font.Glyphs[index].AdvanceX * scaleFactor;
if (i + 1 < length)
{
glyphWidth = glyphWidth + spacing;
}
}
// NOTE: When wordWrap is ON we first measure how much of the text we can draw before going outside of
// the rec container. We store this info in startLine and endLine, then we change states, draw the text
// between those two variables and change states again and again recursively until the end of the text
// (or until we get outside of the container). When wordWrap is OFF we don't need the measure state so
// we go to the drawing state immediately and begin drawing on the next line before we can get outside
// the container.
if (shouldMeasure)
{
// TODO: There are multiple types of spaces in UNICODE, maybe it's a good idea to add support for
// more. Ref: http://jkorpela.fi/chars/spaces.html
if ((codepoint == ' ') || (codepoint == '\t') || (codepoint == '\n'))
{
endLine = i;
}
if ((textOffsetX + glyphWidth) > rec.Width)
{
endLine = (endLine < 1) ? i : endLine;
if (i == endLine)
{
endLine -= codepointByteCount;
}
if ((startLine + codepointByteCount) == endLine)
{
endLine = (i - codepointByteCount);
}
shouldMeasure = !shouldMeasure;
}
else if ((i + 1) == length)
{
endLine = i;
shouldMeasure = !shouldMeasure;
}
else if (codepoint == '\n')
{
shouldMeasure = !shouldMeasure;
}
if (!shouldMeasure)
{
textOffsetX = 0;
i = startLine;
glyphWidth = 0;
// Save character position when we switch states
int tmp = lastk;
lastk = k - 1;
k = tmp;
}
}
else
{
if (codepoint == '\n')
{
if (!wordWrap)
{
textOffsetY += (font.BaseSize + font.BaseSize / 2) * scaleFactor;
textOffsetX = 0;
}
}
else
{
if (!wordWrap && ((textOffsetX + glyphWidth) > rec.Width))
{
textOffsetY += (font.BaseSize + font.BaseSize / 2) * scaleFactor;
textOffsetX = 0;
}
// When text overflows rectangle height limit, just stop drawing
if ((textOffsetY + font.BaseSize * scaleFactor) > rec.Height)
{
break;
}
// Draw selection background
bool isGlyphSelected = false;
if ((selectStart >= 0) && (k >= selectStart) && (k < (selectStart + selectLength)))
{
DrawRectangleRec(
new Rectangle(
rec.X + textOffsetX - 1,
rec.Y + textOffsetY,
glyphWidth,
(float)font.BaseSize * scaleFactor
),
selectBackTint
);
isGlyphSelected = true;
}
// Draw current character glyph
if ((codepoint != ' ') && (codepoint != '\t'))
{
DrawTextCodepoint(
font,
codepoint,
new Vector2(rec.X + textOffsetX, rec.Y + textOffsetY),
fontSize,
isGlyphSelected ? selectTint : tint
);
}
}
if (wordWrap && (i == endLine))
{
textOffsetY += (font.BaseSize + font.BaseSize / 2) * scaleFactor;
textOffsetX = 0;
startLine = endLine;
endLine = -1;
glyphWidth = 0;
selectStart += lastk - k;
k = lastk;
shouldMeasure = !shouldMeasure;
}
}
if ((textOffsetX != 0) || (codepoint != ' '))
{
// avoid leading spaces
textOffsetX += glyphWidth;
}
}
}
}

330
Examples/Text/Unicode.cs Normal file
View File

@ -0,0 +1,330 @@
/*******************************************************************************************
*
* raylib [text] example - Using unicode with raylib
*
* This example has been created using raylib 2.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2019 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using Raylib_cs;
using static Raylib_cs.Raylib;
using static Raylib_cs.Color;
namespace Examples.Text
{
public class Unicode
{
const int EMOJI_PER_WIDTH = 8;
const int EMOJI_PER_HEIGHT = 4;
// String containing 180 emoji codepoints separated by a '\0' char
string emojiCodepoints = @"\xF0\x9F\x8C\x80\x00\xF0\x9F\x98\x80\x00\xF0\x9F\x98\x82\x00\xF0\x9F\xA4\xA3\x00\xF0\x9F\x98\x83\x00\xF0\x9F\x98\x86\x00\xF0\x9F\x98\x89\x00"
"\xF0\x9F\x98\x8B\x00\xF0\x9F\x98\x8E\x00\xF0\x9F\x98\x8D\x00\xF0\x9F\x98\x98\x00\xF0\x9F\x98\x97\x00\xF0\x9F\x98\x99\x00\xF0\x9F\x98\x9A\x00\xF0\x9F\x99\x82\x00"
"\xF0\x9F\xA4\x97\x00\xF0\x9F\xA4\xA9\x00\xF0\x9F\xA4\x94\x00\xF0\x9F\xA4\xA8\x00\xF0\x9F\x98\x90\x00\xF0\x9F\x98\x91\x00\xF0\x9F\x98\xB6\x00\xF0\x9F\x99\x84\x00"
"\xF0\x9F\x98\x8F\x00\xF0\x9F\x98\xA3\x00\xF0\x9F\x98\xA5\x00\xF0\x9F\x98\xAE\x00\xF0\x9F\xA4\x90\x00\xF0\x9F\x98\xAF\x00\xF0\x9F\x98\xAA\x00\xF0\x9F\x98\xAB\x00"
"\xF0\x9F\x98\xB4\x00\xF0\x9F\x98\x8C\x00\xF0\x9F\x98\x9B\x00\xF0\x9F\x98\x9D\x00\xF0\x9F\xA4\xA4\x00\xF0\x9F\x98\x92\x00\xF0\x9F\x98\x95\x00\xF0\x9F\x99\x83\x00"
"\xF0\x9F\xA4\x91\x00\xF0\x9F\x98\xB2\x00\xF0\x9F\x99\x81\x00\xF0\x9F\x98\x96\x00\xF0\x9F\x98\x9E\x00\xF0\x9F\x98\x9F\x00\xF0\x9F\x98\xA4\x00\xF0\x9F\x98\xA2\x00"
"\xF0\x9F\x98\xAD\x00\xF0\x9F\x98\xA6\x00\xF0\x9F\x98\xA9\x00\xF0\x9F\xA4\xAF\x00\xF0\x9F\x98\xAC\x00\xF0\x9F\x98\xB0\x00\xF0\x9F\x98\xB1\x00\xF0\x9F\x98\xB3\x00"
"\xF0\x9F\xA4\xAA\x00\xF0\x9F\x98\xB5\x00\xF0\x9F\x98\xA1\x00\xF0\x9F\x98\xA0\x00\xF0\x9F\xA4\xAC\x00\xF0\x9F\x98\xB7\x00\xF0\x9F\xA4\x92\x00\xF0\x9F\xA4\x95\x00"
"\xF0\x9F\xA4\xA2\x00\xF0\x9F\xA4\xAE\x00\xF0\x9F\xA4\xA7\x00\xF0\x9F\x98\x87\x00\xF0\x9F\xA4\xA0\x00\xF0\x9F\xA4\xAB\x00\xF0\x9F\xA4\xAD\x00\xF0\x9F\xA7\x90\x00"
"\xF0\x9F\xA4\x93\x00\xF0\x9F\x98\x88\x00\xF0\x9F\x91\xBF\x00\xF0\x9F\x91\xB9\x00\xF0\x9F\x91\xBA\x00\xF0\x9F\x92\x80\x00\xF0\x9F\x91\xBB\x00\xF0\x9F\x91\xBD\x00"
"\xF0\x9F\x91\xBE\x00\xF0\x9F\xA4\x96\x00\xF0\x9F\x92\xA9\x00\xF0\x9F\x98\xBA\x00\xF0\x9F\x98\xB8\x00\xF0\x9F\x98\xB9\x00\xF0\x9F\x98\xBB\x00\xF0\x9F\x98\xBD\x00"
"\xF0\x9F\x99\x80\x00\xF0\x9F\x98\xBF\x00\xF0\x9F\x8C\xBE\x00\xF0\x9F\x8C\xBF\x00\xF0\x9F\x8D\x80\x00\xF0\x9F\x8D\x83\x00\xF0\x9F\x8D\x87\x00\xF0\x9F\x8D\x93\x00"
"\xF0\x9F\xA5\x9D\x00\xF0\x9F\x8D\x85\x00\xF0\x9F\xA5\xA5\x00\xF0\x9F\xA5\x91\x00\xF0\x9F\x8D\x86\x00\xF0\x9F\xA5\x94\x00\xF0\x9F\xA5\x95\x00\xF0\x9F\x8C\xBD\x00"
"\xF0\x9F\x8C\xB6\x00\xF0\x9F\xA5\x92\x00\xF0\x9F\xA5\xA6\x00\xF0\x9F\x8D\x84\x00\xF0\x9F\xA5\x9C\x00\xF0\x9F\x8C\xB0\x00\xF0\x9F\x8D\x9E\x00\xF0\x9F\xA5\x90\x00"
"\xF0\x9F\xA5\x96\x00\xF0\x9F\xA5\xA8\x00\xF0\x9F\xA5\x9E\x00\xF0\x9F\xA7\x80\x00\xF0\x9F\x8D\x96\x00\xF0\x9F\x8D\x97\x00\xF0\x9F\xA5\xA9\x00\xF0\x9F\xA5\x93\x00"
"\xF0\x9F\x8D\x94\x00\xF0\x9F\x8D\x9F\x00\xF0\x9F\x8D\x95\x00\xF0\x9F\x8C\xAD\x00\xF0\x9F\xA5\xAA\x00\xF0\x9F\x8C\xAE\x00\xF0\x9F\x8C\xAF\x00\xF0\x9F\xA5\x99\x00"
"\xF0\x9F\xA5\x9A\x00\xF0\x9F\x8D\xB3\x00\xF0\x9F\xA5\x98\x00\xF0\x9F\x8D\xB2\x00\xF0\x9F\xA5\xA3\x00\xF0\x9F\xA5\x97\x00\xF0\x9F\x8D\xBF\x00\xF0\x9F\xA5\xAB\x00"
"\xF0\x9F\x8D\xB1\x00\xF0\x9F\x8D\x98\x00\xF0\x9F\x8D\x9D\x00\xF0\x9F\x8D\xA0\x00\xF0\x9F\x8D\xA2\x00\xF0\x9F\x8D\xA5\x00\xF0\x9F\x8D\xA1\x00\xF0\x9F\xA5\x9F\x00"
"\xF0\x9F\xA5\xA1\x00\xF0\x9F\x8D\xA6\x00\xF0\x9F\x8D\xAA\x00\xF0\x9F\x8E\x82\x00\xF0\x9F\x8D\xB0\x00\xF0\x9F\xA5\xA7\x00\xF0\x9F\x8D\xAB\x00\xF0\x9F\x8D\xAF\x00"
"\xF0\x9F\x8D\xBC\x00\xF0\x9F\xA5\x9B\x00\xF0\x9F\x8D\xB5\x00\xF0\x9F\x8D\xB6\x00\xF0\x9F\x8D\xBE\x00\xF0\x9F\x8D\xB7\x00\xF0\x9F\x8D\xBB\x00\xF0\x9F\xA5\x82\x00"
"\xF0\x9F\xA5\x83\x00\xF0\x9F\xA5\xA4\x00\xF0\x9F\xA5\xA2\x00\xF0\x9F\x91\x81\x00\xF0\x9F\x91\x85\x00\xF0\x9F\x91\x84\x00\xF0\x9F\x92\x8B\x00\xF0\x9F\x92\x98\x00"
"\xF0\x9F\x92\x93\x00\xF0\x9F\x92\x97\x00\xF0\x9F\x92\x99\x00\xF0\x9F\x92\x9B\x00\xF0\x9F\xA7\xA1\x00\xF0\x9F\x92\x9C\x00\xF0\x9F\x96\xA4\x00\xF0\x9F\x92\x9D\x00"
"\xF0\x9F\x92\x9F\x00\xF0\x9F\x92\x8C\x00\xF0\x9F\x92\xA4\x00\xF0\x9F\x92\xA2\x00\xF0\x9F\x92\xA3\x00";
struct {
string text;
string language;
}
const messages[] = { // Array containing all of the emojis messages
{"\x46\x61\x6C\x73\x63\x68\x65\x73\x20\xC3\x9C\x62\x65\x6E\x20\x76\x6F\x6E\x20\x58\x79\x6C\x6F\x70\x68\x6F\x6E\x6D\x75\x73\x69\x6B\x20\x71\x75\xC3\xA4\x6C"
"\x74\x20\x6A\x65\x64\x65\x6E\x20\x67\x72\xC3\xB6\xC3\x9F\x65\x72\x65\x6E\x20\x5A\x77\x65\x72\x67", "German"},
{"\x42\x65\x69\xC3\x9F\x20\x6E\x69\x63\x68\x74\x20\x69\x6E\x20\x64\x69\x65\x20\x48\x61\x6E\x64\x2C\x20\x64\x69\x65\x20\x64\x69\x63\x68\x20\x66\xC3\xBC\x74"
"\x74\x65\x72\x74\x2E", "German"},
{"\x41\x75\xC3\x9F\x65\x72\x6F\x72\x64\x65\x6E\x74\x6C\x69\x63\x68\x65\x20\xC3\x9C\x62\x65\x6C\x20\x65\x72\x66\x6F\x72\x64\x65\x72\x6E\x20\x61\x75\xC3\x9F"
"\x65\x72\x6F\x72\x64\x65\x6E\x74\x6C\x69\x63\x68\x65\x20\x4D\x69\x74\x74\x65\x6C\x2E", "German"},
{"\xD4\xBF\xD6\x80\xD5\xB6\xD5\xA1\xD5\xB4\x20\xD5\xA1\xD5\xBA\xD5\xA1\xD5\xAF\xD5\xAB\x20\xD5\xB8\xD6\x82\xD5\xBF\xD5\xA5\xD5\xAC\x20\xD6\x87\x20\xD5\xAB"
"\xD5\xB6\xD5\xAE\xD5\xAB\x20\xD5\xA1\xD5\xB6\xD5\xB0\xD5\xA1\xD5\xB6\xD5\xA3\xD5\xAB\xD5\xBD\xD5\xBF\x20\xD5\xB9\xD5\xA8\xD5\xB6\xD5\xA5\xD6\x80", "Armenian"},
{"\xD4\xB5\xD6\x80\xD5\xA2\x20\xD5\xB8\xD6\x80\x20\xD5\xAF\xD5\xA1\xD6\x81\xD5\xAB\xD5\xB6\xD5\xA8\x20\xD5\xA5\xD5\xAF\xD5\xA1\xD6\x82\x20\xD5\xA1\xD5\xB6\xD5"
"\xBF\xD5\xA1\xD5\xBC\x2C\x20\xD5\xAE\xD5\xA1\xD5\xBC\xD5\xA5\xD6\x80\xD5\xA8\x20\xD5\xA1\xD5\xBD\xD5\xA1\xD6\x81\xD5\xAB\xD5\xB6\x2E\x2E\x2E\x20\xC2\xAB\xD4\xBF"
"\xD5\xB8\xD5\xBF\xD5\xA8\x20\xD5\xB4\xD5\xA5\xD6\x80\xD5\xB8\xD5\xB6\xD6\x81\xD5\xAB\xD6\x81\x20\xD5\xA7\x3A\xC2\xBB", "Armenian"},
{"\xD4\xB3\xD5\xA1\xD5\xBC\xD5\xA8\xD5\x9D\x20\xD5\xA3\xD5\xA1\xD6\x80\xD5\xB6\xD5\xA1\xD5\xB6\x2C\x20\xD5\xB1\xD5\xAB\xD6\x82\xD5\xB6\xD5\xA8\xD5\x9D\x20\xD5"
"\xB1\xD5\xB4\xD5\xBC\xD5\xA1\xD5\xB6", "Armenian"},
{"\x4A\x65\xC5\xBC\x75\x20\x6B\x6C\xC4\x85\x74\x77\x2C\x20\x73\x70\xC5\x82\xC3\xB3\x64\xC5\xBA\x20\x46\x69\x6E\x6F\x6D\x20\x63\x7A\xC4\x99\xC5\x9B\xC4\x87"
"\x20\x67\x72\x79\x20\x68\x61\xC5\x84\x62\x21", "Polish"},
{"\x44\x6F\x62\x72\x79\x6D\x69\x20\x63\x68\xC4\x99\x63\x69\x61\x6D\x69\x20\x6A\x65\x73\x74\x20\x70\x69\x65\x6B\xC5\x82\x6F\x20\x77\x79\x62\x72\x75\x6B\x6F"
"\x77\x61\x6E\x65\x2E", "Polish"},
{"\xC3\x8E\xC8\x9B\x69\x20\x6D\x75\x6C\xC8\x9B\x75\x6D\x65\x73\x63\x20\x63\xC4\x83\x20\x61\x69\x20\x61\x6C\x65\x73\x20\x72\x61\x79\x6C\x69\x62\x2E\x0A\xC8\x98"
"\x69\x20\x73\x70\x65\x72\x20\x73\xC4\x83\x20\x61\x69\x20\x6F\x20\x7A\x69\x20\x62\x75\x6E\xC4\x83\x21", "Romanian"},
{"\xD0\xAD\xD1\x85\x2C\x20\xD1\x87\xD1\x83\xD0\xB6\xD0\xB0\xD0\xBA\x2C\x20\xD0\xBE\xD0\xB1\xD1\x89\xD0\xB8\xD0\xB9\x20\xD1\x81\xD1\x8A\xD1\x91\xD0\xBC\x20"
"\xD1\x86\xD0\xB5\xD0\xBD\x20\xD1\x88\xD0\xBB\xD1\x8F\xD0\xBF\x20\x28\xD1\x8E\xD1\x84\xD1\x82\xD1\x8C\x29\x20\xD0\xB2\xD0\xB4\xD1\x80\xD1\x8B\xD0\xB7\xD0\xB3\x21", "Russian"},
{"\xD0\xAF\x20\xD0\xBB\xD1\x8E\xD0\xB1\xD0\xBB\xD1\x8E\x20\x72\x61\x79\x6C\x69\x62\x21", "Russian"},
{"\xD0\x9C\xD0\xBE\xD0\xBB\xD1\x87\xD0\xB8\x2C\x20\xD1\x81\xD0\xBA\xD1\x80\xD1\x8B\xD0\xB2\xD0\xB0\xD0\xB9\xD1\x81\xD1\x8F\x20\xD0\xB8\x20\xD1\x82\xD0\xB0\xD0\xB8"
"\x0A\xD0\x98\x20\xD1\x87\xD1\x83\xD0\xB2\xD1\x81\xD1\x82\xD0\xB2\xD0\xB0\x20\xD0\xB8\x20\xD0\xBC\xD0\xB5\xD1\x87\xD1\x82\xD1\x8B\x20\xD1\x81\xD0\xB2\xD0\xBE\xD0\xB8\x20"
"\xE2\x80\x93\x0A\xD0\x9F\xD1\x83\xD1\x81\xD0\xBA\xD0\xB0\xD0\xB9\x20\xD0\xB2\x20\xD0\xB4\xD1\x83\xD1\x88\xD0\xB5\xD0\xB2\xD0\xBD\xD0\xBE\xD0\xB9\x20\xD0\xB3\xD0\xBB\xD1"
"\x83\xD0\xB1\xD0\xB8\xD0\xBD\xD0\xB5\x0A\xD0\x98\x20\xD0\xB2\xD1\x81\xD1\x85\xD0\xBE\xD0\xB4\xD1\x8F\xD1\x82\x20\xD0\xB8\x20\xD0\xB7\xD0\xB0\xD0\xB9\xD0\xB4\xD1\x83\xD1"
"\x82\x20\xD0\xBE\xD0\xBD\xD0\xB5\x0A\xD0\x9A\xD0\xB0\xD0\xBA\x20\xD0\xB7\xD0\xB2\xD0\xB5\xD0\xB7\xD0\xB4\xD1\x8B\x20\xD1\x8F\xD1\x81\xD0\xBD\xD1\x8B\xD0\xB5\x20\xD0\xB2"
"\x20\xD0\xBD\xD0\xBE\xD1\x87\xD0\xB8\x2D\x0A\xD0\x9B\xD1\x8E\xD0\xB1\xD1\x83\xD0\xB9\xD1\x81\xD1\x8F\x20\xD0\xB8\xD0\xBC\xD0\xB8\x20\xE2\x80\x93\x20\xD0\xB8\x20\xD0\xBC"
"\xD0\xBE\xD0\xBB\xD1\x87\xD0\xB8\x2E", "Russian"},
{"\x56\x6F\x69\x78\x20\x61\x6D\x62\x69\x67\x75\xC3\xAB\x20\x64\xE2\x80\x99\x75\x6E\x20\x63\xC5\x93\x75\x72\x20\x71\x75\x69\x20\x61\x75\x20\x7A\xC3\xA9\x70"
"\x68\x79\x72\x20\x70\x72\xC3\xA9\x66\xC3\xA8\x72\x65\x20\x6C\x65\x73\x20\x6A\x61\x74\x74\x65\x73\x20\x64\x65\x20\x6B\x69\x77\x69", "French"},
{"\x42\x65\x6E\x6A\x61\x6D\xC3\xAD\x6E\x20\x70\x69\x64\x69\xC3\xB3\x20\x75\x6E\x61\x20\x62\x65\x62\x69\x64\x61\x20\x64\x65\x20\x6B\x69\x77\x69\x20\x79\x20"
"\x66\x72\x65\x73\x61\x3B\x20\x4E\x6F\xC3\xA9\x2C\x20\x73\x69\x6E\x20\x76\x65\x72\x67\xC3\xBC\x65\x6E\x7A\x61\x2C\x20\x6C\x61\x20\x6D\xC3\xA1\x73\x20\x65\x78"
"\x71\x75\x69\x73\x69\x74\x61\x20\x63\x68\x61\x6D\x70\x61\xC3\xB1\x61\x20\x64\x65\x6C\x20\x6D\x65\x6E\xC3\xBA\x2E", "Spanish"},
{"\xCE\xA4\xCE\xB1\xCF\x87\xCE\xAF\xCF\x83\xCF\x84\xCE\xB7\x20\xCE\xB1\xCE\xBB\xCF\x8E\xCF\x80\xCE\xB7\xCE\xBE\x20\xCE\xB2\xCE\xB1\xCF\x86\xCE\xAE\xCF\x82\x20"
"\xCF\x88\xCE\xB7\xCE\xBC\xCE\xAD\xCE\xBD\xCE\xB7\x20\xCE\xB3\xCE\xB7\x2C\x20\xCE\xB4\xCF\x81\xCE\xB1\xCF\x83\xCE\xBA\xCE\xB5\xCE\xBB\xCE\xAF\xCE\xB6\xCE\xB5\xCE"
"\xB9\x20\xCF\x85\xCF\x80\xCE\xAD\xCF\x81\x20\xCE\xBD\xCF\x89\xCE\xB8\xCF\x81\xCE\xBF\xCF\x8D\x20\xCE\xBA\xCF\x85\xCE\xBD\xCF\x8C\xCF\x82", "Greek"},
{"\xCE\x97\x20\xCE\xBA\xCE\xB1\xCE\xBB\xCF\x8D\xCF\x84\xCE\xB5\xCF\x81\xCE\xB7\x20\xCE\xAC\xCE\xBC\xCF\x85\xCE\xBD\xCE\xB1\x20\xCE\xB5\xCE\xAF\xCE\xBD"
"\xCE\xB1\xCE\xB9\x20\xCE\xB7\x20\xCE\xB5\xCF\x80\xCE\xAF\xCE\xB8\xCE\xB5\xCF\x83\xCE\xB7\x2E", "Greek"},
{"\xCE\xA7\xCF\x81\xCF\x8C\xCE\xBD\xCE\xB9\xCE\xB1\x20\xCE\xBA\xCE\xB1\xCE\xB9\x20\xCE\xB6\xCE\xB1\xCE\xBC\xCE\xAC\xCE\xBD\xCE\xB9\xCE\xB1\x21", "Greek"},
{"\xCE\xA0\xCF\x8E\xCF\x82\x20\xCF\x84\xCE\xB1\x20\xCF\x80\xCE\xB1\xCF\x82\x20\xCF\x83\xCE\xAE\xCE\xBC\xCE\xB5\xCF\x81\xCE\xB1\x3B", "Greek"},
{"\xE6\x88\x91\xE8\x83\xBD\xE5\x90\x9E\xE4\xB8\x8B\xE7\x8E\xBB\xE7\x92\x83\xE8\x80\x8C\xE4\xB8\x8D\xE4\xBC\xA4\xE8\xBA\xAB\xE4\xBD\x93\xE3\x80\x82", "Chinese"},
{"\xE4\xBD\xA0\xE5\x90\x83\xE4\xBA\x86\xE5\x90\x97\xEF\xBC\x9F", "Chinese"},
{"\xE4\xB8\x8D\xE4\xBD\x9C\xE4\xB8\x8D\xE6\xAD\xBB\xE3\x80\x82", "Chinese"},
{"\xE6\x9C\x80\xE8\xBF\x91\xE5\xA5\xBD\xE5\x90\x97\xEF\xBC\x9F", "Chinese"},
{"\xE5\xA1\x9E\xE7\xBF\x81\xE5\xA4\xB1\xE9\xA9\xAC\xEF\xBC\x8C\xE7\x84\x89\xE7\x9F\xA5\xE9\x9D\x9E\xE7\xA6\x8F\xE3\x80\x82", "Chinese"},
{"\xE5\x8D\x83\xE5\x86\x9B\xE6\x98\x93\xE5\xBE\x97\x2C\x20\xE4\xB8\x80\xE5\xB0\x86\xE9\x9A\xBE\xE6\xB1\x82", "Chinese"},
{"\xE4\xB8\x87\xE4\xBA\x8B\xE5\xBC\x80\xE5\xA4\xB4\xE9\x9A\xBE\xE3\x80\x82", "Chinese"},
{"\xE9\xA3\x8E\xE6\x97\xA0\xE5\xB8\xB8\xE9\xA1\xBA\xEF\xBC\x8C\xE5\x85\xB5\xE6\x97\xA0\xE5\xB8\xB8\xE8\x83\x9C\xE3\x80\x82", "Chinese"},
{"\xE6\xB4\xBB\xE5\x88\xB0\xE8\x80\x81\xEF\xBC\x8C\xE5\xAD\xA6\xE5\x88\xB0\xE8\x80\x81\xE3\x80\x82", "Chinese"},
{"\xE4\xB8\x80\xE8\xA8\x80\xE6\x97\xA2\xE5\x87\xBA\xEF\xBC\x8C\xE9\xA9\xB7\xE9\xA9\xAC\xE9\x9A\xBE\xE8\xBF\xBD\xE3\x80\x82", "Chinese"},
{"\xE8\xB7\xAF\xE9\x81\xA5\xE7\x9F\xA5\xE9\xA9\xAC\xE5\x8A\x9B\xEF\xBC\x8C\xE6\x97\xA5\xE4\xB9\x85\xE8\xA7\x81\xE4\xBA\xBA\xE5\xBF\x83", "Chinese"},
{"\xE6\x9C\x89\xE7\x90\x86\xE8\xB5\xB0\xE9\x81\x8D\xE5\xA4\xA9\xE4\xB8\x8B\xEF\xBC\x8C\xE6\x97\xA0\xE7\x90\x86\xE5\xAF\xB8\xE6\xAD\xA5\xE9\x9A\xBE\xE8\xA1\x8C\xE3\x80\x82", "Chinese"},
{"\xE7\x8C\xBF\xE3\x82\x82\xE6\x9C\xA8\xE3\x81\x8B\xE3\x82\x89\xE8\x90\xBD\xE3\x81\xA1\xE3\x82\x8B", "Japanese"},
{"\xE4\xBA\x80\xE3\x81\xAE\xE7\x94\xB2\xE3\x82\x88\xE3\x82\x8A\xE5\xB9\xB4\xE3\x81\xAE\xE5\x8A\x9F", "Japanese"},
{"\xE3\x81\x86\xE3\x82\x89\xE3\x82\x84\xE3\x81\xBE\xE3\x81\x97\x20\x20\xE6\x80\x9D\xE3\x81\xB2\xE5\x88\x87\xE3\x82\x8B\xE6\x99\x82\x20\x20\xE7\x8C\xAB\xE3\x81\xAE\xE6\x81\x8B", "Japanese"},
{"\xE8\x99\x8E\xE7\xA9\xB4\xE3\x81\xAB\xE5\x85\xA5\xE3\x82\x89\xE3\x81\x9A\xE3\x82\x93\xE3\x81\xB0\xE8\x99\x8E\xE5\xAD\x90\xE3\x82\x92\xE5\xBE\x97\xE3\x81\x9A\xE3\x80\x82", "Japanese"},
{"\xE4\xBA\x8C\xE5\x85\x8E\xE3\x82\x92\xE8\xBF\xBD\xE3\x81\x86\xE8\x80\x85\xE3\x81\xAF\xE4\xB8\x80\xE5\x85\x8E\xE3\x82\x92\xE3\x82\x82\xE5\xBE\x97\xE3\x81\x9A\xE3\x80\x82", "Japanese"},
{"\xE9\xA6\xAC\xE9\xB9\xBF\xE3\x81\xAF\xE6\xAD\xBB\xE3\x81\xAA\xE3\x81\xAA\xE3\x81\x8D\xE3\x82\x83\xE6\xB2\xBB\xE3\x82\x89\xE3\x81\xAA\xE3\x81\x84\xE3\x80\x82", "Japanese"},
{"\xE6\x9E\xAF\xE9\x87\x8E\xE8\xB7\xAF\xE3\x81\xAB\xE3\x80\x80\xE5\xBD\xB1\xE3\x81\x8B\xE3\x81\x95\xE3\x81\xAA\xE3\x82\x8A\xE3\x81\xA6\xE3\x80\x80\xE3\x82\x8F\xE3\x81\x8B\xE3\x82\x8C\xE3\x81\x91\xE3\x82\x8A", "Japanese"},
{"\xE7\xB9\xB0\xE3\x82\x8A\xE8\xBF\x94\xE3\x81\x97\xE9\xBA\xA6\xE3\x81\xAE\xE7\x95\x9D\xE7\xB8\xAB\xE3\x81\xB5\xE8\x83\xA1\xE8\x9D\xB6\xE5\x93\x89", "Japanese"},
{"\xEC\x95\x84\xEB\x93\x9D\xED\x95\x9C\x20\xEB\xB0\x94\xEB\x8B\xA4\x20\xEC\x9C\x84\xEC\x97\x90\x20\xEA\xB0\x88\xEB\xA7\xA4\xEA\xB8\xB0\x20\xEB\x91\x90\xEC\x97\x87\x20"
"\xEB\x82\xA0\xEC\x95\x84\x20\xEB\x8F\x88\xEB\x8B\xA4\x2E\x0A\xEB\x84\x88\xED\x9B\x8C\xEB\x84\x88\xED\x9B\x8C\x20\xEC\x8B\x9C\xEB\xA5\xBC\x20\xEC\x93\xB4\xEB\x8B\xA4\x2E"
"\x20\xEB\xAA\xA8\xEB\xA5\xB4\xEB\x8A\x94\x20\xEB\x82\x98\xEB\x9D\xBC\x20\xEA\xB8\x80\xEC\x9E\x90\xEB\x8B\xA4\x2E\x0A\xEB\x84\x90\xEB\x94\xB0\xEB\x9E\x80\x20\xED\x95\x98"
"\xEB\x8A\x98\x20\xEB\xB3\xB5\xED\x8C\x90\xEC\x97\x90\x20\xEB\x82\x98\xEB\x8F\x84\x20\xEA\xB0\x99\xEC\x9D\xB4\x20\xEC\x8B\x9C\xEB\xA5\xBC\x20\xEC\x93\xB4\xEB\x8B\xA4\x2E", "Korean"},
{"\xEC\xA0\x9C\x20\xEB\x88\x88\xEC\x97\x90\x20\xEC\x95\x88\xEA\xB2\xBD\xEC\x9D\xB4\xEB\x8B\xA4", "Korean"},
{"\xEA\xBF\xA9\x20\xEB\xA8\xB9\xEA\xB3\xA0\x20\xEC\x95\x8C\x20\xEB\xA8\xB9\xEB\x8A\x94\xEB\x8B\xA4", "Korean"},
{"\xEB\xA1\x9C\xEB\xA7\x88\xEB\x8A\x94\x20\xED\x95\x98\xEB\xA3\xA8\xEC\x95\x84\xEC\xB9\xA8\xEC\x97\x90\x20\xEC\x9D\xB4\xEB\xA3\xA8\xEC\x96\xB4\xEC\xA7\x84\x20\xEA\xB2\x83\xEC\x9D\xB4"
"\x20\xEC\x95\x84\xEB\x8B\x88\xEB\x8B\xA4", "Korean"},
{"\xEA\xB3\xA0\xEC\x83\x9D\x20\xEB\x81\x9D\xEC\x97\x90\x20\xEB\x82\x99\xEC\x9D\xB4\x20\xEC\x98\xA8\xEB\x8B\xA4", "Korean"},
{"\xEA\xB0\x9C\xEC\xB2\x9C\xEC\x97\x90\xEC\x84\x9C\x20\xEC\x9A\xA9\x20\xEB\x82\x9C\xEB\x8B\xA4", "Korean"},
{"\xEC\x95\x88\xEB\x85\x95\xED\x95\x98\xEC\x84\xB8\xEC\x9A\x94\x3F", "Korean"},
{"\xEB\xA7\x8C\xEB\x82\x98\xEC\x84\x9C\x20\xEB\xB0\x98\xEA\xB0\x91\xEC\x8A\xB5\xEB\x8B\x88\xEB\x8B\xA4", "Korean"},
{"\xED\x95\x9C\xEA\xB5\xAD\xEB\xA7\x90\x20\xED\x95\x98\xEC\x8B\xA4\x20\xEC\xA4\x84\x20\xEC\x95\x84\xEC\x84\xB8\xEC\x9A\x94\x3F", "Korean"},
};
//--------------------------------------------------------------------------------------
// Module functions declaration
//--------------------------------------------------------------------------------------
static void RandomizeEmoji(void); // Fills the emoji array with random emojis
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
// Arrays that holds the random emojis
struct emoji
{
int index; // Index inside `emojiCodepoints`
int message; // Message index
Color color; // Emoji color
}
emoji[EMOJI_PER_WIDTH * EMOJI_PER_HEIGHT] = { 0 };
static int hovered = -1, selected = -1;
int main(int argc, char** argv)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT | FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "raylib [text] example - unicode");
// Load the font resources
// NOTE: fontAsian is for asian languages,
// fontEmoji is the emojis and fontDefault is used for everything else
Font fontDefault = LoadFont("resources/fonts/dejavu.fnt");
Font fontAsian = LoadFont("resources/fonts/notoCJK.fnt");
Font fontEmoji = LoadFont("resources/fonts/emoji.fnt");
Vector2 hoveredPos = new(0.0f, 0.0f);
Vector2 selectedPos = new(0.0f, 0.0f);
// Set a random set of emojis when starting up
RandomizeEmoji();
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
// Add a new set of emojis when SPACE is pressed
if (IsKeyPressed(KEY_SPACE)) RandomizeEmoji();
// Set the selected emoji and copy its text to clipboard
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && (hovered != -1) && (hovered != selected))
{
selected = hovered;
selectedPos = hoveredPos;
SetClipboardText(messages[emoji[selected].message].text);
}
Vector2 mouse = GetMousePosition();
Vector2 pos = new(28.8f, 10.0f);
hovered = -1;
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RAYWHITE);
// Draw random emojis in the background
//------------------------------------------------------------------------------
for (int i = 0; i < SIZEOF(emoji); ++i)
{
const char* txt = ref[emoji[i].index];
Rectangle emojiRect = new(pos.X, pos.Y, fontEmoji.BaseSize, fontEmoji.BaseSize);
if (!CheckCollisionPointRec(mouse, emojiRect))
{
DrawTextEx(fontEmoji, txt, pos, fontEmoji.BaseSize, 1.0, selected == i ? emoji[i].Color : ColorAlpha(LIGHTGRAY, 0.4f));
}
else
{
DrawTextEx(fontEmoji, txt, pos, fontEmoji.BaseSize, 1.0, emoji[i].Color);
hovered = i;
hoveredPos = pos;
}
if ((i != 0) && (i % EMOJI_PER_WIDTH == 0)) { pos.Y += fontEmoji.BaseSize + 24.25f; pos.X = 28.8f; }
else pos.X += fontEmoji.BaseSize + 28.8f;
}
//------------------------------------------------------------------------------
// Draw the message when a emoji is selected
//------------------------------------------------------------------------------
if (selected != -1)
{
const int message = emoji[selected].message;
const int horizontalPadding = 20, verticalPadding = 30;
Font* font = ref;
// Set correct font for asian languages
if (TextIsEqual(messages[message].language, "Chinese") ||
TextIsEqual(messages[message].language, "Korean") ||
TextIsEqual(messages[message].language, "Japanese")) font = ref;
// Calculate size for the message box (approximate the height and width)
Vector2 sz = MeasureTextEx(*font, messages[message].text, font->baseSize, 1.0f);
if (sz.X > 300) { sz.Y *= sz.X / 300; sz.X = 300; }
else if (sz.X < 160) sz.X = 160;
Rectangle msgRect = new(selectedPos.X - 38.8f, selectedPos.Y, 2 * horizontalPadding + sz.X, 2 * verticalPadding + sz.Y);
msgRect.Y -= msgRect.Height;
// Coordinates for the chat bubble triangle
Vector2 a = new(selectedPos.X, msgRect.Y + msgRect.Height);
Vector2 b = new(a.X + 8, a.Y + 10);
Vector2 c = new(a.X + 10, a.Y);
// Don't go outside the screen
if (msgRect.X < 10) msgRect.X += 28;
if (msgRect.Y < 10)
{
msgRect.Y = selectedPos.Y + 84;
a.Y = msgRect.Y;
c.Y = a.Y;
b.Y = a.Y - 10;
// Swap values so we can actually render the triangle :(
Vector2 tmp = a;
a = b;
b = tmp;
}
if (msgRect.X + msgRect.Width > screenWidth) msgRect.X -= (msgRect.X + msgRect.Width) - screenWidth + 10;
// Draw chat bubble
DrawRectangleRec(msgRect, emoji[selected].Color);
DrawTriangle(a, b, c, emoji[selected].Color);
// Draw the main text message
Rectangle textRect = new(msgRect.X + horizontalPadding / 2, msgRect.Y + verticalPadding / 2, msgRect.Width - horizontalPadding, msgRect.Height);
DrawTextRec(*font, messages[message].text, textRect, font->baseSize, 1.0f, true, WHITE);
// Draw the info text below the main message
int size = strlen(messages[message].text);
int len = GetCodepointsCount(messages[message].text);
const char* info = TextFormat("%s %u characters %i bytes", messages[message].language, len, size);
sz = MeasureTextEx(GetFontDefault(), info, 10, 1.0f);
Vector2 pos = new(textRect.X + textRect.Width - sz.X, msgRect.Y + msgRect.Height - sz.Y - 2);
DrawText(info, pos.X, pos.Y, 10, RAYWHITE);
}
//------------------------------------------------------------------------------
// Draw the info text
DrawText("These emojis have something to tell you, click each to find out!", (screenWidth - 650) / 2, screenHeight - 40, 20, GRAY);
DrawText("Each emoji is a unicode character from a font, not a texture... Press [SPACEBAR] to refresh", (screenWidth - 484) / 2, screenHeight - 16, 10, GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadFont(fontDefault); // Unload font resource
UnloadFont(fontAsian); // Unload font resource
UnloadFont(fontEmoji); // Unload font resource
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}
// Fills the emoji array with random emoji (only those emojis present in fontEmoji)
static void RandomizeEmoji(void)
{
hovered = selected = -1;
int start = GetRandomValue(45, 360);
for (int i = 0; i < SIZEOF(emoji); ++i)
{
// 0-179 emoji codepoints (from emoji char array) each 4bytes + null char
emoji[i].index = GetRandomValue(0, 179) * 5;
// Generate a random color for this emoji
Vector3 hsv = new((start * (i + 1)) % 360, 0.6f, 0.85f);
emoji[i].Color = ColorAlpha(ColorFromHSV(hsv), 0.8f);
// Set a random message for this emoji
emoji[i].message = GetRandomValue(0, SIZEOF(messages) - 1);
}
}
}
}

View File

@ -0,0 +1,74 @@
/*******************************************************************************************
*
* raylib [text] example - Text Writing Animation
*
* This example has been created using raylib 1.4 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2016 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Text;
public class WritingAnim
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [text] example - text writing anim");
string message = "This sample illustrates a text writing\nanimation effect! Check it out! ;)";
int framesCounter = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyDown(KeyboardKey.KEY_SPACE))
{
framesCounter += 8;
}
else
{
framesCounter += 1;
}
if (IsKeyPressed(KeyboardKey.KEY_ENTER))
{
framesCounter = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
DrawText(message.SubText(0, framesCounter / 10), 210, 160, 20, Color.MAROON);
DrawText("PRESS [ENTER] to RESTART!", 240, 260, 20, Color.LIGHTGRAY);
DrawText("PRESS [SPACE] to SPEED UP!", 239, 300, 20, Color.LIGHTGRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,116 @@
/*******************************************************************************************
*
* raylib [textures] example - Background scrolling
*
* This example has been created using raylib 2.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Textures;
public class BackgroundScrolling
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - background scrolling");
// NOTE: Be careful, background width must be equal or bigger than screen width
// if not, texture should be draw more than two times for scrolling effect
Texture2D background = LoadTexture("resources/cyberpunk_street_background.png");
Texture2D midground = LoadTexture("resources/cyberpunk_street_midground.png");
Texture2D foreground = LoadTexture("resources/cyberpunk_street_foreground.png");
float scrollingBack = 0.0f;
float scrollingMid = 0.0f;
float scrollingFore = 0.0f;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
scrollingBack -= 0.1f;
scrollingMid -= 0.5f;
scrollingFore -= 1.0f;
// NOTE: Texture is scaled twice its size, so it sould be considered on scrolling
if (scrollingBack <= -background.Width * 2)
{
scrollingBack = 0;
}
if (scrollingMid <= -midground.Width * 2)
{
scrollingMid = 0;
}
if (scrollingFore <= -foreground.Width * 2)
{
scrollingFore = 0;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(GetColor(0x052c46ff));
// Draw background image twice
// NOTE: Texture is scaled twice its size
DrawTextureEx(background, new Vector2(scrollingBack, 20), 0.0f, 2.0f, Color.WHITE);
DrawTextureEx(
background,
new Vector2(background.Width * 2 + scrollingBack, 20),
0.0f,
2.0f,
Color.WHITE
);
// Draw midground image twice
DrawTextureEx(midground, new Vector2(scrollingMid, 20), 0.0f, 2.0f, Color.WHITE);
DrawTextureEx(midground, new Vector2(midground.Width * 2 + scrollingMid, 20), 0.0f, 2.0f, Color.WHITE);
// Draw foreground image twice
DrawTextureEx(foreground, new Vector2(scrollingFore, 70), 0.0f, 2.0f, Color.WHITE);
DrawTextureEx(
foreground,
new Vector2(foreground.Width * 2 + scrollingFore, 70),
0.0f,
2.0f,
Color.WHITE
);
DrawText("BACKGROUND SCROLLING & PARALLAX", 10, 10, 20, Color.RED);
int x = screenWidth - 330;
int y = screenHeight - 20;
DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", x, y, 10, Color.RAYWHITE);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(background);
UnloadTexture(midground);
UnloadTexture(foreground);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,117 @@
/*******************************************************************************************
*
* raylib [textures] example - blend modes
*
* NOTE: Images are loaded in CPU memory (RAM); textures are loaded in GPU memory (VRAM)
*
* This example has been created using raylib 3.5 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Example contributed by Karlo Licudine (@accidentalrebel) and reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2020 Karlo Licudine (@accidentalrebel)
*
********************************************************************************************/
using static Raylib_cs.Raylib;
namespace Examples.Textures;
public class BlendModes
{
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - blend modes");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Image bgImage = LoadImage("resources/cyberpunk_street_background.png");
Texture2D bgTexture = LoadTextureFromImage(bgImage);
Image fgImage = LoadImage("resources/cyberpunk_street_foreground.png");
Texture2D fgTexture = LoadTextureFromImage(fgImage);
// Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM
UnloadImage(bgImage);
UnloadImage(fgImage);
const int blendCountMax = 4;
BlendMode blendMode = 0;
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
if ((int)blendMode >= (blendCountMax - 1))
{
blendMode = 0;
}
else
{
blendMode++;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
int bgX = screenWidth / 2 - bgTexture.Width / 2;
int bgY = screenHeight / 2 - bgTexture.Height / 2;
DrawTexture(bgTexture, bgX, bgY, Color.WHITE);
// Apply the blend mode and then draw the foreground texture
BeginBlendMode(blendMode);
int fgX = screenWidth / 2 - fgTexture.Width / 2;
int fgY = screenHeight / 2 - fgTexture.Height / 2;
DrawTexture(fgTexture, fgX, fgY, Color.WHITE);
EndBlendMode();
// Draw the texts
DrawText("Press SPACE to change blend modes.", 310, 350, 10, Color.GRAY);
switch (blendMode)
{
case BlendMode.BLEND_ALPHA:
DrawText("Current: BLEND_ALPHA", (screenWidth / 2) - 60, 370, 10, Color.GRAY);
break;
case BlendMode.BLEND_ADDITIVE:
DrawText("Current: BLEND_ADDITIVE", (screenWidth / 2) - 60, 370, 10, Color.GRAY);
break;
case BlendMode.BLEND_MULTIPLIED:
DrawText("Current: BLEND_MULTIPLIED", (screenWidth / 2) - 60, 370, 10, Color.GRAY);
break;
case BlendMode.BLEND_ADD_COLORS:
DrawText("Current: BLEND_ADD_COLORS", (screenWidth / 2) - 60, 370, 10, Color.GRAY);
break;
default:
break;
}
string text = "(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)";
DrawText(text, screenWidth - 330, screenHeight - 20, 10, Color.GRAY);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(fgTexture);
UnloadTexture(bgTexture);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,133 @@
/*******************************************************************************************
*
* raylib [textures] example - Bunnymark
*
* This example has been created using raylib 1.6 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2014-2019 Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Textures;
public class Bunnymark
{
public const int MaxBunnies = 150000;
// This is the maximum amount of elements (quads) per batch
// NOTE: This value is defined in [rlgl] module and can be changed there
public const int MAX_BATCH_ELEMENTS = 8192;
struct Bunny
{
public Vector2 Position;
public Vector2 Speed;
public Color Color;
}
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [textures] example - bunnymark");
// Load bunny texture
Texture2D texBunny = LoadTexture("resources/wabbit_alpha.png");
// 50K bunnies limit
Bunny[] bunnies = new Bunny[MaxBunnies];
int bunniesCount = 0;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
if (IsMouseButtonDown(MouseButton.MOUSE_LEFT_BUTTON))
{
// Create more bunnies
for (int i = 0; i < 100; i++)
{
if (bunniesCount < MaxBunnies)
{
bunnies[bunniesCount].Position = GetMousePosition();
bunnies[bunniesCount].Speed.X = (float)GetRandomValue(-250, 250) / 60.0f;
bunnies[bunniesCount].Speed.Y = (float)GetRandomValue(-250, 250) / 60.0f;
bunnies[bunniesCount].Color = new Color(
GetRandomValue(50, 240),
GetRandomValue(80, 240),
GetRandomValue(100, 240), 255
);
bunniesCount++;
}
}
}
// Update bunnies
Vector2 screen = new(GetScreenWidth(), GetScreenHeight());
Vector2 halfSize = new Vector2(texBunny.Width, texBunny.Height) / 2;
for (int i = 0; i < bunniesCount; i++)
{
bunnies[i].Position += bunnies[i].Speed;
if (((bunnies[i].Position.X + halfSize.X) > screen.X) ||
((bunnies[i].Position.X + halfSize.X) < 0))
{
bunnies[i].Speed.X *= -1;
}
if (((bunnies[i].Position.Y + halfSize.Y) > screen.Y) ||
((bunnies[i].Position.Y + halfSize.Y - 40) < 0))
{
bunnies[i].Speed.Y *= -1;
}
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
for (int i = 0; i < bunniesCount; i++)
{
// NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS),
// a draw call is launched and buffer starts being filled again;
// before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU...
// Process of sending data is costly and it could happen that GPU data has not been completely
// processed for drawing while new data is tried to be sent (updating current in-use buffers)
// it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies
DrawTexture(texBunny, (int)bunnies[i].Position.X, (int)bunnies[i].Position.Y, bunnies[i].Color);
}
DrawRectangle(0, 0, screenWidth, 40, Color.BLACK);
DrawText($"bunnies: {bunniesCount}", 120, 10, 20, Color.GREEN);
DrawText($"batched draw calls: {1 + bunniesCount / MAX_BATCH_ELEMENTS}", 320, 10, 20, Color.MAROON);
DrawFPS(10, 10);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texBunny);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
}

View File

@ -0,0 +1,449 @@
/*******************************************************************************************
*
* raylib [textures] example - Draw part of the texture tiled
*
* This example has been created using raylib 3.0 (www.raylib.com)
* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
*
* Copyright (c) 2020 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
using System.Numerics;
using static Raylib_cs.Raylib;
namespace Examples.Textures;
public class DrawTiled
{
const int OptWidth = 220;
const int MarginSize = 8;
const int ColorSize = 16;
public static int Main()
{
// Initialization
//--------------------------------------------------------------------------------------
int screenWidth = 800;
int screenHeight = 450;
SetConfigFlags(ConfigFlags.FLAG_WINDOW_RESIZABLE);
InitWindow(screenWidth, screenHeight, "raylib [textures] example - Draw part of a texture tiled");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Texture2D texPattern = LoadTexture("resources/patterns.png");
// Makes the texture smoother when upscaled
SetTextureFilter(texPattern, TextureFilter.TEXTURE_FILTER_TRILINEAR);
// Coordinates for all patterns inside the texture
Rectangle[] recPattern = new[] {
new Rectangle(3, 3, 66, 66),
new Rectangle(75, 3, 100, 100),
new Rectangle(3, 75, 66, 66),
new Rectangle(7, 156, 50, 50),
new Rectangle(85, 106, 90, 45),
new Rectangle(75, 154, 100, 60)
};
// Setup colors
Color[] colors = new[]
{
Color.BLACK,
Color.MAROON,
Color.ORANGE,
Color.BLUE,
Color.PURPLE,
Color.BEIGE,
Color.LIME,
Color.RED,
Color.DARKGRAY,
Color.SKYBLUE
};
Rectangle[] colorRec = new Rectangle[colors.Length];
// Calculate rectangle for each color
for (int i = 0, x = 0, y = 0; i < colors.Length; i++)
{
colorRec[i].X = 2 + MarginSize + x;
colorRec[i].Y = 22 + 256 + MarginSize + y;
colorRec[i].Width = ColorSize * 2;
colorRec[i].Height = ColorSize;
if (i == (colors.Length / 2 - 1))
{
x = 0;
y += ColorSize + MarginSize;
}
else
{
x += (ColorSize * 2 + MarginSize);
}
}
int activePattern = 0, activeCol = 0;
float scale = 1.0f, rotation = 0.0f;
SetTargetFPS(60);
//---------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose())
{
// Update
//----------------------------------------------------------------------------------
screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight();
// Handle mouse
if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON))
{
Vector2 mouse = GetMousePosition();
// Check which pattern was clicked and set it as the active pattern
for (int i = 0; i < recPattern.Length; i++)
{
Rectangle rec = new(
2 + MarginSize + recPattern[i].X,
40 + MarginSize + recPattern[i].Y,
recPattern[i].Width,
recPattern[i].Height
);
if (CheckCollisionPointRec(mouse, rec))
{
activePattern = i;
break;
}
}
// Check to see which color was clicked and set it as the active color
for (int i = 0; i < colors.Length; ++i)
{
if (CheckCollisionPointRec(mouse, colorRec[i]))
{
activeCol = i;
break;
}
}
}
// Handle keys
// Change scale
if (IsKeyPressed(KeyboardKey.KEY_UP))
{
scale += 0.25f;
}
if (IsKeyPressed(KeyboardKey.KEY_DOWN))
{
scale -= 0.25f;
}
if (scale > 10.0f)
{
scale = 10.0f;
}
else if (scale <= 0.0f)
{
scale = 0.25f;
}
// Change rotation
if (IsKeyPressed(KeyboardKey.KEY_LEFT))
{
rotation -= 25.0f;
}
if (IsKeyPressed(KeyboardKey.KEY_RIGHT))
{
rotation += 25.0f;
}
// Reset
if (IsKeyPressed(KeyboardKey.KEY_SPACE))
{
rotation = 0.0f;
scale = 1.0f;
}
//----------------------------------------------------------------------------------
// Draw
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(Color.RAYWHITE);
// Draw the tiled area
Rectangle source = recPattern[activePattern];
Rectangle dest = new(
OptWidth + MarginSize,
MarginSize,
screenWidth - OptWidth - 2 * MarginSize,
screenHeight - 2 * MarginSize
);
DrawTextureTiled(texPattern, source, dest, Vector2.Zero, rotation, scale, colors[activeCol]);
// Draw options
Color color = ColorAlpha(Color.LIGHTGRAY, 0.5f);
DrawRectangle(MarginSize, MarginSize, OptWidth - MarginSize, screenHeight - 2 * MarginSize, color);
DrawText("Select Pattern", 2 + MarginSize, 30 + MarginSize, 10, Color.BLACK);
DrawTexture(texPattern, 2 + MarginSize, 40 + MarginSize, Color.BLACK);
DrawRectangle(
2 + MarginSize + (int)recPattern[activePattern].X,
40 + MarginSize + (int)recPattern[activePattern].Y,
(int)recPattern[activePattern].Width,
(int)recPattern[activePattern].Height,
ColorAlpha(Color.DARKBLUE, 0.3f)
);
DrawText("Select Color", 2 + MarginSize, 10 + 256 + MarginSize, 10, Color.BLACK);
for (int i = 0; i < colors.Length; i++)
{
DrawRectangleRec(colorRec[i], colors[i]);
if (activeCol == i)
{
DrawRectangleLinesEx(colorRec[i], 3, ColorAlpha(Color.WHITE, 0.5f));
}
}
DrawText("Scale (UP/DOWN to change)", 2 + MarginSize, 80 + 256 + MarginSize, 10, Color.BLACK);
DrawText($"{scale}x", 2 + MarginSize, 92 + 256 + MarginSize, 20, Color.BLACK);
DrawText("Rotation (LEFT/RIGHT to change)", 2 + MarginSize, 122 + 256 + MarginSize, 10, Color.BLACK);
DrawText($"{rotation} degrees", 2 + MarginSize, 134 + 256 + MarginSize, 20, Color.BLACK);
DrawText("Press [SPACE] to reset", 2 + MarginSize, 164 + 256 + MarginSize, 10, Color.DARKBLUE);
// Draw FPS
DrawText($"{GetFPS()}", 2 + MarginSize, 2 + MarginSize, 20, Color.BLACK);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadTexture(texPattern);
CloseWindow();
//--------------------------------------------------------------------------------------
return 0;
}
// Draw part of a texture (defined by a rectangle) with rotation and scale tiled into dest.
static void DrawTextureTiled(
Texture2D texture,
Rectangle source,
Rectangle dest,
Vector2 origin,
float rotation,
float scale,
Color tint
)
{
if ((texture.Id <= 0) || (scale <= 0.0f))
{
// Wanna see a infinite loop?!...just delete this line!
return;
}
if ((source.Width == 0) || (source.Height == 0))
{
return;
}
int tileWidth = (int)(source.Width * scale), tileHeight = (int)(source.Height * scale);
if ((dest.Width < tileWidth) && (dest.Height < tileHeight))
{
// Can fit only one tile
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)dest.Width / tileWidth) * source.Width,
((float)dest.Height / tileHeight) * source.Height
),
new Rectangle(dest.X, dest.Y, dest.Width, dest.Height), origin, rotation, tint
);
}
else if (dest.Width <= tileWidth)
{
// Tiled vertically (one column)
int dy = 0;
for (; dy + tileHeight < dest.Height; dy += tileHeight)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)dest.Width / tileWidth) * source.Width,
source.Height
),
new Rectangle(dest.X, dest.Y + dy, dest.Width, (float)tileHeight),
origin,
rotation,
tint
);
}
// Fit last tile
if (dy < dest.Height)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)dest.Width / tileWidth) * source.Width,
((float)(dest.Height - dy) / tileHeight) * source.Height
),
new Rectangle(dest.X, dest.Y + dy, dest.Width, dest.Height - dy),
origin,
rotation,
tint
);
}
}
else if (dest.Height <= tileHeight)
{
// Tiled horizontally (one row)
int dx = 0;
for (; dx + tileWidth < dest.Width; dx += tileWidth)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
source.Width,
((float)dest.Height / tileHeight) * source.Height
),
new Rectangle(dest.X + dx, dest.Y, (float)tileWidth, dest.Height),
origin,
rotation,
tint
);
}
// Fit last tile
if (dx < dest.Width)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)(dest.Width - dx) / tileWidth) * source.Width,
((float)dest.Height / tileHeight) * source.Height
),
new Rectangle(
dest.X + dx,
dest.Y,
dest.Width - dx,
dest.Height
),
origin,
rotation,
tint
);
}
}
else
{
// Tiled both horizontally and vertically (rows and columns)
int dx = 0;
for (; dx + tileWidth < dest.Width; dx += tileWidth)
{
int dy = 0;
for (; dy + tileHeight < dest.Height; dy += tileHeight)
{
DrawTexturePro(
texture,
source,
new Rectangle(
dest.X + dx,
dest.Y + dy,
(float)tileWidth,
(float)tileHeight
),
origin,
rotation,
tint
);
}
if (dy < dest.Height)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
source.Width,
((float)(dest.Height - dy) / tileHeight) * source.Height
),
new Rectangle(
dest.X + dx,
dest.Y + dy,
(float)tileWidth, dest.Height - dy
),
origin,
rotation,
tint
);
}
}
// Fit last column of tiles
if (dx < dest.Width)
{
int dy = 0;
for (; dy + tileHeight < dest.Height; dy += tileHeight)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)(dest.Width - dx) / tileWidth) * source.Width,
source.Height
),
new Rectangle(
dest.X + dx,
dest.Y + dy,
dest.Width - dx,
(float)tileHeight
),
origin,
rotation,
tint
);
}
// Draw final tile in the bottom right corner
if (dy < dest.Height)
{
DrawTexturePro(
texture,
new Rectangle(
source.X,
source.Y,
((float)(dest.Width - dx) / tileWidth) * source.Width,
((float)(dest.Height - dy) / tileHeight) * source.Height
),
new Rectangle(
dest.X + dx,
dest.Y + dy,
dest.Width - dx,
dest.Height - dy
),
origin,
rotation,
tint
);
}
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More