Merge branch 'raysan5:master' into master

This commit is contained in:
Crydsch 2021-05-21 17:27:41 +02:00
commit 17ab26fdb2
262 changed files with 4741 additions and 3484 deletions

2
.gitignore vendored
View File

@ -55,8 +55,6 @@ packages/
# Ignore all examples files # Ignore all examples files
examples/* examples/*
# Unignore all examples dirs
!examples/*/
# Unignore all examples files with extension # Unignore all examples files with extension
!examples/*.c !examples/*.c
!examples/*.png !examples/*.png

View File

@ -6,11 +6,11 @@ Here it is a list with the ones I'm aware of:
| name | raylib version | language | repo | | name | raylib version | language | repo |
|:------------------:|:-------------: | :--------:|----------------------------------------------------------------------| |:------------------:|:-------------: | :--------:|----------------------------------------------------------------------|
| raylib | **3.5** | [C](https://en.wikipedia.org/wiki/C_(programming_language)) | https://github.com/raysan5/raylib | | raylib | **3.7** | [C](https://en.wikipedia.org/wiki/C_(programming_language)) | https://github.com/raysan5/raylib |
| raylib-cpp | 3.5 | [C++](https://en.wikipedia.org/wiki/C%2B%2B) | https://github.com/robloach/raylib-cpp | | raylib-cpp | 3.7 | [C++](https://en.wikipedia.org/wiki/C%2B%2B) | https://github.com/robloach/raylib-cpp |
| Raylib-cs | 3.5 | [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)) | https://github.com/ChrisDill/Raylib-cs | | Raylib-cs | 3.5 | [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)) | https://github.com/ChrisDill/Raylib-cs |
| raylib-cppsharp | 2.5 | [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)) | https://github.com/phxvyper/raylib-cppsharp | | raylib-cppsharp | 2.5 | [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language)) | https://github.com/phxvyper/raylib-cppsharp |
| raylib-boo | 3.5 | [Boo](http://boo-language.github.io/) | https://github.com/Rabios/raylib-boo | | raylib-boo | 3.7 | [Boo](http://boo-language.github.io/) | https://github.com/Rabios/raylib-boo |
| RaylibFS | 2.5 | [F#](https://fsharp.org/) | https://github.com/dallinbeutler/RaylibFS | | RaylibFS | 2.5 | [F#](https://fsharp.org/) | https://github.com/dallinbeutler/RaylibFS |
| raylib_d | 2.5 | [D](https://dlang.org/) | https://github.com/Sepheus/raylib_d | | raylib_d | 2.5 | [D](https://dlang.org/) | https://github.com/Sepheus/raylib_d |
| raylib-d | 3.0 | [D](https://dlang.org/) | https://github.com/onroundit/raylib-d | | raylib-d | 3.0 | [D](https://dlang.org/) | https://github.com/onroundit/raylib-d |
@ -24,23 +24,23 @@ Here it is a list with the ones I'm aware of:
| raylib-lua | 1.7 | [Lua](http://www.lua.org/) | https://github.com/raysan5/raylib-lua | | raylib-lua | 1.7 | [Lua](http://www.lua.org/) | https://github.com/raysan5/raylib-lua |
| raylib-lua-ffi | 2.0 | [Lua](http://www.lua.org/) | https://github.com/raysan5/raylib/issues/693 | | raylib-lua-ffi | 2.0 | [Lua](http://www.lua.org/) | https://github.com/raysan5/raylib/issues/693 |
| raylib-lua-sol | 2.5 | [Lua](http://www.lua.org/) | https://github.com/RobLoach/raylib-lua-sol | | raylib-lua-sol | 2.5 | [Lua](http://www.lua.org/) | https://github.com/RobLoach/raylib-lua-sol |
| raylib-lua | 3.5 | [Lua](http://www.lua.org/) | https://github.com/TSnake41/raylib-lua | | raylib-lua | 3.7 | [Lua](http://www.lua.org/) | https://github.com/TSnake41/raylib-lua |
| raylib-luamore | 3.0 | [Lua](http://www.lua.org/) | https://github.com/HDPLocust/raylib-luamore | | raylib-luamore | 3.0 | [Lua](http://www.lua.org/) | https://github.com/HDPLocust/raylib-luamore |
| raylua | 3.5 | [Lua](http://www.lua.org/) | https://github.com/Rabios/raylua | | raylua | 3.7 | [Lua](http://www.lua.org/) | https://github.com/Rabios/raylua |
| LuaJIT-Raylib | 2.6 | [Lua](http://www.lua.org/) | https://github.com/Bambofy/LuaJIT-Raylib | | LuaJIT-Raylib | 2.6 | [Lua](http://www.lua.org/) | https://github.com/Bambofy/LuaJIT-Raylib |
| raylib-nelua | 3.0 | [Nelua](https://nelua.io/) | https://github.com/Andre-LA/raylib-nelua | | raylib-nelua | 3.0 | [Nelua](https://nelua.io/) | https://github.com/Andre-LA/raylib-nelua |
| raylib-Nim | 1.7 | [Nim](https://nim-lang.org/) | https://gitlab.com/define-private-public/raylib-Nim | | raylib-Nim | 1.7 | [Nim](https://nim-lang.org/) | https://gitlab.com/define-private-public/raylib-Nim |
| raylib-nim | 2.0 | [Nim](https://nim-lang.org/) | https://github.com/Skrylar/raylib-nim | | raylib-nim | 2.0 | [Nim](https://nim-lang.org/) | https://github.com/Skrylar/raylib-nim |
| raylib-Forever | 3.1-dev | [Nim](https://nim-lang.org/) | https://github.com/Guevara-chan/Raylib-Forever | | raylib-Forever | 3.1-dev | [Nim](https://nim-lang.org/) | https://github.com/Guevara-chan/Raylib-Forever |
| nim-raylib | 3.1-dev | [Nim](https://nim-lang.org/) | https://github.com/tomc1998/nim-raylib | | nim-raylib | 3.1-dev | [Nim](https://nim-lang.org/) | https://github.com/tomc1998/nim-raylib |
| NimraylibNow! | 3.5-dev | [Nim](https://nim-lang.org/) | https://github.com/greenfork/nimraylib_now | | NimraylibNow! | 3.7 | [Nim](https://nim-lang.org/) | https://github.com/greenfork/nimraylib_now |
| raylib-haskell | 2.0 | [Haskell](https://www.haskell.org/) | https://github.com/DevJac/raylib-haskell | | raylib-haskell | 2.0 | [Haskell](https://www.haskell.org/) | https://github.com/DevJac/raylib-haskell |
| raylib-cr | 2.5-dev | [Crystal](https://crystal-lang.org/) | https://github.com/AregevDev/raylib-cr | | raylib-cr | 2.5-dev | [Crystal](https://crystal-lang.org/) | https://github.com/AregevDev/raylib-cr |
| cray | 1.8 | [Crystal](https://crystal-lang.org/) | https://gitlab.com/Zatherz/cray | | cray | 1.8 | [Crystal](https://crystal-lang.org/) | https://gitlab.com/Zatherz/cray |
| raylib.cr | 2.0 | [Crystal](https://crystal-lang.org/) | https://github.com/sam0x17/raylib.cr | | raylib.cr | 2.0 | [Crystal](https://crystal-lang.org/) | https://github.com/sam0x17/raylib.cr |
| raylib-pascal | 2.0 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/drezgames/raylib-pascal | | raylib-pascal | 2.0 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/drezgames/raylib-pascal |
| raylib-pas | 3.0 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/tazdij/raylib-pas | | raylib-pas | 3.0 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/tazdij/raylib-pas |
| Ray4Laz | 3.5 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/GuvaCode/Ray4Laz | | Ray4Laz | 3.7 | [Pascal](https://en.wikipedia.org/wiki/Pascal_(programming_language)) | https://github.com/GuvaCode/Ray4Laz |
| Graphics-Raylib | 1.4 | [Perl](https://www.perl.org/) | https://github.com/athreef/Graphics-Raylib | | Graphics-Raylib | 1.4 | [Perl](https://www.perl.org/) | https://github.com/athreef/Graphics-Raylib |
| raylib-ruby-ffi | 2.0 | [Ruby](https://www.ruby-lang.org/en/) | https://github.com/D3nX/raylib-ruby-ffi | | raylib-ruby-ffi | 2.0 | [Ruby](https://www.ruby-lang.org/en/) | https://github.com/D3nX/raylib-ruby-ffi |
| raylib-ruby | 2.6 | [Ruby](https://www.ruby-lang.org/en/) | https://github.com/a0/raylib-ruby | | raylib-ruby | 2.6 | [Ruby](https://www.ruby-lang.org/en/) | https://github.com/a0/raylib-ruby |
@ -70,7 +70,7 @@ Here it is a list with the ones I'm aware of:
| raylib-chibi | 2.5 | [Chibi-Scheme](https://github.com/ashinn/chibi-scheme) | https://github.com/VincentToups/raylib-chibi | | raylib-chibi | 2.5 | [Chibi-Scheme](https://github.com/ashinn/chibi-scheme) | https://github.com/VincentToups/raylib-chibi |
| raylib-gambit-scheme | 3.1-dev | [Gambit Scheme](https://github.com/gambit/gambit) | https://github.com/georgjz/raylib-gambit-scheme | | raylib-gambit-scheme | 3.1-dev | [Gambit Scheme](https://github.com/gambit/gambit) | https://github.com/georgjz/raylib-gambit-scheme |
| Euraylib | 3.0 | [Euphoria](https://openeuphoria.org/) | https://github.com/gAndy50/Euraylib | | Euraylib | 3.0 | [Euphoria](https://openeuphoria.org/) | https://github.com/gAndy50/Euraylib |
| raylib-wren | 3.0 | [Wren](http://wren.io/) | https://github.com/TSnake41/raylib-wren | | raylib-wren | 3.7 | [Wren](http://wren.io/) | https://github.com/TSnake41/raylib-wren |
| raylib-odin | 3.0 | [Odin](https://odin-lang.org/) | https://github.com/kevinw/raylib-odin | | raylib-odin | 3.0 | [Odin](https://odin-lang.org/) | https://github.com/kevinw/raylib-odin |
| raylib-zig | 3.0 | [Zig](https://ziglang.org/) | https://github.com/Not-Nik/raylib-zig | | raylib-zig | 3.0 | [Zig](https://ziglang.org/) | https://github.com/Not-Nik/raylib-zig |
| raylib-jai | 3.1-dev | [Jai](https://github.com/BSVino/JaiPrimer/blob/master/JaiPrimer.md) | https://github.com/kevinw/raylib-jai | | raylib-jai | 3.1-dev | [Jai](https://github.com/BSVino/JaiPrimer/blob/master/JaiPrimer.md) | https://github.com/kevinw/raylib-jai |
@ -80,7 +80,7 @@ Here it is a list with the ones I'm aware of:
| raykit | ? | [Kit](https://www.kitlang.org/) | https://github.com/Gamerfiend/raykit | | raykit | ? | [Kit](https://www.kitlang.org/) | https://github.com/Gamerfiend/raykit |
| vraylib | 3.5 | [V](https://vlang.io/) | https://github.com/waotzi/vraylib | | vraylib | 3.5 | [V](https://vlang.io/) | https://github.com/waotzi/vraylib |
| ray.mod | 3.0 | [BlitzMax](https://blitzmax.org/) | https://github.com/bmx-ng/ray.mod | | ray.mod | 3.0 | [BlitzMax](https://blitzmax.org/) | https://github.com/bmx-ng/ray.mod |
| ray-ocaml | 3.0 | [OCaml](https://ocaml.org/) | https://github.com/tjammer/raylib-ocaml | | ray-ocaml | 3.5 | [OCaml](https://ocaml.org/) | https://github.com/tjammer/raylib-ocaml |
| raylib-mosaic | 3.0 | [Mosaic](https://github.com/sal55/langs/tree/master/Mosaic) | https://github.com/pluckyporcupine/raylib-mosaic | | raylib-mosaic | 3.0 | [Mosaic](https://github.com/sal55/langs/tree/master/Mosaic) | https://github.com/pluckyporcupine/raylib-mosaic |
| raylib-xdpw | 2.6 | [XD Pascal](https://github.com/vtereshkov/xdpw) | https://github.com/vtereshkov/raylib-xdpw | | raylib-xdpw | 2.6 | [XD Pascal](https://github.com/vtereshkov/xdpw) | https://github.com/vtereshkov/raylib-xdpw |
| raylib-carp | 3.0 | [Carp](https://github.com/carp-lang/Carp) | https://github.com/pluckyporcupine/raylib-carp | | raylib-carp | 3.0 | [Carp](https://github.com/carp-lang/Carp) | https://github.com/pluckyporcupine/raylib-carp |
@ -89,10 +89,11 @@ Here it is a list with the ones I'm aware of:
| raylib-smallBasic | 3.1-dev | [SmallBASIC](https://github.com/smallbasic/SmallBASIC) | https://github.com/smallbasic/smallbasic.plugins/tree/master/raylib | | raylib-smallBasic | 3.1-dev | [SmallBASIC](https://github.com/smallbasic/SmallBASIC) | https://github.com/smallbasic/smallbasic.plugins/tree/master/raylib |
| raylib-ats2 | 3.0 | [ATS2](http://www.ats-lang.org/) | https://github.com/mephistopheles-8/raylib-ats2 | | raylib-ats2 | 3.0 | [ATS2](http://www.ats-lang.org/) | https://github.com/mephistopheles-8/raylib-ats2 |
| raylib-beef | 3.0 | [Beef](https://www.beeflang.org/) | https://github.com/M0n7y5/raylib-beef | | raylib-beef | 3.0 | [Beef](https://www.beeflang.org/) | https://github.com/M0n7y5/raylib-beef |
| raylib-swift | 3.5 | [Swift](https://swift.org/) | https://github.com/conifer-dev/raylib-swift |
| raylib-never | 3.0 | [Never](https://github.com/never-lang/never) | https://github.com/never-lang/raylib-never | | raylib-never | 3.0 | [Never](https://github.com/never-lang/never) | https://github.com/never-lang/raylib-never |
| raylib.cbl | 2.0 | [COBOL](https://en.wikipedia.org/wiki/COBOL) | *[code examples](https://github.com/Martinfx/Cobol/tree/master/OpenCobol/Games/raylib)* | | hb-raylib | 3.5 | [Harbour](https://harbour.github.io) | https://github.com/MarcosLeonardoMendezGerencir/hb-raylib |
| Relib | 3.5 | [ReCT](https://github.com/RedCubeDev-ByteSpace/ReCT) | https://github.com/RedCubeDev-ByteSpace/Relib | | Relib | 3.5 | [ReCT](https://github.com/RedCubeDev-ByteSpace/ReCT) | https://github.com/RedCubeDev-ByteSpace/Relib |
| Harbour | 3.5 | [Harbour](https://harbour.github.io) | https://github.com/MarcosLeonardoMendezGerencir/hb-raylib | | raylib.cbl | 2.0 | [COBOL](https://en.wikipedia.org/wiki/COBOL) | *[code examples](https://github.com/Martinfx/Cobol/tree/master/OpenCobol/Games/raylib)* |
Missing some language? Feel free to create a new binding! :) Missing some language? Feel free to create a new binding! :)

View File

@ -1,26 +1,29 @@
changelog changelog
--------- ---------
Current Release: raylib 3.7.0 (xx April 2021) Current Release: raylib 3.7.0 (26 April 2021)
------------------------------------------------------------------------- -------------------------------------------------------------------------
Release: raylib 3.7 (xx April 2021) Release: raylib 3.7 (26 April 2021)
------------------------------------------------------------------------- -------------------------------------------------------------------------
KEY CHANGES: KEY CHANGES:
- [core] REDESIGNED: VR simulator -> fbo/shader exposed to user - [rlgl] REDESIGNED: Greater abstraction level, some functionality moved to core module
- [rlgl] REDESIGNED: More abstraction
- [rlgl] REVIEWED: Instancing and stereo rendering - [rlgl] REVIEWED: Instancing and stereo rendering
- [core] REDESIGNED: VR simulator, fbo/shader exposed to user
- [utils] ADDED: File access callbacks system - [utils] ADDED: File access callbacks system
- [*] RENAMED: enums values renamed for consistency - [models] ADDED: glTF animations support (#1551) by @object71
- [audio] ADDED: Music streaming support from memory (#1606) by @nezvers
- [*] RENAMED: enum types and enum values for consistency
Detailed changes: Detailed changes:
[core] ADDED: LoadVrStereoConfig() [core] ADDED: LoadVrStereoConfig()
[core] ADDED: UnloadVrStereoConfig() [core] ADDED: UnloadVrStereoConfig()
[core] ADDED: BeginVrStereoMode() [core] ADDED: BeginVrStereoMode()
[core] ADDED: EndVrStereoMode() [core] ADDED: EndVrStereoMode()
[core] ADDED: GetCurrentMonitor() [core] ADDED: GetCurrentMonitor() (#1485) by @object71
[core] ADDED: SetGamepadMappings(), update SDL_GameControllerDB [core] ADDED: SetGamepadMappings() (#1506)
[core] RENAMED: LoadShaderCode() to LoadShaderFromMemory() [core] RENAMED: struct Camera: camera.type to camera.projection
[core] RENAMED: LoadShaderCode() to LoadShaderFromMemory() (#1690)
[core] RENAMED: SetMatrixProjection() to rlSetMatrixProjection() [core] RENAMED: SetMatrixProjection() to rlSetMatrixProjection()
[core] RENAMED: SetMatrixModelview() to rlSetMatrixModelview() [core] RENAMED: SetMatrixModelview() to rlSetMatrixModelview()
[core] RENAMED: GetMatrixModelview() to rlGetMatrixModelview() [core] RENAMED: GetMatrixModelview() to rlGetMatrixModelview()
@ -31,33 +34,67 @@ Detailed changes:
[core] REMOVED: GetShapesTextureRec() [core] REMOVED: GetShapesTextureRec()
[core] REMOVED: GetMouseCursor() [core] REMOVED: GetMouseCursor()
[core] REMOVED: SetTraceLogExit() [core] REMOVED: SetTraceLogExit()
[core] REVIEWED: GetFileName() and GetDirectoryPath() (#1534) by @gilzoide
[core] REVIEWED: Wait() to support FreeBSD (#1618)
[core] REVIEWED: HighDPI support on macOS retina (#1510)
[core] REDESIGNED: GetFileExtension(), includes the .dot [core] REDESIGNED: GetFileExtension(), includes the .dot
[core] REDESIGNED: IsFileExtension(), includes the .dot [core] REDESIGNED: IsFileExtension(), includes the .dot
[shapes] REDESIGNED: void SetShapesTexture(Texture2D texture, Rectangle source); [core] REDESIGNED: Compresion API to use sdefl/sinfl libs
[shapes] ADDED: DrawLineBezierQuad() [rlgl] ADDED: SUPPORT_GL_DETAILS_INFO config flag
[rlgl] REMOVED: GenTexture*() functions (#721)
[rlgl] REVIEWED: rlLoadShaderDefault()
[rlgl] REDESIGNED: rlLoadExtensions(), more details exposed
[raymath] REVIEWED: QuaternionFromEuler() (#1651)
[raymath] REVIEWED: MatrixRotateZYX() (#1642)
[shapes] ADDED: DrawLineBezierQuad() (#1468) by @epsilon-phase
[shapes] ADDED: CheckCollisionLines()
[shapes] ADDED: CheckCollisionPointLine() by @mkupiec1
[shapes] REVIEWED: CheckCollisionPointTriangle() by @mkupiec1
[shapes] REDESIGNED: SetShapesTexture()
[shapes] REDESIGNED: DrawCircleSector(), to use float params [shapes] REDESIGNED: DrawCircleSector(), to use float params
[shapes] REDESIGNED: DrawCircleSectorLines(), to use float params [shapes] REDESIGNED: DrawCircleSectorLines(), to use float params
[shapes] REDESIGNED: DrawRing(), to use float params [shapes] REDESIGNED: DrawRing(), to use float params
[shapes] REDESIGNED: DrawRingLines(), to use float params [shapes] REDESIGNED: DrawRingLines(), to use float params
[shapes] ADDED: CheckCollisionLines() [textures] ADDED: DrawTexturePoly() and example (#1677) by @chriscamacho
[textures] ADDED: DrawTexturePoly() [textures] ADDED: UnloadImageColors() for allocs consistency
[textures] RENAMED: GetImageData() to LoadImageColors()
[textures] REVIEWED: ImageClearBackground() and ImageDrawRectangleRec() (#1487) by @JeffM2501
[textures] REVIEWED: DrawTexturePro() and DrawRectanglePro() transformations (#1632) by @ChrisDill
[text] REDESIGNED: DrawFPS() [text] REDESIGNED: DrawFPS()
[models] ADDED: UploadMesh() [models] ADDED: UploadMesh() (#1529)
[models] ADDED: UpdateMeshBuffer()
[models] ADDED: DrawMesh() [models] ADDED: DrawMesh()
[models] ADDED: DrawMeshInstanced() [models] ADDED: DrawMeshInstanced()
[models] ADDED: UnloadModelAnimations() [models] ADDED: UnloadModelAnimations() (#1648) by @object71
[models] ADDED: GenMeshDefault()
[models] REMOVED: DrawGizmo() [models] REMOVED: DrawGizmo()
[models] REMOVED: LoadMeshes() [models] REMOVED: LoadMeshes()
[models] REMOVED: MeshNormalsSmooth() [models] REMOVED: MeshNormalsSmooth()
[audio] ADDED: LoadMusicStreamFromMemory() [models] REVIEWED: DrawLine3D() (#1643)
[auido] REVIEWED: jar_xm library [audio] REVIEWED: Multichannel sound system (#1548)
[audio] REVIEWED: jar_xm library (#1701) by @jmorel33
[utils] ADDED: SetLoadFileDataCallback() [utils] ADDED: SetLoadFileDataCallback()
[utils] ADDED: SetSaveFileDataCallback() [utils] ADDED: SetSaveFileDataCallback()
[utils] ADDED: SetLoadFileTextCallback() [utils] ADDED: SetLoadFileTextCallback()
[utils] ADDED: SetSaveFileTextCallback() [utils] ADDED: SetSaveFileTextCallback()
[examples] ADDED: [examples] ADDED: text_draw_3d (#1689) by @Demizdor
[*] renamed some functions parameters for consistency [examples] ADDED: textures_poly (#1677) by @chriscamacho
[examples] ADDED: models_gltf_model (#1551) by @object71
[examples] RENAMED: shaders_rlgl_mesh_instanced to shaders_mesh_intancing
[examples] REDESIGNED: shaders_rlgl_mesh_instanced by @moliad
[examples] REDESIGNED: core_vr_simulator
[examples] REDESIGNED: models_yaw_pitch_roll
[build] ADDED: Config flag: SUPPORT_STANDARD_FILEIO
[build] ADDED: Config flag: SUPPORT_WINMM_HIGHRES_TIMER (#1641)
[build] ADDED: Config flag: SUPPORT_GL_DETAILS_INFO
[build] ADDED: Examples projects to VS2019 solution
[build] REVIEWED: Makefile to support PLATFORM_RPI (#1580)
[build] REVIEWED: Multiple typecast warnings by @JeffM2501
[build] REDESIGNED: VS2019 project build paths
[build] REDESIGNED: CMake build system by @object71
[*] RENAMED: Several functions parameters for consistency
[*] UPDATED: Multiple bindings to latest version
[*] UPDATED: All external libraries to latest versions
[*] Multiple code improvements and fixes by multiple contributors!
------------------------------------------------------------------------- -------------------------------------------------------------------------
Release: raylib 3.5 - 7th Anniversary Edition (25 December 2020) Release: raylib 3.5 - 7th Anniversary Edition (25 December 2020)

View File

@ -37,15 +37,11 @@ cmake_dependent_option(SUPPORT_SCREEN_CAPTURE "Allow automatic screen capture of
cmake_dependent_option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON CUSTOMIZE_BUILD ON) cmake_dependent_option(SUPPORT_GIF_RECORDING "Allow automatic gif recording of current screen pressing CTRL+F12, defined in KeyCallback()" ON CUSTOMIZE_BUILD ON)
cmake_dependent_option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" OFF CUSTOMIZE_BUILD OFF) cmake_dependent_option(SUPPORT_BUSY_WAIT_LOOP "Use busy wait loop for timing sync instead of a high-resolution timer" OFF CUSTOMIZE_BUILD OFF)
cmake_dependent_option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF CUSTOMIZE_BUILD OFF) cmake_dependent_option(SUPPORT_EVENTS_WAITING "Wait for events passively (sleeping while no events) instead of polling them actively every frame" OFF CUSTOMIZE_BUILD OFF)
cmake_dependent_option(SUPPORT_HIGH_DPI "Support high DPI displays" OFF CUSTOMIZE_BUILD OFF) cmake_dependent_option(SUPPORT_WINMM_HIGHRES_TIMER "Setting a higher resolution can improve the accuracy of time-out intervals in wait functions" OFF CUSTOMIZE_BUILD OFF)
cmake_dependent_option(SUPPORT_DATA_STORAGE "Support for persistent data storage" ON CUSTOMIZE_BUILD ON) cmake_dependent_option(SUPPORT_DATA_STORAGE "Support for persistent data storage" ON CUSTOMIZE_BUILD ON)
cmake_dependent_option(SUPPORT_COMPRESSION_API "Support for compression API" ON CUSTOMIZE_BUILD ON) cmake_dependent_option(SUPPORT_COMPRESSION_API "Support for compression API" ON CUSTOMIZE_BUILD ON)
# rlgl.h
cmake_dependent_option(SUPPORT_VR_SIMULATOR "Support VR simulation functionality (stereo rendering)" ON CUSTOMIZE_BUILD ON)
# shapes.c # shapes.c
cmake_dependent_option(SUPPORT_FONT_TEXTURE "Draw rectangle shapes using font texture white character instead of default white texture. Allows drawing rectangles and text with a single draw call, very useful for GUI systems!" ON CUSTOMIZE_BUILD ON)
cmake_dependent_option(SUPPORT_QUADS_DRAW_MODE "Use QUADS instead of TRIANGLES for drawing when possible. Some lines-based shapes could still use lines" ON CUSTOMIZE_BUILD ON) cmake_dependent_option(SUPPORT_QUADS_DRAW_MODE "Use QUADS instead of TRIANGLES for drawing when possible. Some lines-based shapes could still use lines" ON CUSTOMIZE_BUILD ON)
# textures.c # textures.c

View File

@ -4,22 +4,22 @@ Hello contributors! Welcome to raylib!
Do you enjoy raylib and want to contribute? Nice! You can help with the following points: Do you enjoy raylib and want to contribute? Nice! You can help with the following points:
- C programming - Can you write/review/test/improve the code? - `C programming` - Can you write/review/test/improve the code?
- Documentation/Tutorials/Example - Can you write some tutorial/example? - `Documentation/Tutorials/Example` - Can you write some tutorial/example?
- Porting to other platforms - Can you port and compile raylib on other systems? - `Porting to other platforms` - Can you port/adapt/compile raylib on other systems?
- Web Development - Can you help [with the website](https://github.com/raysan5/raylib.com)? - `Web Development` - Can you help [with the website](https://github.com/raysan5/raylib.com)?
- Testing - Can you find some bugs in raylib? - `Testing` - Can you find some bugs in raylib?
This document contains a set of guidelines to contribute to the project. These are mostly guidelines, not rules. This document contains a set of guidelines to contribute to the project. These are mostly guidelines, not rules.
Use your best judgement, and feel free to propose changes to this document in a pull request. Use your best judgement, and feel free to propose changes to this document in a pull request.
### raylib philosophy ### raylib philosophy
- raylib is a tool to enjoy videogames programming, every single function in raylib should be a tutorial on itself. - raylib is a tool to **ENJOY** videogames programming, every function in raylib is designed as a mini-tutorial on itself.
- raylib is **SIMPLE** and **EASY-TO-USE**, I tried to keep it compact with a small set of functions, if a function is too complex or is not clearly useful, better not including it. - raylib is **SIMPLE** and **EASY-TO-USE**, I tried to keep it compact with a small set of functions, if a function is too complex, better not including it.
- raylib is open source and free; educators and institutions can use this tool to **TEACH** videogames programming completely for free. - raylib is open source and free; educators and institutions can use this tool to **TEACH** videogames programming completely for free.
- raylib is collaborative; contribution of tutorials / code examples / bug fixes / code comments are highly appreciated. - raylib is collaborative; contribution of tutorials / code examples / bug fixes / code comments are highly appreciated.
- raylib's license (and its external libs respective licenses) allow using it on commercial projects. - raylib's license (and its external libs respective licenses) allow using raylib on commercial projects.
### Some interesting reads to start with ### Some interesting reads to start with
@ -40,9 +40,9 @@ to make it easier for students/users to read, write and understand code.
Source code is extensively commented for that purpose, raylib primary learning method is: Source code is extensively commented for that purpose, raylib primary learning method is:
> learn by reading code and examples > `Learn by reading code and examples`
For detailed information on building raylib and examples, please see [raylib Wiki](https://github.com/raysan5/raylib/wiki). For detailed information on building raylib and examples, please check [raylib Wiki](https://github.com/raysan5/raylib/wiki).
### Opening new Issues ### Opening new Issues
@ -68,69 +68,9 @@ To open new issue for raylib (bug, enhancement, discussion...), just try to foll
If you have any doubt, don't hesitate to [contact me](mailto:ray@raylib.com)!. If you have any doubt, don't hesitate to [contact me](mailto:ray@raylib.com)!.
You can write me a direct mail but you can also contact me on the following networks: You can write me a direct mail but you can also contact me on the following networks:
- [raylib reddit](https://www.reddit.com/r/raylib/) - A good place for discussions or to ask for help.
- [raylib Discord](https://discord.gg/raylib) - A direct communication channel for project discussions. - [raylib Discord](https://discord.gg/raylib) - A direct communication channel for project discussions.
- [raylib twitter](https://twitter.com/raysan5) - My personal twitter account, I usually post about raylib, you can send me PMs. - [raylib twitter](https://twitter.com/raysan5) - My personal twitter account, I usually post about raylib, you can send me PMs.
- [raylib reddit](https://www.reddit.com/r/raylib/) - A good place for discussions or to ask for help.
- [raylib web](http://www.raylib.com/) - On top-right corner there is a bunch of networks where you can find me. - [raylib web](http://www.raylib.com/) - On top-right corner there is a bunch of networks where you can find me.
Thank you very much for your time! :) Thank you very much for your time! :)
----
Here is a list of raylib contributors, these people have invested part of their time
contributing (in some way or another) to make the raylib project better. Huge thanks to all of them!
- [Zopokx](https://github.com/Zopokx) for testing the web.
- [Elendow](http://www.elendow.com) for testing and helping on web development.
- Victor Dual for implementing and testing 3D shapes functions.
- Marc Palau for implementing and testing 3D shapes functions and contribute on camera and gestures modules.
- Kevin Gato for improving texture internal formats support and helping on raygui development.
- Daniel Nicolas for improving texture internal formats support and helping on raygui development.
- Marc Agüera for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- Daniel Moreno for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- Daniel Gomez for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- [Sergio Martinez](https://github.com/anidealgift) for helping on raygui development and tools development (raygui_styler).
- [Victor Fisac](https://github.com/victorfisac) for developing physics raylib module (physac) and implementing PBR materials and lighting systems... among multiple other improvements and multiple tools and games.
- Albert Martos for helping on raygui and porting examples and game-templates to Android and HTML5.
- Ian Eito for helping on raygui and porting examples and game-templates to Android and HTML5.
- [procedural](https://github.com/procedural) for testing raylib on Linux, correcting some bugs and adding several mouse functions.
- [Chris Hemingway](https://github.com/cHemingway) for improving raylib on OSX build system.
- [Emanuele Petriglia](https://github.com/LelixSuper) for working on multiple GNU/Linux improvements and developing [TicTacToe](https://github.com/LelixSuper/TicTacToe) raylib game.
- [Joshua Reisenauer](https://github.com/kd7tck) for adding audio modules support (XM, MOD) and reviewing audio system.
- [Marcelo Paez](https://github.com/paezao) for helping on OSX High DPI display issue.
- [Ghassan Al-Mashareqa](https://github.com/ghassanpl) for an amazing contribution to raylib Lua module.
- [Teodor Stoenescu](https://github.com/teodor-stoenescu) for improvements on OBJ object loading.
- [RDR8](https://github.com/RDR8) for helping with Linux build improvements.
- [Saggi Mizrahi](https://github.com/ficoos) for multiple fixes on Linux and audio system.
- [Daniel Lemos](https://github.com/xspager) for fixing issues on Linux games building.
- [Joel Davis](https://github.com/joeld42) for adding raycast picking utilities and a [great example](https://github.com/raysan5/raylib/blob/master/examples/models/models_mesh_picking.c)
- [Richard Goodwin](https://github.com/AudioMorphology) for adding RPI touchscreen support.
- [Milan Nikolic](https://github.com/gen2brain) for adding Android build support with custom standalone toolchain.
- [Michael Vetter](https://github.com/jubalh) for improvements on build system and his work on Suse Linux package... and multiple fixes!
- [Wilhem Barbier](https://github.com/nounoursheureux) for adding Image generation functions, shaders work and some fixes.
- [Benjamin Summerton](https://github.com/define-private-public) for improving OSX building and his amazing work on CMake build sytem.
- [MartinFX](https://github.com/Martinfx) for adding compilation support for FreeBSD OS and derivatives.
- [Ahmad Fatoum](https://github.com/a3f) for implementing CI support for raylib (Travis and AppVeyor) and great improvements on build system.
- [SamNChiet](https://github.com/SamNChiet) for a greatly improved UWP input implementation.
- [David Reid](https://github.com/mackron) for a complete review of audio module to support his amazing miniaudio library.
- [Kai](https://github.com/questor) for multiple code reviews and improvements.
- [Max Danielsson](https://github.com/autious) for adding support for orthographic 3d camera projection
- [Lumaio](https://github.com/TheLumaio) for his great work on GBuffers and GetCollisionRayModel().
- [Jonas Daeyaert](https://github.com/culacant) for an amazing work on IQM animated models support.
- [Seth Archambault](https://github.com/SethArchambault) for the work on Android Gamepad support (SNES model).
- [D3nX](https://github.com/D3nX) for adding Code::Blocks project template.
- [Jak Barnes](https://github.com/Syphonx) for a great work on `rnet`, new raylib network module
- [Vlad Adrian](https://github.com/Demizdor) for an amazing work on Unicode support, new shapes functions and raygui.
- [Reece Mackie](https://github.com/Rover656) for a great work on improving UWP support
- [flashback-fx](flashback-fx) for improving easings library and example
- [Jorge A. Gomes](https://github.com/overdev) for adding nine-patch textures support and example
- [Berni8k](https://github.com/Berni8k) for improving Raspberry Pi input system, using evdev
- [Wilhem Barbier](https://github.com/wbrbr) for implementing glTF loading support and solving several issues
- [Marco Lizza](https://github.com/MarcoLizza) for improving logging system and multiple issues
- [Anata](https://github.com/anatagawa) for creating amazing examples and contributing with them
- [Narice](https://github.com/narice) made easings.h includable as standalone header
- [Eric J.](https://github.com/ProfJski) for shaders_eratosthenes example contribution
- [PompPenguin](https://github.com/PompPenguin) for reviewing 3rd person camera
- [Mohamed Shazan](https://github.com/msmshazan) for adding support for ANGLE graphics backend
Please, if I forget someone in this list, excuse me and send me a PR!

63
CONTRIBUTORS.md Normal file
View File

@ -0,0 +1,63 @@
### WARNING: This file is unmaintained! This list of contributors is uncomplete!
### Check CHANGELOG for some of the contributors details or just the official contributors list of the repo
---
Here is a list of raylib contributors, these people have invested part of their time
contributing (in some way or another) to make the raylib project better. Huge thanks to all of them!
- [Zopokx](https://github.com/Zopokx) for testing the web.
- [Elendow](http://www.elendow.com) for testing and helping on web development.
- Victor Dual for implementing and testing 3D shapes functions.
- Marc Palau for implementing and testing 3D shapes functions and contribute on camera and gestures modules.
- Kevin Gato for improving texture internal formats support and helping on raygui development.
- Daniel Nicolas for improving texture internal formats support and helping on raygui development.
- Marc Agüera for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- Daniel Moreno for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- Daniel Gomez for testing and using raylib on a real product ([Koala Seasons](http://www.koalaseasons.com))
- [Sergio Martinez](https://github.com/anidealgift) for helping on raygui development and tools development (raygui_styler).
- [Victor Fisac](https://github.com/victorfisac) for developing physics raylib module (physac) and implementing PBR materials and lighting systems... among multiple other improvements and multiple tools and games.
- Albert Martos for helping on raygui and porting examples and game-templates to Android and HTML5.
- Ian Eito for helping on raygui and porting examples and game-templates to Android and HTML5.
- [procedural](https://github.com/procedural) for testing raylib on Linux, correcting some bugs and adding several mouse functions.
- [Chris Hemingway](https://github.com/cHemingway) for improving raylib on OSX build system.
- [Emanuele Petriglia](https://github.com/LelixSuper) for working on multiple GNU/Linux improvements and developing [TicTacToe](https://github.com/LelixSuper/TicTacToe) raylib game.
- [Joshua Reisenauer](https://github.com/kd7tck) for adding audio modules support (XM, MOD) and reviewing audio system.
- [Marcelo Paez](https://github.com/paezao) for helping on OSX High DPI display issue.
- [Ghassan Al-Mashareqa](https://github.com/ghassanpl) for an amazing contribution to raylib Lua module.
- [Teodor Stoenescu](https://github.com/teodor-stoenescu) for improvements on OBJ object loading.
- [RDR8](https://github.com/RDR8) for helping with Linux build improvements.
- [Saggi Mizrahi](https://github.com/ficoos) for multiple fixes on Linux and audio system.
- [Daniel Lemos](https://github.com/xspager) for fixing issues on Linux games building.
- [Joel Davis](https://github.com/joeld42) for adding raycast picking utilities and a [great example](https://github.com/raysan5/raylib/blob/master/examples/models/models_mesh_picking.c)
- [Richard Goodwin](https://github.com/AudioMorphology) for adding RPI touchscreen support.
- [Milan Nikolic](https://github.com/gen2brain) for adding Android build support with custom standalone toolchain.
- [Michael Vetter](https://github.com/jubalh) for improvements on build system and his work on Suse Linux package... and multiple fixes!
- [Wilhem Barbier](https://github.com/nounoursheureux) for adding Image generation functions, shaders work and some fixes.
- [Benjamin Summerton](https://github.com/define-private-public) for improving OSX building and his amazing work on CMake build sytem.
- [MartinFX](https://github.com/Martinfx) for adding compilation support for FreeBSD OS and derivatives.
- [Ahmad Fatoum](https://github.com/a3f) for implementing CI support for raylib (Travis and AppVeyor) and great improvements on build system.
- [SamNChiet](https://github.com/SamNChiet) for a greatly improved UWP input implementation.
- [David Reid](https://github.com/mackron) for a complete review of audio module to support his amazing miniaudio library.
- [Kai](https://github.com/questor) for multiple code reviews and improvements.
- [Max Danielsson](https://github.com/autious) for adding support for orthographic 3d camera projection
- [Lumaio](https://github.com/TheLumaio) for his great work on GBuffers and GetCollisionRayModel().
- [Jonas Daeyaert](https://github.com/culacant) for an amazing work on IQM animated models support.
- [Seth Archambault](https://github.com/SethArchambault) for the work on Android Gamepad support (SNES model).
- [D3nX](https://github.com/D3nX) for adding Code::Blocks project template.
- [Jak Barnes](https://github.com/Syphonx) for a great work on `rnet`, new raylib network module
- [Vlad Adrian](https://github.com/Demizdor) for an amazing work on Unicode support, new shapes functions and raygui.
- [Reece Mackie](https://github.com/Rover656) for a great work on improving UWP support
- [flashback-fx](flashback-fx) for improving easings library and example
- [Jorge A. Gomes](https://github.com/overdev) for adding nine-patch textures support and example
- [Berni8k](https://github.com/Berni8k) for improving Raspberry Pi input system, using evdev
- [Wilhem Barbier](https://github.com/wbrbr) for implementing glTF loading support and solving several issues
- [Marco Lizza](https://github.com/MarcoLizza) for improving logging system and multiple issues
- [Anata](https://github.com/anatagawa) for creating amazing examples and contributing with them
- [Narice](https://github.com/narice) made easings.h includable as standalone header
- [Eric J.](https://github.com/ProfJski) for shaders_eratosthenes example contribution
- [PompPenguin](https://github.com/PompPenguin) for reviewing 3rd person camera
- [Mohamed Shazan](https://github.com/msmshazan) for adding support for ANGLE graphics backend
Please, if I forget someone in this list, excuse me and send me a PR!

View File

@ -291,3 +291,34 @@ Here the list with some highlights for `raylib 3.5`.
A part of those changes, many new functions have been added, some redundant functions removed and many functions have been reviewed for consistency with the full API (function name, parameters name and order, code formatting...). Again, this release represents is a **great improvement for raylib and marks the way forward** for the library. Make sure to check [CHANGELOG](CHANGELOG) for details! Hope you enjoy it! A part of those changes, many new functions have been added, some redundant functions removed and many functions have been reviewed for consistency with the full API (function name, parameters name and order, code formatting...). Again, this release represents is a **great improvement for raylib and marks the way forward** for the library. Make sure to check [CHANGELOG](CHANGELOG) for details! Hope you enjoy it!
Happy holidays! :) Happy holidays! :)
notes on raylib 3.7
-------------------
April 2021, it's been about 4 months since last raylib release and here it is already a new one, this time with a bunch of internal redesigns and improvements. Surprisingly, on April the 8th I was awarded for a second time with the [Google Open Source Peer Bonus Award](https://opensource.googleblog.com/2021/04/announcing-first-group-of-google-open-source-peer-bonus-winners.html) for my contribution to open source world with raylib and it seems the library is getting some traction, what a better moment for a new release? Let's see what can be found in this new version:
Let's start with some numbers:
- **+100** closed issues (for a TOTAL of **+900**!)
- **+400** commits since previous RELEASE
- **+50** functions ADDED (**+30** of them to rlgl API)
- **+30** functions REVIEWED/REDESIGNED
- **+40** new contributors (for a TOTAL of **+210**!)
Highlights for `raylib 3.7`:
- **REDESIGNED: `rlgl` module for greater abstraction level**. This suppose an **important change in raylib architecture**, now `rlgl` functionality is self-contained in the module and used by higher-level layers (specially by `core` module), those upper layers are the ones that expose functionality to the main API when required, for example the `Shaders`, `Mesh` and `Materials` functionality. Multiple `rlgl` functions have been renamed for consistency, in this case, following the `rl*()` prefix convention. Functions have also been reorganized internally by categories and `GenTexture*()` functions have been removed from the library and moved to [`models_material_pbr`](https://github.com/raysan5/raylib/blob/master/examples/models/models_material_pbr.c) example.
- **REDESIGNED: VR simulator and stereo rendering mechanism**. A **brand new API** has been added, more comprehensive and better integrated with raylib, the **new stereo rendering** can be combined with `RenderTexture` and `Shader` API allowing the user to **manage fbo and distortion shader directly**. Also, the new rendering mechanism supports **instancing on stereo rendering**! Check the updated [`core_vr_simulator`](https://github.com/raysan5/raylib/blob/master/examples/core/core_vr_simulator.c) example for reference!
- **ADDED: New file access callbacks system**. Several new callback functions have been added to the API to allow custom file loaders. A [nice example](https://github.com/RobLoach/raylib-physfs) it's the **raylib integration with a virtual file system** [PhysFS](https://icculus.org/physfs/).
- **ADDED: glTF animations support**. glTF is the preferred models file format to be used with raylib and along the addition of a models animation API on latest raylib versions, now animations support for glTF format has come to raylib, thanks for this great contribution to [Hristo Stamenov](@object71)
- **ADDED: Music streaming support from memory**. raylib has been adding the `Load*FromMemory()` option to all its supported file formats but **music streaming** was not supported yet... until now. Thanks to this great contribution by [Agnis "NeZvērs" Aldiņš](@nezvers), now raylib supports music streamming from memory data for all supported file formats: WAV, OGG, MP3, FLAC, XM and MOD.
- **RENAMED: enums values for consistency**. Most raylib enums names and values names have been renamed for consistency, now all value names start with the type of data they represent. It increases clarity and readability when using those values and also **improves overall library consistency**.
Beside those key changes, many functions have been reviewed with improvements and bug fixes, many of them contributed by the community! Thanks! And again, this release sets a **new milestone for raylib library**. Make sure to check [CHANGELOG](CHANGELOG) for detailed list of changes! Hope you enjoy this new raylib installment!
Happy **gamedev/tools/graphics** programming! :)

View File

@ -1,4 +1,4 @@
<img align="left" src="https://github.com/raysan5/raylib/blob/master/logo/raylib_256x256.png" width=256> <img align="left" src="https://github.com/raysan5/raylib/blob/master/logo/raylib_logo_animation.gif" width="288px">
**raylib is a simple and easy-to-use library to enjoy videogames programming.** **raylib is a simple and easy-to-use library to enjoy videogames programming.**
@ -8,11 +8,13 @@ raylib is highly inspired by Borland BGI graphics lib and by XNA framework and i
Ready to learn? Jump to [code examples!](http://www.raylib.com/examples.html) Ready to learn? Jump to [code examples!](http://www.raylib.com/examples.html)
---
<br> <br>
[![GitHub contributors](https://img.shields.io/github/contributors/raysan5/raylib)](https://github.com/raysan5/raylib/graphs/contributors) [![GitHub contributors](https://img.shields.io/github/contributors/raysan5/raylib)](https://github.com/raysan5/raylib/graphs/contributors)
[![GitHub All Releases](https://img.shields.io/github/downloads/raysan5/raylib/total)](https://github.com/raysan5/raylib/releases) [![GitHub All Releases](https://img.shields.io/github/downloads/raysan5/raylib/total)](https://github.com/raysan5/raylib/releases)
[![GitHub commits since tagged version](https://img.shields.io/github/commits-since/raysan5/raylib/3.5.0)](https://github.com/raysan5/raylib/commits/master) [![GitHub commits since tagged version](https://img.shields.io/github/commits-since/raysan5/raylib/3.7.0)](https://github.com/raysan5/raylib/commits/master)
[![License](https://img.shields.io/badge/license-zlib%2Flibpng-blue.svg)](LICENSE) [![License](https://img.shields.io/badge/license-zlib%2Flibpng-blue.svg)](LICENSE)
[![Chat on Discord](https://img.shields.io/discord/426912293134270465.svg?logo=discord)](https://discord.gg/raylib) [![Chat on Discord](https://img.shields.io/discord/426912293134270465.svg?logo=discord)](https://discord.gg/raylib)
@ -25,41 +27,56 @@ Ready to learn? Jump to [code examples!](http://www.raylib.com/examples.html)
[![macOS](https://github.com/raysan5/raylib/workflows/macOS/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AmacOS) [![macOS](https://github.com/raysan5/raylib/workflows/macOS/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AmacOS)
[![Android](https://github.com/raysan5/raylib/workflows/Android/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AAndroid) [![Android](https://github.com/raysan5/raylib/workflows/Android/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AAndroid)
[![WebAssembly](https://github.com/raysan5/raylib/workflows/WebAssembly/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AWebAssembly) [![WebAssembly](https://github.com/raysan5/raylib/workflows/WebAssembly/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3AWebAssembly)
[![CMakeBuilds](https://github.com/raysan5/raylib/workflows/CMakeBuilds/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3ACMakeBuilds) [![CMakeBuilds](https://github.com/raysan5/raylib/workflows/CMakeBuilds/badge.svg)](https://github.com/raysan5/raylib/actions?query=workflow%3ACMakeBuilds)
[![Windows Examples](https://github.com/raysan5/raylib/actions/workflows/windows_examples.yml/badge.svg)](https://github.com/raysan5/raylib/actions/workflows/windows_examples.yml)
[![Linux Examples](https://github.com/raysan5/raylib/actions/workflows/linux_examples.yml/badge.svg)](https://github.com/raysan5/raylib/actions/workflows/linux_examples.yml)
features features
-------- --------
- **NO external dependencies**, all required libraries are bundled into raylib - **NO external dependencies**, all required libraries are [bundled into raylib](https://github.com/raysan5/raylib/tree/master/src/external)
- Multiple platforms supported: **Windows, Linux, MacOS, RPI, Android, HTML5... and more!** - Multiple platforms supported: **Windows, Linux, MacOS, RPI, Android, HTML5... and more!**
- Written in plain C code (C99) in PascalCase/camelCase notation - Written in plain C code (C99) in PascalCase/camelCase notation
- Hardware accelerated with OpenGL (**1.1, 2.1, 3.3 or ES 2.0**) - Hardware accelerated with OpenGL (**1.1, 2.1, 3.3 or ES 2.0**)
- **Unique OpenGL abstraction layer** (usable as standalone module): [rlgl](https://github.com/raysan5/raylib/blob/master/src/rlgl.h) - **Unique OpenGL abstraction layer** (usable as standalone module): [rlgl](https://github.com/raysan5/raylib/blob/master/src/rlgl.h)
- Multiple **Fonts** formats supported (TTF, XNA fonts, AngelCode fonts) - Multiple **Fonts** formats supported (TTF, XNA fonts, AngelCode fonts)
- Outstanding texture formats support, including compressed formats (DXT, ETC, ASTC) - Multiple texture formats supported, including **compressed formats** (DXT, ETC, ASTC)
- **Full 3D support**, including 3D Shapes, Models, Billboards, Heightmaps and more! - **Full 3D support**, including 3D Shapes, Models, Billboards, Heightmaps and more!
- Flexible Materials system, supporting classic maps and **PBR maps** - Flexible Materials system, supporting classic maps and **PBR maps**
- **Animated 3D models** supported (skeletal bones animation) - **Animated 3D models** supported (skeletal bones animation) (IQM, glTF)
- Shaders support, including model and **postprocessing** shaders. - Shaders support, including model and **postprocessing** shaders.
- **Powerful math module** for Vector, Matrix and Quaternion operations: [raymath](https://github.com/raysan5/raylib/blob/master/src/raymath.h) - **Powerful math module** for Vector, Matrix and Quaternion operations: [raymath](https://github.com/raysan5/raylib/blob/master/src/raymath.h)
- Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, XM, MOD) - Audio loading and playing with streaming support (WAV, OGG, MP3, FLAC, XM, MOD)
- **VR stereo rendering** support with configurable HMD device parameters - **VR stereo rendering** support with configurable HMD device parameters
- Huge examples collection with [+120 code examples](https://github.com/raysan5/raylib/tree/master/examples)! - Huge examples collection with [+120 code examples](https://github.com/raysan5/raylib/tree/master/examples)!
- Bindings to [+50 programming languages](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)! - Bindings to [+50 programming languages](https://github.com/raysan5/raylib/blob/master/BINDINGS.md)!
- Free and open source. - **Free and open source**.
raylib uses on its [core](https://github.com/raysan5/raylib/blob/master/src/core.c) module the outstanding [GLFW3](http://www.glfw.org/) library, embedded in the form of [rglfw](https://github.com/raysan5/raylib/blob/master/src/rglfw.c) module, to avoid external dependencies. raylib uses internally some libraries for window/graphics/inputs management and also to support different fileformats loading, all those libraries are embedded with raylib and are available in [src/external](https://github.com/raysan5/raylib/tree/master/src/external) directory. Check [raylib dependencies](https://github.com/raysan5/raylib/wiki/raylib-dependencies) on [raylib Wiki](https://github.com/raysan5/raylib/wiki) for a detailed list.
raylib uses on its [raudio](https://github.com/raysan5/raylib/blob/master/src/raudio.c) module, the amazing [miniaudio](https://github.com/dr-soft/miniaudio) library to support multiple platforms and multiple audio backends. basic example
--------------
This is a basic raylib example, it creates a window and it draws the text `"Congrats! You created your first window!"` in the middle of the screen. Check this example [running live on web here](https://www.raylib.com/examples/web/core/loader.html?name=core_basic_window).
```c
#include "raylib.h"
raylib uses internally several single-file header-only libraries to support different fileformats loading and saving, all those libraries are embedded with raylib and available in [src/external](https://github.com/raysan5/raylib/tree/master/src/external) directory. Check [raylib Wiki](https://github.com/raysan5/raylib/wiki/raylib-dependencies) for a detailed list. int main(void)
{
InitWindow(800, 450, "raylib [core] example - basic window");
*On Android platform, `native_app_glue` module (provided by Android NDK) and native Android libraries are used to manage window/context, inputs and activity life cycle.* while (!WindowShouldClose())
{
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
EndDrawing();
}
*On Raspberry Pi 0,1,2,3 platform (native mode), `Videocore API` and `EGL` libraries are used for window/context management. Inputs are processed using `evdev` Linux libraries* CloseWindow();
*On Raspberry Pi 4 platform (native mode), `DRM subsystem` and `GBM API` libraries are used for window/context management. Inputs are processed using `evdev` Linux libraries* return 0;
}
*On Web platform, raylib uses `emscripten` provided libraries for several input events management, specially noticeable the touch events support.* ```
build and installation build and installation
---------------------- ----------------------
@ -88,7 +105,7 @@ You can download and install raylib using the [conan](https://conan.io) dependen
*The raylib recipe in conan is kept up to date by conan team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/conan-io/conan-center-index) on the conan-center-index repository.* *The raylib recipe in conan is kept up to date by conan team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/conan-io/conan-center-index) on the conan-center-index repository.*
#### Building raylib on multiple platforms #### Installing and building raylib on multiple platforms
[raylib Wiki](https://github.com/raysan5/raylib/wiki#development-platforms) contains detailed instructions on building and usage on multiple platforms. [raylib Wiki](https://github.com/raysan5/raylib/wiki#development-platforms) contains detailed instructions on building and usage on multiple platforms.
@ -103,7 +120,7 @@ You can download and install raylib using the [conan](https://conan.io) dependen
*Note that Wiki is open for edit, if you find some issue while building raylib for your target platform, feel free to edit the Wiki or open and issue related to it.* *Note that Wiki is open for edit, if you find some issue while building raylib for your target platform, feel free to edit the Wiki or open and issue related to it.*
#### Using raylib with multiple IDEs #### Setup raylib with multiple IDEs
raylib has been developed on Windows platform using [Notepad++](https://notepad-plus-plus.org/) and [MinGW GCC](http://mingw-w64.org/doku.php) compiler but it can be used with other IDEs on multiple platforms. raylib has been developed on Windows platform using [Notepad++](https://notepad-plus-plus.org/) and [MinGW GCC](http://mingw-w64.org/doku.php) compiler but it can be used with other IDEs on multiple platforms.
@ -111,18 +128,32 @@ raylib has been developed on Windows platform using [Notepad++](https://notepad-
*Note that there are lots of IDEs supported, some of the provided templates could require some review, please, if you find some issue with some template or you think they could be improved, feel free to send a PR or open a related issue.* *Note that there are lots of IDEs supported, some of the provided templates could require some review, please, if you find some issue with some template or you think they could be improved, feel free to send a PR or open a related issue.*
contact learning and docs
------- ------------------
* Webpage: [http://www.raylib.com](http://www.raylib.com) raylib is designed to be learned using [the examples](https://github.com/raysan5/raylib/tree/master/examples) as the main reference. There is no standard API documentation but there is a [**cheatsheet**](https://www.raylib.com/cheatsheet/cheatsheet.html) containing all the functions available on the library and a short description of each one of them, input parameters and result value names should be intuitive enough to understand how each function works.
* Discord: [https://discord.gg/raylib](https://discord.gg/raylib)
* Twitter: [http://www.twitter.com/raysan5](http://www.twitter.com/raysan5)
* Twitch: [http://www.twitch.tv/raysan5](http://www.twitch.tv/raysan5)
* Reddit: [https://www.reddit.com/r/raylib](https://www.reddit.com/r/raylib)
* Patreon: [https://www.patreon.com/raylib](https://www.patreon.com/raylib)
* YouTube: [https://www.youtube.com/channel/raylib](https://www.youtube.com/c/raylib)
If you are using raylib and enjoying it, please, join our [Discord server](https://discord.gg/raylib) and let us know! :) Some additional documentation about raylib design can be found in raylib GitHub Wiki. Here the more relevant links:
- [raylib cheatsheet](https://www.raylib.com/cheatsheet/cheatsheet.html)
- [raylib architecture](https://github.com/raysan5/raylib/wiki/raylib-architecture)
- [raylib library design](https://github.com/raysan5/raylib/wiki)
- [raylib examples collection](https://github.com/raysan5/raylib/tree/master/examples)
- [raylib games collection](https://github.com/raysan5/raylib-games)
contact and networks
---------------------
raylib is present in several networks and raylib community is growing everyday. If you are using raylib and enjoying it, feel free to join us in any of these networks. The most active network is our [Discord server](https://discord.gg/raylib)! :)
- Webpage: [http://www.raylib.com](http://www.raylib.com)
- Discord: [https://discord.gg/raylib](https://discord.gg/raylib)
- Twitter: [http://www.twitter.com/raysan5](http://www.twitter.com/raysan5)
- Twitch: [http://www.twitch.tv/raysan5](http://www.twitch.tv/raysan5)
- Reddit: [https://www.reddit.com/r/raylib](https://www.reddit.com/r/raylib)
- Patreon: [https://www.patreon.com/raylib](https://www.patreon.com/raylib)
- YouTube: [https://www.youtube.com/channel/raylib](https://www.youtube.com/c/raylib)
license license
------- -------

View File

@ -1,21 +1,25 @@
roadmap roadmap
------- -------
Here it is a wish-list with features and ideas to improve the library. Note that features listed here are quite high-level and could be long term additions for the library. Current version of raylib is complete and functional but there is a lot of room for improvement. Here it is a wish-list with features and ideas to improve the library. Note that features listed here are usually long term additions for the library. Current version of raylib is complete and functional but there is a lot of room for improvement.
[raylib source code](https://github.com/raysan5/raylib/tree/master/src) has some *TODO* marks around code with pending things to review and improve. Check also [GitHub Issues](https://github.com/raysan5/raylib/issues) for further details! Also note that [raylib source code](https://github.com/raysan5/raylib/tree/master/src) has multiple *TODO* comments around code with pending things to review or improve. Check also [GitHub Issues](https://github.com/raysan5/raylib/issues) for further details!
**raylib 3.x** There is also a [Discussions Wishlist](https://github.com/raysan5/raylib/discussions/1502) open to everyone, feel free to check and comment.
- [ ] Network module (UDP): `rnet` ([info](https://github.com/raysan5/raylib/issues/753))
- [ ] Custom raylib resource packer: `rres` ([info](https://github.com/raysan5/rres)) **raylib 4.0**
- [ ] Basic CPU/GPU stats system (memory, draws, time...) - [ ] Network module (UDP): `rnet` ([#753](https://github.com/raysan5/raylib/issues/753))
- [ ] Custom raylib resource packer: `rres` ([link](https://github.com/raysan5/rres))
- [ ] Basic CPU/GPU stats system (memory, draws, time...) ([#1295](https://github.com/raysan5/raylib/issues/1295))
- [ ] Software rendering backend (avoiding OpenGL) ([#1370](https://github.com/raysan5/raylib/issues/1370))
- [ ] Redesigned camera module (more flexible) ([#1143](https://github.com/raysan5/raylib/issues/1143))
- [x] Continuous Deployment using GitHub Actions - [x] Continuous Deployment using GitHub Actions
**raylib 3.0** **raylib 3.0**
- [x] Custom memory allocators support - [x] Custom memory allocators support
- [x] Global variables moved to global context - [x] Global variables moved to global context
- [x] Optimize data structures for pass-by-value - [x] Optimize data structures for pass-by-value
- [x] Trace log messages redesign ([info](https://github.com/raysan5/raylib/issues/1065)) - [x] Trace log messages redesign ([#1065](https://github.com/raysan5/raylib/issues/1065))
- [x] Continuous Integration using GitHub Actions - [x] Continuous Integration using GitHub Actions
**raylib 2.5** **raylib 2.5**

View File

@ -1,47 +1,57 @@
The following people has contributed with a generous donation to the raylib project. ## raylib GitHub Sponsors
## 🥇 Gold Contributors ### Current raylib GitHub Sponsors
... The following people is currently [**sponsoring raylib**](https://github.com/sponsors/raysan5) with a generous donation to allow improving and growing the project!
## 🥈 Silver Contributors Note that Sponsors donations vary between sponsors, I just decided not to make any distinction while listing them.
- Jonathan Johnson ([@ecton](https://github.com/ecton))
- Eric J. ([@ProfJski](https://github.com/ProfJski)) - Eric J. ([@ProfJski](https://github.com/ProfJski))
- Rudy Faile ([@rfaile313](https://github.com/rfaile313)) - https://rudyfaile.com/
- devdad ([@devdad](https://github.com/devdad)) - devdad ([@devdad](https://github.com/devdad))
- frithrah ([@frithrah](https://github.com/frithrah))
- Zach Geis ([@zacgeis](https://github.com/zacgeis)) - Zach Geis ([@zacgeis](https://github.com/zacgeis))
## 🥉 Bronze Contributors
- minirop ([@minirop](https://github.com/minirop)) - minirop ([@minirop](https://github.com/minirop))
- Daniel Gómez ([@Koocachookies](https://github.com/Koocachookies)) - Daniel Gómez ([@Koocachookies](https://github.com/Koocachookies))
- Sergio ([@anidealgift](https://github.com/anidealgift)) - Sergio ([@anidealgift](https://github.com/anidealgift))
- JFons ([@JFonS](https://github.com/JFonS))
- Marc Agüera ([@maguera93](https://github.com/maguera93)) - Marc Agüera ([@maguera93](https://github.com/maguera93))
- Pau Fernández ([@pauek](https://github.com/pauek)) - Pau Fernández ([@pauek](https://github.com/pauek))
- Jens Pitkänen ([@neonmoe](https://github.com/neonmoe))
- Snowminx ([@Gamerfiend](https://github.com/Gamerfiend)) - Snowminx ([@Gamerfiend](https://github.com/Gamerfiend))
- NimbusFox ([@NimbusFox](https://github.com/NimbusFox)) - NimbusFox ([@NimbusFox](https://github.com/NimbusFox))
- Robin Mattheussen ([@romatthe](https://github.com/romatthe)) - Robin Mattheussen ([@romatthe](https://github.com/romatthe))
- Rahul Nair ([@rahulunair](https://github.com/rahulunair))
- Grant Haywood ([@cinterloper](https://github.com/cinterloper)) - Grant Haywood ([@cinterloper](https://github.com/cinterloper))
- Terry Nguyen ([@terrehbyte](https://github.com/terrehbyte)) - Terry Nguyen ([@terrehbyte](https://github.com/terrehbyte))
- albatros-hmd ([@albatros-hmd](https://github.com/albatros-hmd))
- Benjamin Stigsen ([@BenStigsen](https://github.com/BenStigsen))
- Louis Johnson ([@louisgjohnson](https://github.com/louisgjohnson))
- Dani Martin ([@danimartin82](https://github.com/danimartin82))
- Tommi Sinivuo ([@TommiSinivuo](https://github.com/TommiSinivuo)) - Tommi Sinivuo ([@TommiSinivuo](https://github.com/TommiSinivuo))
- Joakim Wennergren ([@joakimwennergren](https://github.com/joakimwennergren))
- Richard Urbanec ([@Poryg1](https://github.com/Poryg1)) - Richard Urbanec ([@Poryg1](https://github.com/Poryg1))
- pmgl ([@pmgl](https://github.com/pmgl)) - pmgl ([@pmgl](https://github.com/pmgl))
- cob ([@majorcob](https://github.com/majorcob)) - cob ([@majorcob](https://github.com/majorcob))
- Samuel Batista ([@gamedevsam](https://github.com/gamedevsam)) - Samuel Batista ([@gamedevsam](https://github.com/gamedevsam))
- Merlyn Morgan-Graham ([@kavika13](https://github.com/kavika13))
- Toby4213 ([@Toby4213](https://github.com/Toby4213))
- linus ([@hochbaum](https://github.com/hochbaum))
### Past raylib GitHub Sponsors
The following people has **sponsored raylib** in the past, allowing the project to reach current amazing state.
- Jonathan Johnson ([@ecton](https://github.com/ecton))
- Rudy Faile ([@rfaile313](https://github.com/rfaile313)) - https://rudyfaile.com/
- frithrah ([@frithrah](https://github.com/frithrah))
- Jens Pitkänen ([@neonmoe](https://github.com/neonmoe))
- Rahul Nair ([@rahulunair](https://github.com/rahulunair))
- albatros-hmd ([@albatros-hmd](https://github.com/albatros-hmd))
- Benjamin Stigsen ([@BenStigsen](https://github.com/BenStigsen))
- Louis Johnson ([@louisgjohnson](https://github.com/louisgjohnson))
- Dani Martin ([@danimartin82](https://github.com/danimartin82))
- Joakim Wennergren ([@joakimwennergren](https://github.com/joakimwennergren))
- Alexandre Chêne ([@kooparse](https://github.com/kooparse)) - Alexandre Chêne ([@kooparse](https://github.com/kooparse))
- daddio69 ([@daddio69](https://github.com/daddio69)) - daddio69 ([@daddio69](https://github.com/daddio69))
- James Ghawaly ([@jghawaly](https://github.com/jghawaly)) - James Ghawaly ([@jghawaly](https://github.com/jghawaly))
- jack ([@Jack-Ji](https://github.com/Jack-Ji)) - jack ([@Jack-Ji](https://github.com/Jack-Ji))
- Merlyn Morgan-Graham ([@kavika13](https://github.com/kavika13)) - Guido Offermans ([@jghawaly](https://github.com/GuidoOffermans))
### Notes for Current/Past raylib Sponsor
- **If you are not on the list, feel free to send a PR to add you if desired.**
- **If you want your personal webpage listed along your GitHub account, feel free to send a PR to add it.**
- **If you prefer not to listed in this list, feel free to send a PR to remove it.**

View File

@ -73,7 +73,9 @@ elseif (${PLATFORM} MATCHES "DRM")
find_library(DRM drm) find_library(DRM drm)
find_library(GBM gbm) find_library(GBM gbm)
include_directories(/usr/include/libdrm) if (NOT CMAKE_CROSSCOMPILING)
include_directories(/usr/include/libdrm)
endif ()
set(LIBS_PRIVATE ${GLESV2} ${EGL} ${DRM} ${GBM} pthread m dl) set(LIBS_PRIVATE ${GLESV2} ${EGL} ${DRM} ${GBM} pthread m dl)
endif () endif ()
@ -102,4 +104,4 @@ set(LIBS_PRIVATE ${LIBS_PRIVATE} ${OPENAL_LIBRARY})
if (${PLATFORM} MATCHES "Desktop") if (${PLATFORM} MATCHES "Desktop")
set(LIBS_PRIVATE ${LIBS_PRIVATE} glfw) set(LIBS_PRIVATE ${LIBS_PRIVATE} glfw)
endif () endif ()

View File

@ -25,7 +25,7 @@
# Define required raylib variables # Define required raylib variables
PROJECT_NAME ?= raylib_examples PROJECT_NAME ?= raylib_examples
RAYLIB_VERSION ?= 3.5.0 RAYLIB_VERSION ?= 3.7.0
RAYLIB_PATH ?= .. RAYLIB_PATH ?= ..
# Define default options # Define default options
@ -308,10 +308,6 @@ ifeq ($(PLATFORM),PLATFORM_RPI)
LDFLAGS += -L/opt/vc/lib LDFLAGS += -L/opt/vc/lib
endif endif
ifeq ($(PLATFORM),PLATFORM_DRM)
LDFLAGS += -lGLESv2 -lEGL -ldrm -lgbm
endif
# Define any libraries required on linking # Define any libraries required on linking
# if you want to link libraries (libname.so or libname.a), use the -lname # if you want to link libraries (libname.so or libname.a), use the -lname
ifeq ($(PLATFORM),PLATFORM_DESKTOP) ifeq ($(PLATFORM),PLATFORM_DESKTOP)

View File

@ -42,56 +42,64 @@ else
endif endif
ifeq ($(ANDROID_ARCH),ARM) ifeq ($(ANDROID_ARCH),ARM)
ANDROID_ARCH_NAME = armeabi-v7a ANDROID_ARCH_NAME = armeabi-v7a
endif endif
ifeq ($(ANDROID_ARCH),ARM64) ifeq ($(ANDROID_ARCH),ARM64)
ANDROID_ARCH_NAME = arm64-v8a ANDROID_ARCH_NAME = arm64-v8a
endif endif
ifeq ($(ANDROID_ARCH),x86) ifeq ($(ANDROID_ARCH),x86)
ANDROID_ARCH_NAME = i686 ANDROID_ARCH_NAME = i686
endif endif
ifeq ($(ANDROID_ARCH),x86_64) ifeq ($(ANDROID_ARCH),x86_64)
ANDROID_ARCH_NAME = x86_64 ANDROID_ARCH_NAME = x86_64
endif endif
# Required path variables # Required path variables
# NOTE: JAVA_HOME must be set to JDK (using OpenJDK 13) # NOTE: JAVA_HOME must be set to JDK (using OpenJDK 13)
JAVA_HOME ?= C:/open-jdk JAVA_HOME ?= C:/open-jdk
ANDROID_HOME = C:/android-sdk ANDROID_HOME ?= C:/android-sdk
ANDROID_TOOLCHAIN = C:/android-ndk/toolchains/llvm/prebuilt/windows-x86_64 ANDROID_BUILD_TOOLS ?= $(ANDROID_HOME)/build-tools/29.0.3
ANDROID_BUILD_TOOLS = $(ANDROID_HOME)/build-tools/29.0.3
ANDROID_PLATFORM_TOOLS = $(ANDROID_HOME)/platform-tools ANDROID_PLATFORM_TOOLS = $(ANDROID_HOME)/platform-tools
# Android project configuration variables # Android project configuration variables
PROJECT_NAME ?= raylib_game PROJECT_NAME ?= raylib_game
PROJECT_LIBRARY_NAME ?= main PROJECT_LIBRARY_NAME ?= main
PROJECT_BUILD_PATH ?= android.$(PROJECT_NAME) PROJECT_BUILD_ID ?= android
PROJECT_BUILD_PATH ?= $(PROJECT_BUILD_ID).$(PROJECT_NAME)
PROJECT_RESOURCES_PATH ?= resources PROJECT_RESOURCES_PATH ?= resources
PROJECT_SOURCE_FILES ?= raylib_game.c PROJECT_SOURCE_FILES ?= raylib_game.c
NATIVE_APP_GLUE_PATH = $(ANDROID_NDK)/sources/android/native_app_glue
# Some source files are placed in directories, when compiling to some # Some source files are placed in directories, when compiling to some
# output directory other than source, that directory must pre-exist. # output directory other than source, that directory must pre-exist.
# Here we get a list of required folders that need to be created on # Here we get a list of required folders that need to be created on
# code output folder $(PROJECT_BUILD_PATH)\obj to avoid GCC errors. # code output folder $(PROJECT_BUILD_PATH)\obj to avoid GCC errors.
PROJECT_SOURCE_DIRS = $(sort $(dir $(PROJECT_SOURCE_FILES))) PROJECT_SOURCE_DIRS = $(sort $(dir $(PROJECT_SOURCE_FILES)))
# Android app configuration variables # Android app configuration variables
APP_LABEL_NAME ?= rGame APP_LABEL_NAME ?= rGame
APP_COMPANY_NAME ?= raylib APP_COMPANY_NAME ?= raylib
APP_PRODUCT_NAME ?= rgame APP_PRODUCT_NAME ?= rgame
APP_VERSION_CODE ?= 1 APP_VERSION_CODE ?= 1
APP_VERSION_NAME ?= 1.0 APP_VERSION_NAME ?= 1.0
APP_ICON_LDPI ?= $(RAYLIB_PATH)\logo\raylib_36x36.png APP_ICON_LDPI ?= $(RAYLIB_PATH)/logo/raylib_36x36.png
APP_ICON_MDPI ?= $(RAYLIB_PATH)\logo\raylib_48x48.png APP_ICON_MDPI ?= $(RAYLIB_PATH)/logo/raylib_48x48.png
APP_ICON_HDPI ?= $(RAYLIB_PATH)\logo\raylib_72x72.png APP_ICON_HDPI ?= $(RAYLIB_PATH)/logo/raylib_72x72.png
APP_SCREEN_ORIENTATION ?= landscape APP_SCREEN_ORIENTATION ?= landscape
APP_KEYSTORE_PASS ?= raylib APP_KEYSTORE_PASS ?= raylib
# Library type used for raylib: STATIC (.a) or SHARED (.so/.dll) # Library type used for raylib: STATIC (.a) or SHARED (.so/.dll)
RAYLIB_LIBTYPE ?= STATIC RAYLIB_LIBTYPE ?= STATIC
# Library path for libraylib.a/libraylib.so # Library path for libraylib.a/libraylib.so
RAYLIB_LIB_PATH = $(RAYLIB_PATH)\src RAYLIB_LIB_PATH = $(RAYLIB_PATH)/src
# Define copy command depending on OS
ifeq ($(OS),Windows_NT)
COPY_COMMAND ?= copy /Y
else
COPY_COMMAND ?= cp -f
endif
# Shared libs must be added to APK if required # Shared libs must be added to APK if required
# NOTE: Generated NativeLoader.java automatically load those libraries # NOTE: Generated NativeLoader.java automatically load those libraries
@ -108,6 +116,14 @@ ifeq ($(ANDROID_ARCH),ARM64)
CC = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android$(ANDROID_API_VERSION)-clang CC = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android$(ANDROID_API_VERSION)-clang
AR = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-ar AR = $(ANDROID_TOOLCHAIN)/bin/aarch64-linux-android-ar
endif endif
ifeq ($(ANDROID_ARCH),x86)
CC = $(ANDROID_TOOLCHAIN)/bin/i686-linux-android$(ANDROID_API_VERSION)-clang
AR = $(ANDROID_TOOLCHAIN)/bin/i686-linux-android-ar
endif
ifeq ($(ANDROID_ARCH),x86_64)
CC = $(ANDROID_TOOLCHAIN)/bin/x86_64-linux-android$(ANDROID_API_VERSION)-clang
AR = $(ANDROID_TOOLCHAIN)/bin/x86_64-linux-android-ar
endif
# Compiler flags for arquitecture # Compiler flags for arquitecture
ifeq ($(ANDROID_ARCH),ARM) ifeq ($(ANDROID_ARCH),ARM)
@ -124,7 +140,7 @@ CFLAGS += -Wall -Wa,--noexecstack -Wformat -Werror=format-security -no-canonical
CFLAGS += -DANDROID -DPLATFORM_ANDROID -D__ANDROID_API__=$(ANDROID_API_VERSION) CFLAGS += -DANDROID -DPLATFORM_ANDROID -D__ANDROID_API__=$(ANDROID_API_VERSION)
# Paths containing required header files # Paths containing required header files
INCLUDE_PATHS = -I. -I$(RAYLIB_PATH)/src -I$(RAYLIB_PATH)/src/external/android/native_app_glue INCLUDE_PATHS = -I. -I$(RAYLIB_PATH)/src -I$(NATIVE_APP_GLUE_PATH)
# Linker options # Linker options
LDFLAGS = -Wl,-soname,lib$(PROJECT_LIBRARY_NAME).so -Wl,--exclude-libs,libatomic.a LDFLAGS = -Wl,-soname,lib$(PROJECT_LIBRARY_NAME).so -Wl,--exclude-libs,libatomic.a
@ -154,13 +170,15 @@ all: create_temp_project_dirs \
compile_project_class \ compile_project_class \
compile_project_class_dex \ compile_project_class_dex \
create_project_apk_package \ create_project_apk_package \
sign_project_apk_package \ zipalign_project_apk_package \
zipalign_project_apk_package sign_project_apk_package
# Create required temp directories for APK building # Create required temp directories for APK building
create_temp_project_dirs: create_temp_project_dirs:
ifeq ($(OS),Windows_NT)
if not exist $(PROJECT_BUILD_PATH) mkdir $(PROJECT_BUILD_PATH) if not exist $(PROJECT_BUILD_PATH) mkdir $(PROJECT_BUILD_PATH)
if not exist $(PROJECT_BUILD_PATH)\obj mkdir $(PROJECT_BUILD_PATH)\obj if not exist $(PROJECT_BUILD_PATH)\obj mkdir $(PROJECT_BUILD_PATH)\obj
if not exist $(PROJECT_BUILD_PATH)\obj mkdir $(PROJECT_BUILD_PATH)\obj\src
if not exist $(PROJECT_BUILD_PATH)\src mkdir $(PROJECT_BUILD_PATH)\src if not exist $(PROJECT_BUILD_PATH)\src mkdir $(PROJECT_BUILD_PATH)\src
if not exist $(PROJECT_BUILD_PATH)\src\com mkdir $(PROJECT_BUILD_PATH)\src\com if not exist $(PROJECT_BUILD_PATH)\src\com mkdir $(PROJECT_BUILD_PATH)\src\com
if not exist $(PROJECT_BUILD_PATH)\src\com\$(APP_COMPANY_NAME) mkdir $(PROJECT_BUILD_PATH)\src\com\$(APP_COMPANY_NAME) if not exist $(PROJECT_BUILD_PATH)\src\com\$(APP_COMPANY_NAME) mkdir $(PROJECT_BUILD_PATH)\src\com\$(APP_COMPANY_NAME)
@ -176,36 +194,62 @@ create_temp_project_dirs:
if not exist $(PROJECT_BUILD_PATH)\assets mkdir $(PROJECT_BUILD_PATH)\assets if not exist $(PROJECT_BUILD_PATH)\assets mkdir $(PROJECT_BUILD_PATH)\assets
if not exist $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH) mkdir $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH) if not exist $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH) mkdir $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH)
if not exist $(PROJECT_BUILD_PATH)\obj\screens mkdir $(PROJECT_BUILD_PATH)\obj\screens if not exist $(PROJECT_BUILD_PATH)\obj\screens mkdir $(PROJECT_BUILD_PATH)\obj\screens
else
mkdir -p $(PROJECT_BUILD_PATH)
mkdir -p $(PROJECT_BUILD_PATH)/obj
mkdir -p $(PROJECT_BUILD_PATH)/obj/src
mkdir -p $(PROJECT_BUILD_PATH)/src
mkdir -p $(PROJECT_BUILD_PATH)/src/com
mkdir -p $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)
mkdir -p $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)
mkdir -p $(PROJECT_BUILD_PATH)/lib
mkdir -p $(PROJECT_BUILD_PATH)/lib/$(ANDROID_ARCH_NAME)
mkdir -p $(PROJECT_BUILD_PATH)/bin
mkdir -p $(PROJECT_BUILD_PATH)/res
mkdir -p $(PROJECT_BUILD_PATH)/res/drawable-ldpi
mkdir -p $(PROJECT_BUILD_PATH)/res/drawable-mdpi
mkdir -p $(PROJECT_BUILD_PATH)/res/drawable-hdpi
mkdir -p $(PROJECT_BUILD_PATH)/res/values
mkdir -p $(PROJECT_BUILD_PATH)/assets
mkdir -p $(PROJECT_BUILD_PATH)/assets/$(PROJECT_RESOURCES_PATH)
mkdir -p $(PROJECT_BUILD_PATH)/obj/screens
endif
$(foreach dir, $(PROJECT_SOURCE_DIRS), $(call create_dir, $(dir))) $(foreach dir, $(PROJECT_SOURCE_DIRS), $(call create_dir, $(dir)))
define create_dir define create_dir
if not exist $(PROJECT_BUILD_PATH)\obj\$(1) mkdir $(PROJECT_BUILD_PATH)\obj\$(1) mkdir -p $(PROJECT_BUILD_PATH)/obj/$(1)
endef endef
# Copy required shared libs for integration into APK # Copy required shared libs for integration into APK
# NOTE: If using shared libs they are loaded by generated NativeLoader.java # NOTE: If using shared libs they are loaded by generated NativeLoader.java
copy_project_required_libs: copy_project_required_libs:
ifeq ($(RAYLIB_LIBTYPE),SHARED) ifeq ($(RAYLIB_LIBTYPE),SHARED)
copy /Y $(RAYLIB_LIB_PATH)\libraylib.so $(PROJECT_BUILD_PATH)\lib\$(ANDROID_ARCH_NAME)\libraylib.so $(COPY_COMMAND) $(RAYLIB_LIB_PATH)/libraylib.so $(PROJECT_BUILD_PATH)/lib/$(ANDROID_ARCH_NAME)/libraylib.so
endif endif
ifeq ($(RAYLIB_LIBTYPE),STATIC) ifeq ($(RAYLIB_LIBTYPE),STATIC)
copy /Y $(RAYLIB_LIB_PATH)\libraylib.a $(PROJECT_BUILD_PATH)\lib\$(ANDROID_ARCH_NAME)\libraylib.a $(COPY_COMMAND) $(RAYLIB_LIB_PATH)/libraylib.a $(PROJECT_BUILD_PATH)/lib/$(ANDROID_ARCH_NAME)/libraylib.a
endif endif
# Copy project required resources: strings.xml, icon.png, assets # Copy project required resources: strings.xml, icon.png, assets
# NOTE: Required strings.xml is generated and game resources are copied to assets folder # NOTE: Required strings.xml is generated and game resources are copied to assets folder
# TODO: Review xcopy usage, it can not be found in some systems!
copy_project_resources: copy_project_resources:
copy $(APP_ICON_LDPI) $(PROJECT_BUILD_PATH)\res\drawable-ldpi\icon.png /Y $(COPY_COMMAND) $(APP_ICON_LDPI) $(PROJECT_BUILD_PATH)/res/drawable-ldpi/icon.png
copy $(APP_ICON_MDPI) $(PROJECT_BUILD_PATH)\res\drawable-mdpi\icon.png /Y $(COPY_COMMAND) $(APP_ICON_MDPI) $(PROJECT_BUILD_PATH)/res/drawable-mdpi/icon.png
copy $(APP_ICON_HDPI) $(PROJECT_BUILD_PATH)\res\drawable-hdpi\icon.png /Y $(COPY_COMMAND) $(APP_ICON_HDPI) $(PROJECT_BUILD_PATH)/res/drawable-hdpi/icon.png
ifeq ($(OS),Windows_NT)
@echo ^<?xml version="1.0" encoding="utf-8"^?^> > $(PROJECT_BUILD_PATH)/res/values/strings.xml @echo ^<?xml version="1.0" encoding="utf-8"^?^> > $(PROJECT_BUILD_PATH)/res/values/strings.xml
@echo ^<resources^>^<string name="app_name"^>$(APP_LABEL_NAME)^</string^>^</resources^> >> $(PROJECT_BUILD_PATH)/res/values/strings.xml @echo ^<resources^>^<string name="app_name"^>$(APP_LABEL_NAME)^</string^>^</resources^> >> $(PROJECT_BUILD_PATH)/res/values/strings.xml
if exist $(PROJECT_RESOURCES_PATH) C:\Windows\System32\xcopy $(PROJECT_RESOURCES_PATH) $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH) /Y /E /F if exist $(PROJECT_RESOURCES_PATH) C:\Windows\System32\xcopy $(PROJECT_RESOURCES_PATH) $(PROJECT_BUILD_PATH)\assets\$(PROJECT_RESOURCES_PATH) /Y /E /F
else
@echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>" > $(PROJECT_BUILD_PATH)/res/values/strings.xml
@echo "<resources><string name=\"app_name\">$(APP_LABEL_NAME)</string></resources>" >> $(PROJECT_BUILD_PATH)/res/values/strings.xml
@[ -d "$(PROJECT_RESOURCES_PATH)" ] || cp -rf $(PROJECT_RESOURCES_PATH) $(PROJECT_BUILD_PATH)/assets/$(PROJECT_RESOURCES_PATH)
endif
# Generate NativeLoader.java to load required shared libraries # Generate NativeLoader.java to load required shared libraries
# NOTE: Probably not the bet way to generate this file... but it works. # NOTE: Probably not the bet way to generate this file... but it works.
generate_loader_script: generate_loader_script:
ifeq ($(OS),Windows_NT)
@echo package com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME); > $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo package com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME); > $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo. >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo. >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo public class NativeLoader extends android.app.NativeActivity { >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo public class NativeLoader extends android.app.NativeActivity { >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@ -216,10 +260,23 @@ endif
@echo System.loadLibrary("$(PROJECT_LIBRARY_NAME)"); >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo System.loadLibrary("$(PROJECT_LIBRARY_NAME)"); >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo } >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo } >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo } >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java @echo } >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
else
@echo "package com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME);" > $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo "" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo "public class NativeLoader extends android.app.NativeActivity {" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo " static {" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
ifeq ($(RAYLIB_LIBTYPE),SHARED)
@echo " System.loadLibrary(\"raylib\");" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
endif
@echo " System.loadLibrary(\"$(PROJECT_LIBRARY_NAME)\");" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo " }" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
@echo "}" >> $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
endif
# Generate AndroidManifest.xml with all the required options # Generate AndroidManifest.xml with all the required options
# NOTE: Probably not the bet way to generate this file... but it works. # NOTE: Probably not the bet way to generate this file... but it works.
generate_android_manifest: generate_android_manifest:
ifeq ($(OS),Windows_NT)
@echo ^<?xml version="1.0" encoding="utf-8"^?^> > $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo ^<?xml version="1.0" encoding="utf-8"^?^> > $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo ^<manifest xmlns:android="http://schemas.android.com/apk/res/android" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo ^<manifest xmlns:android="http://schemas.android.com/apk/res/android" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo package="com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME)" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo package="com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME)" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@ -240,11 +297,37 @@ generate_android_manifest:
@echo ^</activity^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo ^</activity^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo ^</application^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo ^</application^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo ^</manifest^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml @echo ^</manifest^> >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
else
@echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>" > $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " package=\"com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME)\" " >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " android:versionCode=\"$(APP_VERSION_CODE)\" android:versionName=\"$(APP_VERSION_NAME)\" >" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <uses-sdk android:minSdkVersion=\"$(ANDROID_API_VERSION)\" />" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <uses-feature android:glEsVersion=\"0x00020000\" android:required=\"true\" />" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <application android:allowBackup=\"false\" android:label=\"@string/app_name\" android:icon=\"@drawable/icon\" >" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <activity android:name=\"com.$(APP_COMPANY_NAME).$(APP_PRODUCT_NAME).NativeLoader\"" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " android:configChanges=\"orientation|keyboardHidden|screenSize\"" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " android:screenOrientation=\"$(APP_SCREEN_ORIENTATION)\" android:launchMode=\"singleTask\"" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " android:clearTaskOnLaunch=\"true\">" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <meta-data android:name=\"android.app.lib_name\" android:value=\"$(PROJECT_LIBRARY_NAME)\" />" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <intent-filter>" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <action android:name=\"android.intent.action.MAIN\" />" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " <category android:name=\"android.intent.category.LAUNCHER\" />" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " </intent-filter>" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " </activity>" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo " </application>" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
@echo "</manifest>" >> $(PROJECT_BUILD_PATH)/AndroidManifest.xml
endif
# Generate storekey for APK signing: $(PROJECT_NAME).keystore # Generate storekey for APK signing: $(PROJECT_NAME).keystore
# NOTE: Configure here your Distinguished Names (-dname) if required! # NOTE: Configure here your Distinguished Names (-dname) if required!
generate_apk_keystore: generate_apk_keystore:
ifeq ($(OS),Windows_NT)
if not exist $(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore $(JAVA_HOME)/bin/keytool -genkeypair -validity 10000 -dname "CN=$(APP_COMPANY_NAME),O=Android,C=ES" -keystore $(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore -storepass $(APP_KEYSTORE_PASS) -keypass $(APP_KEYSTORE_PASS) -alias $(PROJECT_NAME)Key -keyalg RSA if not exist $(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore $(JAVA_HOME)/bin/keytool -genkeypair -validity 10000 -dname "CN=$(APP_COMPANY_NAME),O=Android,C=ES" -keystore $(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore -storepass $(APP_KEYSTORE_PASS) -keypass $(APP_KEYSTORE_PASS) -alias $(PROJECT_NAME)Key -keyalg RSA
else
@[ -f "$(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore" ] || $(JAVA_HOME)/bin/keytool -genkeypair -validity 10000 -dname "CN=$(APP_COMPANY_NAME),O=Android,C=ES" -keystore $(PROJECT_BUILD_PATH)/$(PROJECT_NAME).keystore -storepass $(APP_KEYSTORE_PASS) -keypass $(APP_KEYSTORE_PASS) -alias $(PROJECT_NAME)Key -keyalg RSA
endif
# Config project package and resource using AndroidManifest.xml and res/values/strings.xml # Config project package and resource using AndroidManifest.xml and res/values/strings.xml
# NOTE: Generates resources file: src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/R.java # NOTE: Generates resources file: src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/R.java
@ -253,7 +336,7 @@ config_project_package:
# Compile native_app_glue code as static library: obj/libnative_app_glue.a # Compile native_app_glue code as static library: obj/libnative_app_glue.a
compile_native_app_glue: compile_native_app_glue:
$(CC) -c $(RAYLIB_PATH)/src/external/android/native_app_glue/android_native_app_glue.c -o $(PROJECT_BUILD_PATH)/obj/native_app_glue.o $(CFLAGS) $(CC) -c $(NATIVE_APP_GLUE_PATH)/android_native_app_glue.c -o $(PROJECT_BUILD_PATH)/obj/native_app_glue.o $(CFLAGS)
$(AR) rcs $(PROJECT_BUILD_PATH)/obj/libnative_app_glue.a $(PROJECT_BUILD_PATH)/obj/native_app_glue.o $(AR) rcs $(PROJECT_BUILD_PATH)/obj/libnative_app_glue.a $(PROJECT_BUILD_PATH)/obj/native_app_glue.o
# Compile project code into a shared library: lib/lib$(PROJECT_LIBRARY_NAME).so # Compile project code into a shared library: lib/lib$(PROJECT_LIBRARY_NAME).so
@ -267,7 +350,7 @@ $(PROJECT_BUILD_PATH)/obj/%.o:%.c
# Compile project .java code into .class (Java bytecode) # Compile project .java code into .class (Java bytecode)
compile_project_class: compile_project_class:
$(JAVA_HOME)/bin/javac -verbose -source 1.7 -target 1.7 -d $(PROJECT_BUILD_PATH)/obj -bootclasspath $(JAVA_HOME)/jre/lib/rt.jar -classpath $(ANDROID_HOME)/platforms/android-$(ANDROID_API_VERSION)/android.jar;$(PROJECT_BUILD_PATH)/obj -sourcepath $(PROJECT_BUILD_PATH)/src $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/R.java $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java $(JAVA_HOME)/bin/javac -verbose -source 1.7 -target 1.7 -d $(PROJECT_BUILD_PATH)/obj -bootclasspath $(JAVA_HOME)/jre/lib/rt.jar -classpath $(ANDROID_HOME)/platforms/android-$(ANDROID_API_VERSION)/android.jar -d $(PROJECT_BUILD_PATH)/obj $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/R.java $(PROJECT_BUILD_PATH)/src/com/$(APP_COMPANY_NAME)/$(APP_PRODUCT_NAME)/NativeLoader.java
# Compile .class files into Dalvik executable bytecode (.dex) # Compile .class files into Dalvik executable bytecode (.dex)
# NOTE: Since Android 5.0, Dalvik interpreter (JIT) has been replaced by ART (AOT) # NOTE: Since Android 5.0, Dalvik interpreter (JIT) has been replaced by ART (AOT)
@ -313,6 +396,10 @@ deploy:
# Clean everything # Clean everything
clean: clean:
ifeq ($(OS),Windows_NT)
del $(PROJECT_BUILD_PATH)\* /f /s /q del $(PROJECT_BUILD_PATH)\* /f /s /q
rmdir $(PROJECT_BUILD_PATH) /s /q rmdir $(PROJECT_BUILD_PATH) /s /q
else
rm -r $(PROJECT_BUILD_PATH)
endif
@echo Cleaning done @echo Cleaning done

View File

@ -20,16 +20,16 @@ Examples using raylib core platform functionality like window creation, inputs,
| 12 | [core_3d_camera_first_person](core/core_3d_camera_first_person.c) | <img src="core/core_3d_camera_first_person.png" alt="core_3d_camera_first_person" width="200"> | ray | | | 12 | [core_3d_camera_first_person](core/core_3d_camera_first_person.c) | <img src="core/core_3d_camera_first_person.png" alt="core_3d_camera_first_person" width="200"> | ray | |
| 13 | [core_3d_picking](core/core_3d_picking.c) | <img src="core/core_3d_picking.png" alt="core_3d_picking" width="200"> | ray | | | 13 | [core_3d_picking](core/core_3d_picking.c) | <img src="core/core_3d_picking.png" alt="core_3d_picking" width="200"> | ray | |
| 14 | [core_world_screen](core/core_world_screen.c) | <img src="core/core_world_screen.png" alt="core_world_screen" width="200"> | ray | | | 14 | [core_world_screen](core/core_world_screen.c) | <img src="core/core_world_screen.png" alt="core_world_screen" width="200"> | ray | |
| 15 | [core_custom_logging](core/core_custom_logging.c) | <img src="core/core_custom_logging.png" alt="core_custom_logging" width="200"> | [Pablo Marcos](https://github.com/pamarcos) | | | 15 | [core_custom_logging](core/core_custom_logging.c) | <img src="core/core_custom_logging.png" alt="core_custom_logging" width="200"> | [Pablo Marcos](https://github.com/pamarcos) | |
| 16 | [core_window_letterbox](core/core_window_letterbox.c) | <img src="core/core_window_letterbox.png" alt="core_window_letterbox" width="200"> | [Anata](https://github.com/anatagawa) | | | 16 | [core_window_letterbox](core/core_window_letterbox.c) | <img src="core/core_window_letterbox.png" alt="core_window_letterbox" width="200"> | [Anata](https://github.com/anatagawa) | |
| 17 | [core_drop_files](core/core_drop_files.c) | <img src="core/core_drop_files.png" alt="core_drop_files" width="200"> | ray | | | 17 | [core_drop_files](core/core_drop_files.c) | <img src="core/core_drop_files.png" alt="core_drop_files" width="200"> | ray | |
| 18 | [core_random_values](core/core_random_values.c) | <img src="core/core_random_values.png" alt="core_random_values" width="200"> | ray | | | 18 | [core_random_values](core/core_random_values.c) | <img src="core/core_random_values.png" alt="core_random_values" width="200"> | ray | |
| 19 | [core_scissor_test](core/core_scissor_test.c) | <img src="core/core_scissor_test.png" alt="core_scissor_test" width="200"> | [Chris Dill](https://github.com/MysteriousSpace) | ⭐️ | | 19 | [core_scissor_test](core/core_scissor_test.c) | <img src="core/core_scissor_test.png" alt="core_scissor_test" width="200"> | [Chris Dill](https://github.com/MysteriousSpace) | |
| 20 | [core_storage_values](core/core_storage_values.c) | <img src="core/core_storage_values.png" alt="core_storage_values" width="200"> | ray | | | 20 | [core_storage_values](core/core_storage_values.c) | <img src="core/core_storage_values.png" alt="core_storage_values" width="200"> | ray | |
| 21 | [core_vr_simulator](core/core_vr_simulator.c) | <img src="core/core_vr_simulator.png" alt="core_vr_simulator" width="200"> | ray | | | 21 | [core_vr_simulator](core/core_vr_simulator.c) | <img src="core/core_vr_simulator.png" alt="core_vr_simulator" width="200"> | ray | ⭐️ |
| 22 | [core_loading_thread](core/core_loading_thread.c) | <img src="core/core_loading_thread.png" alt="core_loading_thread" width="200"> | ray | ⭐️ | | 22 | [core_loading_thread](core/core_loading_thread.c) | <img src="core/core_loading_thread.png" alt="core_loading_thread" width="200"> | ray | |
| 23 | [core/core_quat_conversion](core/core_quat_conversion.c) | <img src="core/core_quat_conversion.png" alt="core_quat_conversion" width="200"> | [Chris Camacho](https://github.com/codifies) | ⭐️ | | 23 | [core/core_quat_conversion](core/core_quat_conversion.c) | <img src="core/core_quat_conversion.png" alt="core_quat_conversion" width="200"> | [Chris Camacho](https://github.com/codifies) | |
| 24 | [core/core_window_flags](core/core_window_flags.c) | <img src="core/core_window_flags.png" alt="core_window_flags" width="200"> | ray | ⭐️ | | ⭐️ | | 24 | [core/core_window_flags](core/core_window_flags.c) | <img src="core/core_window_flags.png" alt="core_window_flags" width="200"> | ray | |
### category: shapes ### category: shapes
@ -38,18 +38,18 @@ Examples using raylib shapes drawing functionality, provided by raylib [shapes](
| ## | example | image | developer | new | | ## | example | image | developer | new |
|----|----------|--------|:----------:|:---:| |----|----------|--------|:----------:|:---:|
| 25 | [shapes_basic_shapes](shapes/shapes_basic_shapes.c) | <img src="shapes/shapes_basic_shapes.png" alt="shapes_basic_shapes" width="200"> | ray | | | 25 | [shapes_basic_shapes](shapes/shapes_basic_shapes.c) | <img src="shapes/shapes_basic_shapes.png" alt="shapes_basic_shapes" width="200"> | ray | |
| 26 | [shapes_bouncing_ball](shapes/shapes_bouncing_ball.c) | <img src="shapes/shapes_bouncing_ball.png" alt="shapes_bouncing_ball" width="200"> | ray | ⭐️ | | 26 | [shapes_bouncing_ball](shapes/shapes_bouncing_ball.c) | <img src="shapes/shapes_bouncing_ball.png" alt="shapes_bouncing_ball" width="200"> | ray | |
| 27 | [shapes_colors_palette](shapes/shapes_colors_palette.c) | <img src="shapes/shapes_colors_palette.png" alt="shapes_colors_palette" width="200"> | ray | | | 27 | [shapes_colors_palette](shapes/shapes_colors_palette.c) | <img src="shapes/shapes_colors_palette.png" alt="shapes_colors_palette" width="200"> | ray | |
| 28 | [shapes_logo_raylib](shapes/shapes_logo_raylib.c) | <img src="shapes/shapes_logo_raylib.png" alt="shapes_logo_raylib" width="200"> | ray | | | 28 | [shapes_logo_raylib](shapes/shapes_logo_raylib.c) | <img src="shapes/shapes_logo_raylib.png" alt="shapes_logo_raylib" width="200"> | ray | |
| 29 | [shapes_logo_raylib_anim](shapes/shapes_logo_raylib_anim.c) | <img src="shapes/shapes_logo_raylib_anim.png" alt="shapes_logo_raylib_anim" width="200"> | ray | | | 29 | [shapes_logo_raylib_anim](shapes/shapes_logo_raylib_anim.c) | <img src="shapes/shapes_logo_raylib_anim.png" alt="shapes_logo_raylib_anim" width="200"> | ray | |
| 30 | [shapes_rectangle_scaling](shapes/shapes_rectangle_scaling.c) | <img src="shapes/shapes_rectangle_scaling.png" alt="shapes_rectangle_scaling" width="200"> | [Vlad Adrian](https://github.com/demizdor) | | | 30 | [shapes_rectangle_scaling](shapes/shapes_rectangle_scaling.c) | <img src="shapes/shapes_rectangle_scaling.png" alt="shapes_rectangle_scaling" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| 31 | [shapes_lines_bezier](shapes/shapes_lines_bezier.c) | <img src="shapes/shapes_lines_bezier.png" alt="shapes_lines_bezier" width="200"> | ray | | | 31 | [shapes_lines_bezier](shapes/shapes_lines_bezier.c) | <img src="shapes/shapes_lines_bezier.png" alt="shapes_lines_bezier" width="200"> | ray | |
| 32 | [shapes_collision_area](shapes/shapes_collision_area.c) | <img src="shapes/shapes_collision_area.png" alt="shapes_collision_area" width="200"> | ray | ⭐️ | | 32 | [shapes_collision_area](shapes/shapes_collision_area.c) | <img src="shapes/shapes_collision_area.png" alt="shapes_collision_area" width="200"> | ray | |
| 33 | [shapes_following_eyes](shapes/shapes_following_eyes.c) | <img src="shapes/shapes_following_eyes.png" alt="shapes_following_eyes" width="200"> | ray | ⭐️ | | 33 | [shapes_following_eyes](shapes/shapes_following_eyes.c) | <img src="shapes/shapes_following_eyes.png" alt="shapes_following_eyes" width="200"> | ray | |
| 34 | [shapes_easings_ball_anim](shapes/shapes_easings_ball_anim.c) | <img src="shapes/shapes_easings_ball_anim.png" alt="shapes_easings_ball_anim" width="200"> | ray | ⭐️ | | 34 | [shapes_easings_ball_anim](shapes/shapes_easings_ball_anim.c) | <img src="shapes/shapes_easings_ball_anim.png" alt="shapes_easings_ball_anim" width="200"> | ray | |
| 35 | [shapes_easings_box_anim](shapes/shapes_easings_box_anim.c) | <img src="shapes/shapes_easings_box_anim.png" alt="shapes_easings_box_anim" width="200"> | ray | ⭐️ | | 35 | [shapes_easings_box_anim](shapes/shapes_easings_box_anim.c) | <img src="shapes/shapes_easings_box_anim.png" alt="shapes_easings_box_anim" width="200"> | ray | |
| 36 | [shapes_easings_rectangle_array](shapes/shapes_easings_rectangle_array.c) | <img src="shapes/shapes_easings_rectangle_array.png" alt="shapes_easings_rectangle_array" width="200"> | ray | ⭐️ | | 36 | [shapes_easings_rectangle_array](shapes/shapes_easings_rectangle_array.c) | <img src="shapes/shapes_easings_rectangle_array.png" alt="shapes_easings_rectangle_array" width="200"> | ray | |
| 37 | [shapes_draw_ring](shapes/shapes_draw_ring.c) | <img src="shapes/shapes_draw_ring.png" alt="shapes_draw_ring" width="200"> | [Vlad Adrian](https://github.com/demizdor) | ⭐️ | | 37 | [shapes_draw_ring](shapes/shapes_draw_ring.c) | <img src="shapes/shapes_draw_ring.png" alt="shapes_draw_ring" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| 38 | [shapes_draw_circle_sector](shapes/shapes_draw_circle_sector.c) | <img src="shapes/shapes_draw_circle_sector.png" alt="shapes_draw_circle_sector" width="200"> | [Vlad Adrian](https://github.com/demizdor) | | | 38 | [shapes_draw_circle_sector](shapes/shapes_draw_circle_sector.c) | <img src="shapes/shapes_draw_circle_sector.png" alt="shapes_draw_circle_sector" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| 39 | [shapes_draw_rectangle_rounded](shapes/shapes_draw_rectangle_rounded.c) | <img src="shapes/shapes_draw_rectangle_rounded.png" alt="shapes_draw_rectangle_rounded" width="200"> | [Vlad Adrian](https://github.com/demizdor) | | | 39 | [shapes_draw_rectangle_rounded](shapes/shapes_draw_rectangle_rounded.c) | <img src="shapes/shapes_draw_rectangle_rounded.png" alt="shapes_draw_rectangle_rounded" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
@ -66,18 +66,19 @@ Examples using raylib textures functionality, including image/textures loading/g
| 44 | [textures_image_generation](textures/textures_image_generation.c) | <img src="textures/textures_image_generation.png" alt="textures_image_generation" width="200"> | ray | | | 44 | [textures_image_generation](textures/textures_image_generation.c) | <img src="textures/textures_image_generation.png" alt="textures_image_generation" width="200"> | ray | |
| 45 | [textures_image_loading](textures/textures_image_loading.c) | <img src="textures/textures_image_loading.png" alt="textures_image_loading" width="200"> | ray | | | 45 | [textures_image_loading](textures/textures_image_loading.c) | <img src="textures/textures_image_loading.png" alt="textures_image_loading" width="200"> | ray | |
| 46 | [textures_image_processing](textures/textures_image_processing.c) | <img src="textures/textures_image_processing.png" alt="textures_image_processing" width="200"> | ray | | | 46 | [textures_image_processing](textures/textures_image_processing.c) | <img src="textures/textures_image_processing.png" alt="textures_image_processing" width="200"> | ray | |
| 47 | [textures_image_text](textures/textures_image_text.c) | <img src="textures/textures_image_text.png" alt="textures_image_text" width="200"> | ray | | | 47 | [textures_image_text](textures/textures_image_text.c) | <img src="textures/textures_image_text.png" alt="textures_image_text" width="200"> | ray | |
| 48 | [textures_to_image](textures/textures_to_image.c) | <img src="textures/textures_to_image.png" alt="textures_to_image" width="200"> | ray | ⭐️ | | 48 | [textures_to_image](textures/textures_to_image.c) | <img src="textures/textures_to_image.png" alt="textures_to_image" width="200"> | ray | |
| 49 | [textures_raw_data](textures/textures_raw_data.c) | <img src="textures/textures_raw_data.png" alt="textures_raw_data" width="200"> | ray | | | 49 | [textures_raw_data](textures/textures_raw_data.c) | <img src="textures/textures_raw_data.png" alt="textures_raw_data" width="200"> | ray | |
| 50 | [textures_particles_blending](textures/textures_particles_blending.c) | <img src="textures/textures_particles_blending.png" alt="textures_particles_blending" width="200"> | ray | | | 50 | [textures_particles_blending](textures/textures_particles_blending.c) | <img src="textures/textures_particles_blending.png" alt="textures_particles_blending" width="200"> | ray | |
| 51 | [textures_npatch_drawing](textures/textures_npatch_drawing.c) | <img src="textures/textures_npatch_drawing.png" alt="textures_npatch_drawing" width="200"> | [Jorge A. Gomes](https://github.com/overdev) | | | 51 | [textures_npatch_drawing](textures/textures_npatch_drawing.c) | <img src="textures/textures_npatch_drawing.png" alt="textures_npatch_drawing" width="200"> | [Jorge A. Gomes](https://github.com/overdev) | |
| 52 | [textures_background_scrolling](textures/textures_background_scrolling.c) | <img src="textures/textures_background_scrolling.png" alt="textures_background_scrolling" width="200"> | ray | ⭐️ | | 52 | [textures_background_scrolling](textures/textures_background_scrolling.c) | <img src="textures/textures_background_scrolling.png" alt="textures_background_scrolling" width="200"> | ray | |
| 53 | [textures_sprite_button](textures/textures_sprite_button.c) | <img src="textures/textures_sprite_button.png" alt="textures_sprite_button" width="200"> | ray | ⭐️ | | 53 | [textures_sprite_button](textures/textures_sprite_button.c) | <img src="textures/textures_sprite_button.png" alt="textures_sprite_button" width="200"> | ray | |
| 54 | [textures_sprite_explosion](textures/textures_sprite_explosion.c) | <img src="textures/textures_sprite_explosion.png" alt="textures_sprite_explosion" width="200"> | ray | ⭐️ | | 54 | [textures_sprite_explosion](textures/textures_sprite_explosion.c) | <img src="textures/textures_sprite_explosion.png" alt="textures_sprite_explosion" width="200"> | ray | |
| 55 | [textures_bunnymark](textures/textures_bunnymark.c) | <img src="textures/textures_bunnymark.png" alt="textures_bunnymark" width="200"> | ray | | | 55 | [textures_bunnymark](textures/textures_bunnymark.c) | <img src="textures/textures_bunnymark.png" alt="textures_bunnymark" width="200"> | ray | |
| 56 | [textures_mouse_painting](textures/textures_mouse_painting.c) | <img src="textures/textures_mouse_painting.png" alt="textures_mouse_painting" width="200"> | [Chris Dill](https://github.com/MysteriousSpace) | | | 56 | [textures_mouse_painting](textures/textures_mouse_painting.c) | <img src="textures/textures_mouse_painting.png" alt="textures_mouse_painting" width="200"> | [Chris Dill](https://github.com/MysteriousSpace) | |
| 57 | [textures_blend_modes](textures/textures_blend_modes.c) | <img src="textures/textures_blend_modes.png" alt="textures_blend_modes" width="200"> | [Karlo Licudine](https://github.com/accidentalrebel) | ⭐️ | | 57 | [textures_blend_modes](textures/textures_blend_modes.c) | <img src="textures/textures_blend_modes.png" alt="textures_blend_modes" width="200"> | [Karlo Licudine](https://github.com/accidentalrebel) | |
| 58 | [textures/textures_draw_tiled](textures/textures_draw_tiled.c) | <img src="textures/textures_draw_tiled.png" alt="textures_draw_tiled" width="200"> | [Vlad Adrian](https://github.com/demizdor) | ⭐️ | | 58 | [textures_draw_tiled](textures/textures_draw_tiled.c) | <img src="textures/textures_draw_tiled.png" alt="textures_draw_tiled" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| -- | [textures_poly](textures/textures_poly.c) | <img src="textures/textures_poly.png" alt="textures_poly" width="200"> | [Chris Camacho](https://github.com/codifies) | ⭐️ |
### category: text ### category: text
@ -89,12 +90,13 @@ Examples using raylib text functionality, including sprite fonts loading/generat
| 60 | [text_font_spritefont](text/text_font_spritefont.c) | <img src="text/text_font_spritefont.png" alt="text_font_spritefont" width="200"> | ray | | | 60 | [text_font_spritefont](text/text_font_spritefont.c) | <img src="text/text_font_spritefont.png" alt="text_font_spritefont" width="200"> | ray | |
| 61 | [text_font_filters](text/text_font_filters.c) | <img src="text/text_font_filters.png" alt="text_font_filters" width="200"> | ray | | | 61 | [text_font_filters](text/text_font_filters.c) | <img src="text/text_font_filters.png" alt="text_font_filters" width="200"> | ray | |
| 62 | [text_font_loading](text/text_font_loading.c) | <img src="text/text_font_loading.png" alt="text_font_loading" width="200"> | ray | | | 62 | [text_font_loading](text/text_font_loading.c) | <img src="text/text_font_loading.png" alt="text_font_loading" width="200"> | ray | |
| 63 | [text_font_sdf](text/text_font_sdf.c) | <img src="text/text_font_sdf.png" alt="text_font_sdf" width="200"> | ray | | | 63 | [text_font_sdf](text/text_font_sdf.c) | <img src="text/text_font_sdf.png" alt="text_font_sdf" width="200"> | ray | |
| 64 | [text_format_text](text/text_format_text.c) | <img src="text/text_format_text.png" alt="text_format_text" width="200"> | ray | | | 64 | [text_format_text](text/text_format_text.c) | <img src="text/text_format_text.png" alt="text_format_text" width="200"> | ray | |
| 65 | [text_input_box](text/text_input_box.c) | <img src="text/text_input_box.png" alt="text_input_box" width="200"> | ray | | | 65 | [text_input_box](text/text_input_box.c) | <img src="text/text_input_box.png" alt="text_input_box" width="200"> | ray | |
| 66 | [text_writing_anim](text/text_writing_anim.c) | <img src="text/text_writing_anim.png" alt="text_writing_anim" width="200"> | ray | | | 66 | [text_writing_anim](text/text_writing_anim.c) | <img src="text/text_writing_anim.png" alt="text_writing_anim" width="200"> | ray | |
| 67 | [text_rectangle_bounds](text/text_rectangle_bounds.c) | <img src="text/text_rectangle_bounds.png" alt="text_rectangle_bounds" width="200"> | [Vlad Adrian](https://github.com/demizdor) | | | 67 | [text_rectangle_bounds](text/text_rectangle_bounds.c) | <img src="text/text_rectangle_bounds.png" alt="text_rectangle_bounds" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| 68 | [text_unicode](text/text_unicode.c) | <img src="text/text_unicode.png" alt="text_unicode" width="200"> | [Vlad Adrian](https://github.com/demizdor) | | | 68 | [text_unicode](text/text_unicode.c) | <img src="text/text_unicode.png" alt="text_unicode" width="200"> | [Vlad Adrian](https://github.com/demizdor) | |
| -- | [text_draw_3d](text/text_draw_3d.c) | <img src="text/text_draw_3d.png" alt="text_draw_3d" width="200"> | [Vlad Adrian](https://github.com/demizdor) | ⭐️ |
### category: models ### category: models
@ -102,22 +104,23 @@ Examples using raylib models functionality, including models loading/generation
| ## | example | image | developer | new | | ## | example | image | developer | new |
|----|----------|--------|:----------:|:---:| |----|----------|--------|:----------:|:---:|
| 69 | [models_animation](models/models_animation.c) | <img src="models/models_animation.png" alt="models_animation" width="200"> | [culacant](https://github.com/culacant) | | | 69 | [models_animation](models/models_animation.c) | <img src="models/models_animation.png" alt="models_animation" width="200"> | [culacant](https://github.com/culacant) | |
| 70 | [models_billboard](models/models_billboard.c) | <img src="models/models_billboard.png" alt="models_billboard" width="200"> | ray | | | 70 | [models_billboard](models/models_billboard.c) | <img src="models/models_billboard.png" alt="models_billboard" width="200"> | ray | |
| 71 | [models_box_collisions](models/models_box_collisions.c) | <img src="models/models_box_collisions.png" alt="models_box_collisions" width="200"> | ray | | | 71 | [models_box_collisions](models/models_box_collisions.c) | <img src="models/models_box_collisions.png" alt="models_box_collisions" width="200"> | ray | |
| 72 | [models_cubicmap](models/models_cubicmap.c) | <img src="models/models_cubicmap.png" alt="models_cubicmap" width="200"> | ray | | | 72 | [models_cubicmap](models/models_cubicmap.c) | <img src="models/models_cubicmap.png" alt="models_cubicmap" width="200"> | ray | |
| 73 | [models_first_person_maze](models/models_first_person_maze.c) | <img src="models/models_first_person_maze.png" alt="models_first_person_maze" width="200"> | ray | | | 73 | [models_first_person_maze](models/models_first_person_maze.c) | <img src="models/models_first_person_maze.png" alt="models_first_person_maze" width="200"> | ray | |
| 74 | [models_geometric_shapes](models/models_geometric_shapes.c) | <img src="models/models_geometric_shapes.png" alt="models_geometric_shapes" width="200"> | ray | | | 74 | [models_geometric_shapes](models/models_geometric_shapes.c) | <img src="models/models_geometric_shapes.png" alt="models_geometric_shapes" width="200"> | ray | |
| 75 | [models_material_pbr](models/models_material_pbr.c) | <img src="models/models_material_pbr.png" alt="models_material_pbr" width="200"> | ray | | | 75 | [models_material_pbr](models/models_material_pbr.c) | <img src="models/models_material_pbr.png" alt="models_material_pbr" width="200"> | ray | |
| 76 | [models_mesh_generation](models/models_mesh_generation.c) | <img src="models/models_mesh_generation.png" alt="models_mesh_generation" width="200"> | ray | | | 76 | [models_mesh_generation](models/models_mesh_generation.c) | <img src="models/models_mesh_generation.png" alt="models_mesh_generation" width="200"> | ray | |
| 77 | [models_mesh_picking](models/models_mesh_picking.c) | <img src="models/models_mesh_picking.png" alt="models_mesh_picking" width="200"> | [Joel Davis](https://github.com/joeld42) | | | 77 | [models_mesh_picking](models/models_mesh_picking.c) | <img src="models/models_mesh_picking.png" alt="models_mesh_picking" width="200"> | [Joel Davis](https://github.com/joeld42) | |
| 78 | [models_loading](models/models_loading.c) | <img src="models/models_loading.png" alt="models_loading" width="200"> | ray | | | 78 | [models_loading](models/models_loading.c) | <img src="models/models_loading.png" alt="models_loading" width="200"> | ray | |
| 79 | [models_orthographic_projection](models/models_orthographic_projection.c) | <img src="models/models_orthographic_projection.png" alt="models_orthographic_projection" width="200"> | [Max Danielsson](https://github.com/autious) | | | 79 | [models_orthographic_projection](models/models_orthographic_projection.c) | <img src="models/models_orthographic_projection.png" alt="models_orthographic_projection" width="200"> | [Max Danielsson](https://github.com/autious) | |
| 80 | [models_rlgl_solar_system](models/models_rlgl_solar_system.c) | <img src="models/models_rlgl_solar_system.png" alt="models_rlgl_solar_system" width="200"> | ray | | | 80 | [models_rlgl_solar_system](models/models_rlgl_solar_system.c) | <img src="models/models_rlgl_solar_system.png" alt="models_rlgl_solar_system" width="200"> | ray | |
| 81 | [models_skybox](models/models_skybox.c) | <img src="models/models_skybox.png" alt="models_skybox" width="200"> | ray | | | 81 | [models_skybox](models/models_skybox.c) | <img src="models/models_skybox.png" alt="models_skybox" width="200"> | ray | |
| 82 | [models_yaw_pitch_roll](models/models_yaw_pitch_roll.c) | <img src="models/models_yaw_pitch_roll.png" alt="models_yaw_pitch_roll" width="200"> | [Berni](https://github.com/Berni8k) | | | 82 | [models_yaw_pitch_roll](models/models_yaw_pitch_roll.c) | <img src="models/models_yaw_pitch_roll.png" alt="models_yaw_pitch_roll" width="200"> | [Berni](https://github.com/Berni8k) | ⭐️ |
| 83 | [models_heightmap](models/models_heightmap.c) | <img src="models/models_heightmap.png" alt="models_heightmap" width="200"> | ray | | | 83 | [models_heightmap](models/models_heightmap.c) | <img src="models/models_heightmap.png" alt="models_heightmap" width="200"> | ray | |
| 84 | [models_waving_cubes](models/models_waving_cubes.c) | <img src="models/models_waving_cubes.png" alt="models_waving_cubes" width="200"> | [codecat](https://github.com/codecat) | ⭐️ | | 84 | [models_waving_cubes](models/models_waving_cubes.c) | <img src="models/models_waving_cubes.png" alt="models_waving_cubes" width="200"> | [codecat](https://github.com/codecat) | |
| -- | [models_gltf_model](models/models_gltf_model.c) | <img src="models/models_gltf_model.png" alt="models_gltf_model" width="200"> | [object71](https://github.com/object71) | ⭐️ |
### category: shaders ### category: shaders
@ -126,22 +129,22 @@ Examples using raylib shaders functionality, including shaders loading, paramete
| ## | example | image | developer | new | | ## | example | image | developer | new |
|----|----------|--------|:----------:|:---:| |----|----------|--------|:----------:|:---:|
| 85 | [shaders_basic_lighting](shaders/shaders_basic_lighting.c) | <img src="shaders/shaders_basic_lighting.png" alt="shaders_basic_lighting" width="200"> | [Chris Camacho](https://github.com/codifies) | | | 85 | [shaders_basic_lighting](shaders/shaders_basic_lighting.c) | <img src="shaders/shaders_basic_lighting.png" alt="shaders_basic_lighting" width="200"> | [Chris Camacho](https://github.com/codifies) | |
| 86 | [shaders_model_shader](shaders/shaders_model_shader.c) | <img src="shaders/shaders_model_shader.png" alt="shaders_model_shader" width="200"> | ray | | | 86 | [shaders_model_shader](shaders/shaders_model_shader.c) | <img src="shaders/shaders_model_shader.png" alt="shaders_model_shader" width="200"> | ray | |
| 87 | [shaders_shapes_textures](shaders/shaders_shapes_textures.c) | <img src="shaders/shaders_shapes_textures.png" alt="shaders_shapes_textures" width="200"> | ray | | | 87 | [shaders_shapes_textures](shaders/shaders_shapes_textures.c) | <img src="shaders/shaders_shapes_textures.png" alt="shaders_shapes_textures" width="200"> | ray | |
| 88 | [shaders_custom_uniform](shaders/shaders_custom_uniform.c) | <img src="shaders/shaders_custom_uniform.png" alt="shaders_custom_uniform" width="200"> | ray | | | 88 | [shaders_custom_uniform](shaders/shaders_custom_uniform.c) | <img src="shaders/shaders_custom_uniform.png" alt="shaders_custom_uniform" width="200"> | ray | |
| 89 | [shaders_postprocessing](shaders/shaders_postprocessing.c) | <img src="shaders/shaders_postprocessing.png" alt="shaders_postprocessing" width="200"> | ray | | | 89 | [shaders_postprocessing](shaders/shaders_postprocessing.c) | <img src="shaders/shaders_postprocessing.png" alt="shaders_postprocessing" width="200"> | ray | |
| 90 | [shaders_palette_switch](shaders/shaders_palette_switch.c) | <img src="shaders/shaders_palette_switch.png" alt="shaders_palette_switch" width="200"> | [Marco Lizza](https://github.com/MarcoLizza) | | | 90 | [shaders_palette_switch](shaders/shaders_palette_switch.c) | <img src="shaders/shaders_palette_switch.png" alt="shaders_palette_switch" width="200"> | [Marco Lizza](https://github.com/MarcoLizza) | |
| 91 | [shaders_raymarching](shaders/shaders_raymarching.c) | <img src="shaders/shaders_raymarching.png" alt="shaders_raymarching" width="200"> | Shader by Iñigo Quilez | | | 91 | [shaders_raymarching](shaders/shaders_raymarching.c) | <img src="shaders/shaders_raymarching.png" alt="shaders_raymarching" width="200"> | Shader by Iñigo Quilez | |
| 92 | [shaders_texture_drawing](shaders/shaders_texture_drawing.c) | <img src="shaders/shaders_texture_drawing.png" alt="shaders_texture_drawing" width="200"> | Michał Ciesielski | | | 92 | [shaders_texture_drawing](shaders/shaders_texture_drawing.c) | <img src="shaders/shaders_texture_drawing.png" alt="shaders_texture_drawing" width="200"> | Michał Ciesielski | |
| 93 | [shaders_texture_waves](shaders/shaders_texture_waves.c) | <img src="shaders/shaders_texture_waves.png" alt="shaders_texture_waves" width="200"> | [Anata](https://github.com/anatagawa) | | | 93 | [shaders_texture_waves](shaders/shaders_texture_waves.c) | <img src="shaders/shaders_texture_waves.png" alt="shaders_texture_waves" width="200"> | [Anata](https://github.com/anatagawa) | |
| 94 | [shaders_julia_set](shaders/shaders_julia_set.c) | <img src="shaders/shaders_julia_set.png" alt="shaders_julia_set" width="200"> | [eggmund](https://github.com/eggmund) | | | 94 | [shaders_julia_set](shaders/shaders_julia_set.c) | <img src="shaders/shaders_julia_set.png" alt="shaders_julia_set" width="200"> | [eggmund](https://github.com/eggmund) | |
| 95 | [shaders_eratosthenes](shaders/shaders_eratosthenes.c) | <img src="shaders/shaders_eratosthenes.png" alt="shaders_eratosthenes" width="200"> | [ProfJski](https://github.com/ProfJski) | | | 95 | [shaders_eratosthenes](shaders/shaders_eratosthenes.c) | <img src="shaders/shaders_eratosthenes.png" alt="shaders_eratosthenes" width="200"> | [ProfJski](https://github.com/ProfJski) | |
| 96 | [shaders_fog](shaders/shaders_fog.c) | <img src="shaders/shaders_fog.png" alt="shaders_fog" width="200"> | [Chris Camacho](https://github.com/codifies) | | | 96 | [shaders_fog](shaders/shaders_fog.c) | <img src="shaders/shaders_fog.png" alt="shaders_fog" width="200"> | [Chris Camacho](https://github.com/codifies) | |
| 97 | [shaders_simple_mask](shaders/shaders_simple_mask.c) | <img src="shaders/shaders_simple_mask.png" alt="shaders_simple_mask" width="200"> | [Chris Camacho](https://github.com/codifies) | | | 97 | [shaders_simple_mask](shaders/shaders_simple_mask.c) | <img src="shaders/shaders_simple_mask.png" alt="shaders_simple_mask" width="200"> | [Chris Camacho](https://github.com/codifies) | |
| 98 | [shaders_spotlight](shaders/shaders_spotlight.c) | <img src="shaders/shaders_spotlight.png" alt="shaders_spotlight" width="200"> | [Chris Camacho](https://github.com/codifies) | ⭐️ | | 98 | [shaders_spotlight](shaders/shaders_spotlight.c) | <img src="shaders/shaders_spotlight.png" alt="shaders_spotlight" width="200"> | [Chris Camacho](https://github.com/codifies) | |
| 99 | [shaders_hot_reloading](shaders/shaders_hot_reloading.c) | <img src="shaders/shaders_hot_reloading.png" alt="shaders_hot_reloading" width="200"> | ray | ⭐️ | | 99 | [shaders_hot_reloading](shaders/shaders_hot_reloading.c) | <img src="shaders/shaders_hot_reloading.png" alt="shaders_hot_reloading" width="200"> | ray | |
| 100 | [shaders_rlgl_mesh_instanced](shaders/shaders_rlgl_mesh_instanced.c) | <img src="shaders/shaders_rlgl_mesh_instanced.png" alt="shaders_rlgl_mesh_instanced" width="200"> | [Chris Camacho](https://github.com/codifies) | ⭐️ | | 100 | [shaders_mesh_instancing](shaders/shaders_mesh_instancing.c) | <img src="shaders/shaders_mesh_instancing.png" alt="shaders_mesh_instancing" width="200"> | [seanpringle](https://github.com/seanpringle), [moliad](https://github.com/moliad) | ⭐️ |
| 101 | [shaders_multi_sample2d](shaders/shaders_multi_sample2d.c) | <img src="shaders/shaders_multi_sample2d.png" alt="shaders_multi_sample2d" width="200"> | ray | ⭐️ | | 101 | [shaders_multi_sample2d](shaders/shaders_multi_sample2d.c) | <img src="shaders/shaders_multi_sample2d.png" alt="shaders_multi_sample2d" width="200"> | ray | |
### category: audio ### category: audio
@ -192,7 +195,7 @@ Examples showing raylib misc functionality that does not fit in other categories
| 119 | [raudio_standalone](others/raudio_standalone.c) | | ray | | | 119 | [raudio_standalone](others/raudio_standalone.c) | | ray | |
| 120 | [rlgl_standalone](others/rlgl_standalone.c) | | ray | | | 120 | [rlgl_standalone](others/rlgl_standalone.c) | | ray | |
| 121 | [easings_testbed](others/easings_testbed.c) | | [Juan Miguel López](https://github.com/flashback-fx) | | | 121 | [easings_testbed](others/easings_testbed.c) | | [Juan Miguel López](https://github.com/flashback-fx) | |
| 122 | [embedded_files_loading](others/embedded_files_loading.c)) | | [Kristian Holmgren](https://github.com/defutura) | | | 122 | [embedded_files_loading](others/embedded_files_loading.c) | | [Kristian Holmgren](https://github.com/defutura) | |
As always contributions are welcome, feel free to send new examples! Here it is an [examples template](examples_template.c) to start with! As always contributions are welcome, feel free to send new examples! Here it is an [examples template](examples_template.c) to start with!

View File

@ -87,7 +87,7 @@ int main(void)
if (IsKeyDown(KEY_DOWN)) pitch -= 0.01f; if (IsKeyDown(KEY_DOWN)) pitch -= 0.01f;
else if (IsKeyDown(KEY_UP)) pitch += 0.01f; else if (IsKeyDown(KEY_UP)) pitch += 0.01f;
SetMusicPitch(music, pitch); SetMusicPitch(music, pitch);
// Get timePlayed scaled to bar dimensions // Get timePlayed scaled to bar dimensions

View File

@ -26,7 +26,7 @@ int main(void)
Sound fxWav = LoadSound("resources/sound.wav"); // Load WAV audio file Sound fxWav = LoadSound("resources/sound.wav"); // Load WAV audio file
Sound fxOgg = LoadSound("resources/target.ogg"); // Load OGG audio file Sound fxOgg = LoadSound("resources/target.ogg"); // Load OGG audio file
SetSoundVolume(fxWav, 0.2f); SetSoundVolume(fxWav, 0.2f);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -46,7 +46,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("MULTICHANNEL SOUND PLAYING", 20, 20, 20, GRAY); DrawText("MULTICHANNEL SOUND PLAYING", 20, 20, 20, GRAY);
DrawText("Press SPACE to play new ogg instance!", 200, 120, 20, LIGHTGRAY); DrawText("Press SPACE to play new ogg instance!", 200, 120, 20, LIGHTGRAY);
DrawText("Press ENTER to play new wav instance!", 200, 180, 20, LIGHTGRAY); DrawText("Press ENTER to play new wav instance!", 200, 180, 20, LIGHTGRAY);

View File

@ -71,7 +71,7 @@ int main(void)
// Sample mouse input. // Sample mouse input.
mousePosition = GetMousePosition(); mousePosition = GetMousePosition();
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) if (IsMouseButtonDown(MOUSE_BUTTON_LEFT))
{ {
float fp = (float)(mousePosition.y); float fp = (float)(mousePosition.y);
frequency = 40.0f + (float)(fp); frequency = 40.0f + (float)(fp);

View File

@ -54,7 +54,7 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Player movement // Player movement
if (IsKeyDown(KEY_RIGHT)) player.x += 2; if (IsKeyDown(KEY_RIGHT)) player.x += 2;
else if (IsKeyDown(KEY_LEFT)) player.x -= 2; else if (IsKeyDown(KEY_LEFT)) player.x -= 2;

View File

@ -46,7 +46,7 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera"); InitWindow(screenWidth, screenHeight, "raylib [core] example - 2d camera");
Player player = { 0 }; Player player = { 0 };
@ -60,7 +60,7 @@ int main(void)
{{ 250, 300, 100, 10 }, 1, GRAY }, {{ 250, 300, 100, 10 }, 1, GRAY },
{{ 650, 300, 100, 10 }, 1, GRAY } {{ 650, 300, 100, 10 }, 1, GRAY }
}; };
int envItemsLength = sizeof(envItems)/sizeof(envItems[0]); int envItemsLength = sizeof(envItems)/sizeof(envItems[0]);
Camera2D camera = { 0 }; Camera2D camera = { 0 };
@ -77,10 +77,10 @@ int main(void)
UpdateCameraEvenOutOnLanding, UpdateCameraEvenOutOnLanding,
UpdateCameraPlayerBoundsPush UpdateCameraPlayerBoundsPush
}; };
int cameraOption = 0; int cameraOption = 0;
int cameraUpdatersLength = sizeof(cameraUpdaters)/sizeof(cameraUpdaters[0]); int cameraUpdatersLength = sizeof(cameraUpdaters)/sizeof(cameraUpdaters[0]);
char *cameraDescriptions[] = { char *cameraDescriptions[] = {
"Follow player center", "Follow player center",
"Follow player center, but clamp to map edges", "Follow player center, but clamp to map edges",
@ -88,25 +88,25 @@ int main(void)
"Follow player center horizontally; updateplayer center vertically after landing", "Follow player center horizontally; updateplayer center vertically after landing",
"Player push camera on getting too close to screen edge" "Player push camera on getting too close to screen edge"
}; };
SetTargetFPS(60); SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) while (!WindowShouldClose())
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
float deltaTime = GetFrameTime(); float deltaTime = GetFrameTime();
UpdatePlayer(&player, envItems, envItemsLength, deltaTime); UpdatePlayer(&player, envItems, envItemsLength, deltaTime);
camera.zoom += ((float)GetMouseWheelMove()*0.05f); camera.zoom += ((float)GetMouseWheelMove()*0.05f);
if (camera.zoom > 3.0f) camera.zoom = 3.0f; if (camera.zoom > 3.0f) camera.zoom = 3.0f;
else if (camera.zoom < 0.25f) camera.zoom = 0.25f; else if (camera.zoom < 0.25f) camera.zoom = 0.25f;
if (IsKeyPressed(KEY_R)) if (IsKeyPressed(KEY_R))
{ {
camera.zoom = 1.0f; camera.zoom = 1.0f;
player.position = (Vector2){ 400, 280 }; player.position = (Vector2){ 400, 280 };
@ -125,12 +125,12 @@ int main(void)
ClearBackground(LIGHTGRAY); ClearBackground(LIGHTGRAY);
BeginMode2D(camera); BeginMode2D(camera);
for (int i = 0; i < envItemsLength; i++) DrawRectangleRec(envItems[i].rect, envItems[i].color); for (int i = 0; i < envItemsLength; i++) DrawRectangleRec(envItems[i].rect, envItems[i].color);
Rectangle playerRect = { player.position.x - 20, player.position.y - 40, 40, 40 }; Rectangle playerRect = { player.position.x - 20, player.position.y - 40, 40, 40 };
DrawRectangleRec(playerRect, RED); DrawRectangleRec(playerRect, RED);
EndMode2D(); EndMode2D();
DrawText("Controls:", 20, 20, 10, BLACK); DrawText("Controls:", 20, 20, 10, BLACK);
@ -140,7 +140,7 @@ int main(void)
DrawText("- C to change camera mode", 40, 100, 10, DARKGRAY); DrawText("- C to change camera mode", 40, 100, 10, DARKGRAY);
DrawText("Current camera mode:", 20, 120, 10, BLACK); DrawText("Current camera mode:", 20, 120, 10, BLACK);
DrawText(cameraDescriptions[cameraOption], 40, 140, 10, DARKGRAY); DrawText(cameraDescriptions[cameraOption], 40, 140, 10, DARKGRAY);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
@ -157,35 +157,35 @@ void UpdatePlayer(Player *player, EnvItem *envItems, int envItemsLength, float d
{ {
if (IsKeyDown(KEY_LEFT)) player->position.x -= PLAYER_HOR_SPD*delta; if (IsKeyDown(KEY_LEFT)) player->position.x -= PLAYER_HOR_SPD*delta;
if (IsKeyDown(KEY_RIGHT)) player->position.x += PLAYER_HOR_SPD*delta; if (IsKeyDown(KEY_RIGHT)) player->position.x += PLAYER_HOR_SPD*delta;
if (IsKeyDown(KEY_SPACE) && player->canJump) if (IsKeyDown(KEY_SPACE) && player->canJump)
{ {
player->speed = -PLAYER_JUMP_SPD; player->speed = -PLAYER_JUMP_SPD;
player->canJump = false; player->canJump = false;
} }
int hitObstacle = 0; int hitObstacle = 0;
for (int i = 0; i < envItemsLength; i++) for (int i = 0; i < envItemsLength; i++)
{ {
EnvItem *ei = envItems + i; EnvItem *ei = envItems + i;
Vector2 *p = &(player->position); Vector2 *p = &(player->position);
if (ei->blocking && if (ei->blocking &&
ei->rect.x <= p->x && ei->rect.x <= p->x &&
ei->rect.x + ei->rect.width >= p->x && ei->rect.x + ei->rect.width >= p->x &&
ei->rect.y >= p->y && ei->rect.y >= p->y &&
ei->rect.y < p->y + player->speed*delta) ei->rect.y < p->y + player->speed*delta)
{ {
hitObstacle = 1; hitObstacle = 1;
player->speed = 0.0f; player->speed = 0.0f;
p->y = ei->rect.y; p->y = ei->rect.y;
} }
} }
if (!hitObstacle) if (!hitObstacle)
{ {
player->position.y += player->speed*delta; player->position.y += player->speed*delta;
player->speed += G*delta; player->speed += G*delta;
player->canJump = false; player->canJump = false;
} }
else player->canJump = true; else player->canJump = true;
} }
@ -200,7 +200,7 @@ void UpdateCameraCenterInsideMap(Camera2D *camera, Player *player, EnvItem *envI
camera->target = player->position; camera->target = player->position;
camera->offset = (Vector2){ width/2.0f, height/2.0f }; camera->offset = (Vector2){ width/2.0f, height/2.0f };
float minX = 1000, minY = 1000, maxX = -1000, maxY = -1000; float minX = 1000, minY = 1000, maxX = -1000, maxY = -1000;
for (int i = 0; i < envItemsLength; i++) for (int i = 0; i < envItemsLength; i++)
{ {
EnvItem *ei = envItems + i; EnvItem *ei = envItems + i;
@ -209,10 +209,10 @@ void UpdateCameraCenterInsideMap(Camera2D *camera, Player *player, EnvItem *envI
minY = fminf(ei->rect.y, minY); minY = fminf(ei->rect.y, minY);
maxY = fmaxf(ei->rect.y + ei->rect.height, maxY); maxY = fmaxf(ei->rect.y + ei->rect.height, maxY);
} }
Vector2 max = GetWorldToScreen2D((Vector2){ maxX, maxY }, *camera); Vector2 max = GetWorldToScreen2D((Vector2){ maxX, maxY }, *camera);
Vector2 min = GetWorldToScreen2D((Vector2){ minX, minY }, *camera); Vector2 min = GetWorldToScreen2D((Vector2){ minX, minY }, *camera);
if (max.x < width) camera->offset.x = width - (max.x - width/2); 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 (max.y < height) camera->offset.y = height - (max.y - height/2);
if (min.x > 0) camera->offset.x = width/2 - min.x; if (min.x > 0) camera->offset.x = width/2 - min.x;
@ -224,11 +224,11 @@ void UpdateCameraCenterSmoothFollow(Camera2D *camera, Player *player, EnvItem *e
static float minSpeed = 30; static float minSpeed = 30;
static float minEffectLength = 10; static float minEffectLength = 10;
static float fractionSpeed = 0.8f; static float fractionSpeed = 0.8f;
camera->offset = (Vector2){ width/2.0f, height/2.0f }; camera->offset = (Vector2){ width/2.0f, height/2.0f };
Vector2 diff = Vector2Subtract(player->position, camera->target); Vector2 diff = Vector2Subtract(player->position, camera->target);
float length = Vector2Length(diff); float length = Vector2Length(diff);
if (length > minEffectLength) if (length > minEffectLength)
{ {
float speed = fmaxf(fractionSpeed*length, minSpeed); float speed = fmaxf(fractionSpeed*length, minSpeed);
@ -241,34 +241,34 @@ void UpdateCameraEvenOutOnLanding(Camera2D *camera, Player *player, EnvItem *env
static float evenOutSpeed = 700; static float evenOutSpeed = 700;
static int eveningOut = false; static int eveningOut = false;
static float evenOutTarget; static float evenOutTarget;
camera->offset = (Vector2){ width/2.0f, height/2.0f }; camera->offset = (Vector2){ width/2.0f, height/2.0f };
camera->target.x = player->position.x; camera->target.x = player->position.x;
if (eveningOut) if (eveningOut)
{ {
if (evenOutTarget > camera->target.y) if (evenOutTarget > camera->target.y)
{ {
camera->target.y += evenOutSpeed*delta; camera->target.y += evenOutSpeed*delta;
if (camera->target.y > evenOutTarget) 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; camera->target.y = evenOutTarget;
eveningOut = 0; eveningOut = 0;
} }
} }
} else
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)) if (player->canJump && (player->speed == 0) && (player->position.y != camera->target.y))
{ {
@ -278,7 +278,7 @@ void UpdateCameraEvenOutOnLanding(Camera2D *camera, Player *player, EnvItem *env
} }
} }
void UpdateCameraPlayerBoundsPush(Camera2D *camera, Player *player, EnvItem *envItems, int envItemsLength, float delta, int width, int height) void UpdateCameraPlayerBoundsPush(Camera2D *camera, Player *player, EnvItem *envItems, int envItemsLength, float delta, int width, int height)
{ {
static Vector2 bbox = { 0.2f, 0.2f }; static Vector2 bbox = { 0.2f, 0.2f };

View File

@ -0,0 +1,130 @@
/*******************************************************************************************
*
* 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 ([discord]NotManyIdeas#9972 - [github]NotManyIdeasDev) and
* reviewed by Ramon Santamaria (@raysan5)
*
* Copyright (c) 2021 Giancamillo Alessandroni (NotManyIdeas#9972) and Ramon Santamaria (@raysan5)
*
********************************************************************************************/
#include "raylib.h"
#include <math.h>
int main(void)
{
// Initialization
//--------------------------------------------------------------------------------------
const int screenWidth = 800;
const int screenHeight = 450;
const int virualScreenWidth = 160;
const int virtualScreenHeight = 90;
const float virtualRatio = (float)screenWidth/(float)virualScreenWidth;
InitWindow(screenWidth, screenHeight, "raylib [core] example - smooth pixel-perfect camera");
Camera2D worldSpaceCamera = { 0 }; // Game world camera
worldSpaceCamera.zoom = 1.0f;
Camera2D screenSpaceCamera = { 0 }; //Smoothing camera
screenSpaceCamera.zoom = 1.0f;
RenderTexture2D renderTexture = LoadRenderTexture(virualScreenWidth, virtualScreenHeight); //This is where we'll draw all our objects.
Rectangle firstRectangle = { 70.0f, 35.0f, 20.0f, 20.0f };
Rectangle secondRectangle = { 90.0f, 55.0f, 30.0f, 10.0f };
Rectangle thirdRectangle = { 80.0f, 65.0f, 15.0f, 25.0f };
//The renderTexture's height is flipped (in the source Rectangle), due to OpenGL reasons.
Rectangle renderTextureSource = { 0.0f, 0.0f, (float)renderTexture.texture.width, (float)-renderTexture.texture.height };
Rectangle renderTextureDest = { -virtualRatio, -virtualRatio, screenWidth + (virtualRatio*2), screenHeight + (virtualRatio*2) };
Vector2 origin = { 0.0f, 0.0f };
float rotation = 0.0f;
float degreesPerSecond = 60.0f;
float cameraX = 0.0f;
float cameraY = 0.0f;
SetTargetFPS(60);
//--------------------------------------------------------------------------------------
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
// Update
//----------------------------------------------------------------------------------
rotation += degreesPerSecond*GetFrameTime(); // Rotate the rectangles.
// Make the camera move to demonstrate the effect.
cameraX = (sinf(GetTime())*50.0f) - 10.0f;
cameraY = cosf(GetTime())*30.0f;
// Set the camera's target to the values computed above.
screenSpaceCamera.target = (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
//----------------------------------------------------------------------------------
BeginDrawing();
ClearBackground(RED); // This is for debug purposes. If you see red, then you've probably done something wrong.
BeginTextureMode(renderTexture);
BeginMode2D(worldSpaceCamera);
ClearBackground(RAYWHITE); // This is the color you should see as background color.
// Draw the rectangles
DrawRectanglePro(firstRectangle, origin, rotation, BLACK);
DrawRectanglePro(secondRectangle, origin, -rotation, RED);
DrawRectanglePro(thirdRectangle, origin, rotation + 45.0f, BLUE);
EndMode2D();
EndTextureMode();
BeginMode2D(screenSpaceCamera);
// Draw the render texture with an offset of 1 worldSpace unit/pixel, so that the content behind the renderTexture is not shown.
DrawTexturePro(
renderTexture.texture,
renderTextureSource,
renderTextureDest,
origin,
0.0f,
WHITE
);
EndMode2D();
//Debug info
DrawText("Screen resolution: 800x450", 5, 0, 20, DARKBLUE);
DrawText("World resolution: 160x90", 5, 20, 20, DARKGREEN);
DrawFPS(screenWidth - 75, 0);
EndDrawing();
//----------------------------------------------------------------------------------
}
// De-Initialization
//--------------------------------------------------------------------------------------
UnloadRenderTexture(renderTexture); // RenderTexture unloading
CloseWindow(); // Close window and OpenGL context
//--------------------------------------------------------------------------------------
return 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View File

@ -47,7 +47,7 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
if (!collision) if (!collision)
{ {

View File

@ -46,7 +46,7 @@ int main()
#else #else
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {

View File

@ -33,9 +33,13 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
ballPosition = GetMousePosition(); ballPosition = GetMousePosition();
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON; if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) ballColor = MAROON;
else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME; else if (IsMouseButtonPressed(MOUSE_BUTTON_MIDDLE)) ballColor = LIME;
else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE; else if (IsMouseButtonPressed(MOUSE_BUTTON_RIGHT)) ballColor = DARKBLUE;
else if (IsMouseButtonPressed(MOUSE_BUTTON_SIDE)) ballColor = PURPLE;
else if (IsMouseButtonPressed(MOUSE_BUTTON_EXTRA)) ballColor = YELLOW;
else if (IsMouseButtonPressed(MOUSE_BUTTON_FORWARD)) ballColor = ORANGE;
else if (IsMouseButtonPressed(MOUSE_BUTTON_BACK)) ballColor = BEIGE;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw

View File

@ -42,13 +42,13 @@ int main(void)
ballColor = BEIGE; ballColor = BEIGE;
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) ballColor = MAROON; if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) ballColor = MAROON;
if (IsMouseButtonDown(MOUSE_MIDDLE_BUTTON)) ballColor = LIME; if (IsMouseButtonDown(MOUSE_BUTTON_MIDDLE)) ballColor = LIME;
if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE; if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) ballColor = DARKBLUE;
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) touchCounter = 10;
if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_BUTTON_MIDDLE)) touchCounter = 10;
if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) touchCounter = 10; if (IsMouseButtonPressed(MOUSE_BUTTON_RIGHT)) touchCounter = 10;
if (touchCounter > 0) touchCounter--; if (touchCounter > 0) touchCounter--;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------

View File

@ -26,7 +26,7 @@ int main(void)
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - quat conversions"); InitWindow(screenWidth, screenHeight, "raylib [core] example - quat conversions");
Camera3D camera = { 0 }; Camera3D camera = { 0 };
camera.position = (Vector3){ 0.0f, 10.0f, 10.0f }; // Camera position camera.position = (Vector3){ 0.0f, 10.0f, 10.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
@ -34,9 +34,9 @@ int main(void)
camera.fovy = 45.0f; // Camera field-of-view Y camera.fovy = 45.0f; // Camera field-of-view Y
camera.projection = CAMERA_PERSPECTIVE; // Camera mode type camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
Mesh mesh = GenMeshCylinder(0.2f, 1.0f, 32); Mesh mesh = GenMeshCylinder(0.2f, 1.0f, 32);
Model model = LoadModelFromMesh(mesh); Model model = LoadModelFromMesh(mesh);
// Some required variables // Some required variables
Quaternion q1 = { 0 }; Quaternion q1 = { 0 };
Matrix m1 = { 0 }, m2 = { 0 }, m3 = { 0 }, m4 = { 0 }; Matrix m1 = { 0 }, m2 = { 0 }, m3 = { 0 }, m4 = { 0 };
@ -44,7 +44,7 @@ int main(void)
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
@ -60,28 +60,28 @@ int main(void)
if (v1.x > PI*2) v1.x -= PI*2; if (v1.x > PI*2) v1.x -= PI*2;
if (v1.y > PI*2) v1.y -= PI*2; if (v1.y > PI*2) v1.y -= PI*2;
if (v1.z > PI*2) v1.z -= PI*2; if (v1.z > PI*2) v1.z -= PI*2;
q1 = QuaternionFromEuler(v1.x, v1.y, v1.z); q1 = QuaternionFromEuler(v1.x, v1.y, v1.z);
m1 = MatrixRotateZYX(v1); m1 = MatrixRotateZYX(v1);
m2 = QuaternionToMatrix(q1); m2 = QuaternionToMatrix(q1);
q1 = QuaternionFromMatrix(m1); q1 = QuaternionFromMatrix(m1);
m3 = QuaternionToMatrix(q1); m3 = QuaternionToMatrix(q1);
v2 = QuaternionToEuler(q1); v2 = QuaternionToEuler(q1);
v2.x *= DEG2RAD; v2.x *= DEG2RAD;
v2.y *= DEG2RAD; v2.y *= DEG2RAD;
v2.z *= DEG2RAD; v2.z *= DEG2RAD;
m4 = MatrixRotateZYX(v2); m4 = MatrixRotateZYX(v2);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera); BeginMode3D(camera);
model.transform = m1; model.transform = m1;
@ -94,19 +94,19 @@ int main(void)
DrawModel(model, (Vector3){ 0, 0, -1 }, 1.0f, RED); DrawModel(model, (Vector3){ 0, 0, -1 }, 1.0f, RED);
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();
if (v2.x < 0) v2.x += PI*2; if (v2.x < 0) v2.x += PI*2;
if (v2.y < 0) v2.y += PI*2; if (v2.y < 0) v2.y += PI*2;
if (v2.z < 0) v2.z += PI*2; if (v2.z < 0) v2.z += PI*2;
Color cx,cy,cz; Color cx,cy,cz;
cx = cy = cz = BLACK; cx = cy = cz = BLACK;
if (v1.x == v2.x) cx = GREEN; if (v1.x == v2.x) cx = GREEN;
if (v1.y == v2.y) cy = GREEN; if (v1.y == v2.y) cy = GREEN;
if (v1.z == v2.z) cz = GREEN; if (v1.z == v2.z) cz = GREEN;
DrawText(TextFormat("%2.3f", v1.x), 20, 20, 20, cx); DrawText(TextFormat("%2.3f", v1.x), 20, 20, 20, cx);
DrawText(TextFormat("%2.3f", v1.y), 20, 40, 20, cy); DrawText(TextFormat("%2.3f", v1.y), 20, 40, 20, cy);
DrawText(TextFormat("%2.3f", v1.z), 20, 60, 20, cz); DrawText(TextFormat("%2.3f", v1.z), 20, 60, 20, cz);
@ -122,7 +122,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadModel(model); // Unload model data (mesh and materials) UnloadModel(model); // Unload model data (mesh and materials)
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -38,9 +38,9 @@ int main(void)
.eyeToScreenDistance = 0.041f, // Distance between eye and display in meters .eyeToScreenDistance = 0.041f, // Distance between eye and display in meters
.lensSeparationDistance = 0.07f, // Lens separation distance in meters .lensSeparationDistance = 0.07f, // Lens separation distance in meters
.interpupillaryDistance = 0.07f, // IPD (distance between pupils) in meters .interpupillaryDistance = 0.07f, // IPD (distance between pupils) in meters
// NOTE: CV1 uses fresnel-hybrid-asymmetric lenses with specific compute shaders // NOTE: CV1 uses fresnel-hybrid-asymmetric lenses with specific compute shaders
// Following parameters are just an approximation to CV1 distortion stereo rendering // Following parameters are just an approximation to CV1 distortion stereo rendering
.lensDistortionValues[0] = 1.0f, // Lens distortion constant parameter 0 .lensDistortionValues[0] = 1.0f, // Lens distortion constant parameter 0
.lensDistortionValues[1] = 0.22f, // Lens distortion constant parameter 1 .lensDistortionValues[1] = 0.22f, // Lens distortion constant parameter 1
.lensDistortionValues[2] = 0.24f, // Lens distortion constant parameter 2 .lensDistortionValues[2] = 0.24f, // Lens distortion constant parameter 2
@ -50,32 +50,32 @@ int main(void)
.chromaAbCorrection[2] = 1.014f, // Chromatic aberration correction parameter 2 .chromaAbCorrection[2] = 1.014f, // Chromatic aberration correction parameter 2
.chromaAbCorrection[3] = 0.0f, // Chromatic aberration correction parameter 3 .chromaAbCorrection[3] = 0.0f, // Chromatic aberration correction parameter 3
}; };
// Load VR stereo config for VR device parameteres (Oculus Rift CV1 parameters) // Load VR stereo config for VR device parameteres (Oculus Rift CV1 parameters)
VrStereoConfig config = LoadVrStereoConfig(device); VrStereoConfig config = LoadVrStereoConfig(device);
// Distortion shader (uses device lens distortion and chroma) // Distortion shader (uses device lens distortion and chroma)
Shader distortion = LoadShader(0, TextFormat("resources/distortion%i.fs", GLSL_VERSION)); Shader distortion = LoadShader(0, TextFormat("resources/distortion%i.fs", GLSL_VERSION));
// Update distortion shader with lens and distortion-scale parameters // Update distortion shader with lens and distortion-scale parameters
SetShaderValue(distortion, GetShaderLocation(distortion, "leftLensCenter"), SetShaderValue(distortion, GetShaderLocation(distortion, "leftLensCenter"),
config.leftLensCenter, SHADER_UNIFORM_VEC2); config.leftLensCenter, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "rightLensCenter"), SetShaderValue(distortion, GetShaderLocation(distortion, "rightLensCenter"),
config.rightLensCenter, SHADER_UNIFORM_VEC2); config.rightLensCenter, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "leftScreenCenter"), SetShaderValue(distortion, GetShaderLocation(distortion, "leftScreenCenter"),
config.leftScreenCenter, SHADER_UNIFORM_VEC2); config.leftScreenCenter, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "rightScreenCenter"), SetShaderValue(distortion, GetShaderLocation(distortion, "rightScreenCenter"),
config.rightScreenCenter, SHADER_UNIFORM_VEC2); config.rightScreenCenter, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "scale"), SetShaderValue(distortion, GetShaderLocation(distortion, "scale"),
config.scale, SHADER_UNIFORM_VEC2); config.scale, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "scaleIn"), SetShaderValue(distortion, GetShaderLocation(distortion, "scaleIn"),
config.scaleIn, SHADER_UNIFORM_VEC2); config.scaleIn, SHADER_UNIFORM_VEC2);
SetShaderValue(distortion, GetShaderLocation(distortion, "deviceWarpParam"), SetShaderValue(distortion, GetShaderLocation(distortion, "deviceWarpParam"),
device.lensDistortionValues, SHADER_UNIFORM_VEC4); device.lensDistortionValues, SHADER_UNIFORM_VEC4);
SetShaderValue(distortion, GetShaderLocation(distortion, "chromaAbParam"), SetShaderValue(distortion, GetShaderLocation(distortion, "chromaAbParam"),
device.chromaAbCorrection, SHADER_UNIFORM_VEC4); device.chromaAbCorrection, SHADER_UNIFORM_VEC4);
// Initialize framebuffer for stereo rendering // Initialize framebuffer for stereo rendering
// NOTE: Screen size should match HMD aspect ratio // NOTE: Screen size should match HMD aspect ratio
RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight()); RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight());
@ -121,9 +121,9 @@ int main(void)
EndMode3D(); EndMode3D();
EndVrStereoMode(); EndVrStereoMode();
EndTextureMode(); EndTextureMode();
BeginShaderMode(distortion); BeginShaderMode(distortion);
DrawTextureRec(target.texture, (Rectangle){ 0, 0, (float)target.texture.width, DrawTextureRec(target.texture, (Rectangle){ 0, 0, (float)target.texture.width,
(float)-target.texture.height }, (Vector2){ 0.0f, 0.0f }, WHITE); (float)-target.texture.height }, (Vector2){ 0.0f, 0.0f }, WHITE);
EndShaderMode(); EndShaderMode();
@ -136,7 +136,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadVrStereoConfig(config); // Unload stereo config UnloadVrStereoConfig(config); // Unload stereo config
UnloadRenderTexture(target); // Unload stereo render fbo UnloadRenderTexture(target); // Unload stereo render fbo
UnloadShader(distortion); // Unload distortion shader UnloadShader(distortion); // Unload distortion shader

View File

@ -64,13 +64,13 @@ int main(void)
// Recalculate random colors for the bars // Recalculate random colors for the bars
for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 }; for (int i = 0; i < 10; i++) colors[i] = (Color){ GetRandomValue(100, 250), GetRandomValue(50, 150), GetRandomValue(10, 100), 255 };
} }
// Update virtual mouse (clamped mouse value behind game screen) // Update virtual mouse (clamped mouse value behind game screen)
Vector2 mouse = GetMousePosition(); Vector2 mouse = GetMousePosition();
Vector2 virtualMouse = { 0 }; Vector2 virtualMouse = { 0 };
virtualMouse.x = (mouse.x - (GetScreenWidth() - (gameScreenWidth*scale))*0.5f)/scale; virtualMouse.x = (mouse.x - (GetScreenWidth() - (gameScreenWidth*scale))*0.5f)/scale;
virtualMouse.y = (mouse.y - (GetScreenHeight() - (gameScreenHeight*scale))*0.5f)/scale; virtualMouse.y = (mouse.y - (GetScreenHeight() - (gameScreenHeight*scale))*0.5f)/scale;
virtualMouse = ClampValue(virtualMouse, (Vector2){ 0, 0 }, (Vector2){ gameScreenWidth, gameScreenHeight }); virtualMouse = ClampValue(virtualMouse, (Vector2){ 0, 0 }, (Vector2){ (float)gameScreenWidth, (float)gameScreenHeight });
// Apply the same transformation as the virtual mouse to the real mouse (i.e. to work with raygui) // Apply the same transformation as the virtual mouse to the real mouse (i.e. to work with raygui)
//SetMouseOffset(-(GetScreenWidth() - (gameScreenWidth*scale))*0.5f, -(GetScreenHeight() - (gameScreenHeight*scale))*0.5f); //SetMouseOffset(-(GetScreenWidth() - (gameScreenWidth*scale))*0.5f, -(GetScreenHeight() - (gameScreenHeight*scale))*0.5f);
@ -90,7 +90,7 @@ int main(void)
for (int i = 0; i < 10; i++) DrawRectangle(0, (gameScreenHeight/10)*i, gameScreenWidth, gameScreenHeight/10, colors[i]); 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, WHITE); DrawText("If executed inside a window,\nyou can resize the window,\nand see the screen scaling!", 10, 25, 20, WHITE);
DrawText(TextFormat("Default Mouse: [%i , %i]", (int)mouse.x, (int)mouse.y), 350, 25, 20, GREEN); DrawText(TextFormat("Default Mouse: [%i , %i]", (int)mouse.x, (int)mouse.y), 350, 25, 20, GREEN);
DrawText(TextFormat("Virtual Mouse: [%i , %i]", (int)virtualMouse.x, (int)virtualMouse.y), 350, 55, 20, YELLOW); DrawText(TextFormat("Virtual Mouse: [%i , %i]", (int)virtualMouse.x, (int)virtualMouse.y), 350, 55, 20, YELLOW);

View File

@ -1,39 +1,39 @@
/* /*
WELCOME raylib EXAMPLES CONTRIBUTOR! WELCOME raylib EXAMPLES CONTRIBUTOR!
This is a bsasic template to anyone ready to contribute with some code example for the library, This is a basic template to anyone ready to contribute with some code example for the library,
here there are some guidelines on how to create an example to be included in raylib here there are some guidelines on how to create an example to be included in raylib
1. File naming: <module>_<description> - Lower case filename, words separated by underscore, 1. File naming: <module>_<description> - Lower case filename, words separated by underscore,
no more than 3-4 words in total to describe the example. <module> referes to the primary no more than 3-4 words in total to describe the example. <module> referes to the primary
raylib module the example is more related with (code, shapes, textures, models, shaders, raudio). raylib module the example is more related with (code, shapes, textures, models, shaders, raudio).
i.e: core_input_multitouch, shapes_lines_bezier, shaders_palette_switch i.e: core_input_multitouch, shapes_lines_bezier, shaders_palette_switch
2. Follow below template structure, example info should list the module, the short description 2. Follow below template structure, example info should list the module, the short description
and the author of the example, twitter or github info could be also provided for the author. and the author of the example, twitter or github info could be also provided for the author.
Short description should also be used on the title of the window. Short description should also be used on the title of the window.
3. Code should be organized by sections:[Initialization]- [Update] - [Draw] - [De-Initialization] 3. Code should be organized by sections:[Initialization]- [Update] - [Draw] - [De-Initialization]
Place your code between the dotted lines for every section, please don't mix update logic with drawing Place your code between the dotted lines for every section, please don't mix update logic with drawing
and remember to unload all loaded resources. and remember to unload all loaded resources.
4. Code should follow raylib conventions: https://github.com/raysan5/raylib/wiki/raylib-coding-conventions 4. Code should follow raylib conventions: https://github.com/raysan5/raylib/wiki/raylib-coding-conventions
Try to be very organized, using line-breaks appropiately. Try to be very organized, using line-breaks appropiately.
5. Add comments to the specific parts of code the example is focus on. 5. Add comments to the specific parts of code the example is focus on.
Don't abuse with comments, try to be clear and impersonal on the comments. Don't abuse with comments, try to be clear and impersonal on the comments.
6. Try to keep the example simple, under 300 code lines if possible. Try to avoid external dependencies. 6. Try to keep the example simple, under 300 code lines if possible. Try to avoid external dependencies.
Try to avoid defining functions outside the main(). Example should be as self-contained as possible. Try to avoid defining functions outside the main(). Example should be as self-contained as possible.
7. About external resources, they should be placed in a [resources] folder and those resources 7. About external resources, they should be placed in a [resources] folder and those resources
should be open and free for use and distribution. Avoid propietary content. should be open and free for use and distribution. Avoid propietary content.
8. Try to keep the example simple but with a creative touch. 8. Try to keep the example simple but with a creative touch.
Simple but beautiful examples are more appealing to users! Simple but beautiful examples are more appealing to users!
9. In case of additional information is required, just come to raylib Discord channel: example-contributions 9. In case of additional information is required, just come to raylib Discord channel: example-contributions
10. Have fun! 10. Have fun!
*/ */
@ -58,9 +58,9 @@ int main()
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window"); InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
// TODO: Load resources / Initialize variables at this point // TODO: Load resources / Initialize variables at this point
SetTargetFPS(60); SetTargetFPS(60);
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -79,7 +79,7 @@ int main()
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw everything that requires to be drawn at this point: // TODO: Draw everything that requires to be drawn at this point:
DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); // Example DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY); // Example
EndDrawing(); EndDrawing();
@ -88,11 +88,11 @@ int main()
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// TODO: Unload all loaded resources at this point // TODO: Unload all loaded resources at this point
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View File

@ -11,7 +11,7 @@
* *
******************************************************************************************** ********************************************************************************************
* *
* To export a model from blender, make sure it is not posed, the vertices need to be in the * 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. * 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. * and that the scale of your models is set to 0. Scaling can be done from the export menu.
* *
@ -100,7 +100,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture UnloadTexture(texture); // Unload texture
// Unload model animations data // Unload model animations data
for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]);
RL_FREE(anims); RL_FREE(anims);

View File

@ -11,7 +11,7 @@
* *
******************************************************************************************** ********************************************************************************************
* *
* To export a model from blender, make sure it is not posed, the vertices need to be in the * 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. * 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. * and that the scale of your models is set to 0. Scaling can be done from the export menu.
* *
@ -68,13 +68,13 @@ int main(void)
if (IsKeyDown(KEY_SPACE)) if (IsKeyDown(KEY_SPACE))
{ {
animFrameCounter += animationDirection; animFrameCounter += animationDirection;
if (animFrameCounter >= anims[0].frameCount || animFrameCounter <= 0) if (animFrameCounter >= anims[0].frameCount || animFrameCounter <= 0)
{ {
animationDirection *= -1; animationDirection *= -1;
animFrameCounter += animationDirection; animFrameCounter += animationDirection;
} }
UpdateModelAnimation(model, anims[0], animFrameCounter); UpdateModelAnimation(model, anims[0], animFrameCounter);
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -108,7 +108,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// UnloadTexture(texture); // Unload texture // UnloadTexture(texture); // Unload texture
// Unload model animations data // Unload model animations data
for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]); for (int i = 0; i < animsCount; i++) UnloadModelAnimation(anims[i]);
RL_FREE(anims); RL_FREE(anims);

View File

@ -11,7 +11,7 @@
* *
******************************************************************************************** ********************************************************************************************
* *
* To export a model from blender, make sure it is not posed, the vertices need to be in the * 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. * 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. * and that the scale of your models is set to 0. Scaling can be done from the export menu.
* *
@ -41,14 +41,14 @@ int main(void)
camera.projection = CAMERA_PERSPECTIVE; // Camera mode type camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
Model model[MAX_MODELS] = { 0 }; Model model[MAX_MODELS] = { 0 };
model[0] = LoadModel("resources/gltf/raylib_32x32.glb"); model[0] = LoadModel("resources/gltf/raylib_32x32.glb");
model[1] = LoadModel("resources/gltf/rigged_figure.glb"); model[1] = LoadModel("resources/gltf/rigged_figure.glb");
model[2] = LoadModel("resources/gltf/GearboxAssy.glb"); model[2] = LoadModel("resources/gltf/GearboxAssy.glb");
model[3] = LoadModel("resources/gltf/BoxAnimated.glb"); model[3] = LoadModel("resources/gltf/BoxAnimated.glb");
model[4] = LoadModel("resources/gltf/AnimatedTriangle.gltf"); model[4] = LoadModel("resources/gltf/AnimatedTriangle.gltf");
model[5] = LoadModel("resources/gltf/AnimatedMorphCube.glb"); model[5] = LoadModel("resources/gltf/AnimatedMorphCube.glb");
int currentModel = 0; int currentModel = 0;
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
@ -64,13 +64,13 @@ int main(void)
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); UpdateCamera(&camera);
if (IsKeyReleased(KEY_RIGHT)) if (IsKeyReleased(KEY_RIGHT))
{ {
currentModel++; currentModel++;
if (currentModel == MAX_MODELS) currentModel = 0; if (currentModel == MAX_MODELS) currentModel = 0;
} }
if (IsKeyReleased(KEY_LEFT)) if (IsKeyReleased(KEY_LEFT))
{ {
currentModel--; currentModel--;

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

View File

@ -9,7 +9,7 @@
* - GLTF > Modern text/binary file format, includes lot of information and it could * - 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 * also reference external files, raylib will try loading mesh and materials data
* - IQM > Binary file format including mesh vertex data but also animation data, * - IQM > Binary file format including mesh vertex data but also animation data,
* raylib can load .iqm animations. * raylib can load .iqm animations.
* *
* This example has been created using raylib 2.6 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
@ -42,8 +42,8 @@ int main(void)
model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set map diffuse texture model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set map diffuse texture
Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 position = { 0.0f, 0.0f, 0.0f }; // Set model position
BoundingBox bounds = MeshBoundingBox(model.meshes[0]); // Set model bounds BoundingBox bounds = GetMeshBoundingBox(model.meshes[0]); // Set model bounds
// NOTE: bounds are calculated from the original size of the model, // NOTE: bounds are calculated from the original size of the model,
// if model is scaled on drawing, bounds must be also scaled // if model is scaled on drawing, bounds must be also scaled
@ -61,7 +61,7 @@ int main(void)
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); UpdateCamera(&camera);
// Load new models/textures on drag&drop // Load new models/textures on drag&drop
if (IsFileDropped()) if (IsFileDropped())
{ {
@ -78,8 +78,8 @@ int main(void)
model = LoadModel(droppedFiles[0]); // Load new model model = LoadModel(droppedFiles[0]); // Load new model
model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set current map diffuse texture model.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set current map diffuse texture
bounds = MeshBoundingBox(model.meshes[0]); bounds = GetMeshBoundingBox(model.meshes[0]);
// TODO: Move camera position from target enough distance to visualize model properly // TODO: Move camera position from target enough distance to visualize model properly
} }
else if (IsFileExtension(droppedFiles[0], ".png")) // Texture file formats supported else if (IsFileExtension(droppedFiles[0], ".png")) // Texture file formats supported
@ -95,7 +95,7 @@ int main(void)
} }
// Select model on mouse click // Select model on mouse click
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
// Check collision between ray and box // Check collision between ray and box
if (CheckCollisionRayBox(GetMouseRay(GetMousePosition(), camera), bounds)) selected = !selected; if (CheckCollisionRayBox(GetMouseRay(GetMousePosition(), camera), bounds)) selected = !selected;
@ -118,7 +118,7 @@ int main(void)
if (selected) DrawBoundingBox(bounds, GREEN); // Draw selection box if (selected) DrawBoundingBox(bounds, GREEN); // Draw selection box
EndMode3D(); EndMode3D();
DrawText("Drag & drop model to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY); DrawText("Drag & drop model to load mesh/texture.", 10, GetScreenHeight() - 20, 10, DARKGRAY);
if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN); if (selected) DrawText("MODEL SELECTED", GetScreenWidth() - 110, 10, 10, GREEN);

View File

@ -133,7 +133,7 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
Material mat = LoadMaterialDefault(); // Initialize material to default Material mat = LoadMaterialDefault(); // Initialize material to default
// Load PBR shader (requires several maps) // Load PBR shader (requires several maps)
mat.shader = LoadShader(TextFormat("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION), mat.shader = LoadShader(TextFormat("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION));
// Get required locations points for PBR material // Get required locations points for PBR material
@ -160,14 +160,14 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
mat.maps[MATERIAL_MAP_METALNESS].texture = LoadTexture("resources/pbr/trooper_metalness.png"); mat.maps[MATERIAL_MAP_METALNESS].texture = LoadTexture("resources/pbr/trooper_metalness.png");
mat.maps[MATERIAL_MAP_ROUGHNESS].texture = LoadTexture("resources/pbr/trooper_roughness.png"); mat.maps[MATERIAL_MAP_ROUGHNESS].texture = LoadTexture("resources/pbr/trooper_roughness.png");
mat.maps[MATERIAL_MAP_OCCLUSION].texture = LoadTexture("resources/pbr/trooper_ao.png"); mat.maps[MATERIAL_MAP_OCCLUSION].texture = LoadTexture("resources/pbr/trooper_ao.png");
// Set textures filtering for better quality // Set textures filtering for better quality
SetTextureFilter(mat.maps[MATERIAL_MAP_ALBEDO].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MATERIAL_MAP_ALBEDO].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MATERIAL_MAP_NORMAL].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MATERIAL_MAP_NORMAL].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MATERIAL_MAP_METALNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MATERIAL_MAP_METALNESS].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MATERIAL_MAP_ROUGHNESS].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MATERIAL_MAP_ROUGHNESS].texture, FILTER_BILINEAR);
SetTextureFilter(mat.maps[MATERIAL_MAP_OCCLUSION].texture, FILTER_BILINEAR); SetTextureFilter(mat.maps[MATERIAL_MAP_OCCLUSION].texture, FILTER_BILINEAR);
// Enable sample usage in shader for assigned textures // Enable sample usage in shader for assigned textures
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "albedo.useSampler"), (int[1]){ 1 }, SHADER_UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "albedo.useSampler"), (int[1]){ 1 }, SHADER_UNIFORM_INT);
SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "normals.useSampler"), (int[1]){ 1 }, SHADER_UNIFORM_INT); SetShaderValue(mat.shader, GetShaderLocation(mat.shader, "normals.useSampler"), (int[1]){ 1 }, SHADER_UNIFORM_INT);
@ -186,13 +186,13 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
mat.maps[MATERIAL_MAP_OCCLUSION].value = 1.0f; mat.maps[MATERIAL_MAP_OCCLUSION].value = 1.0f;
mat.maps[MATERIAL_MAP_EMISSION].value = 0.5f; mat.maps[MATERIAL_MAP_EMISSION].value = 0.5f;
mat.maps[MATERIAL_MAP_HEIGHT].value = 0.5f; mat.maps[MATERIAL_MAP_HEIGHT].value = 0.5f;
// Generate cubemap from panorama texture // Generate cubemap from panorama texture
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
Texture2D panorama = LoadTexture("resources/dresden_square_2k.hdr"); Texture2D panorama = LoadTexture("resources/dresden_square_2k.hdr");
// Load equirectangular to cubemap shader // Load equirectangular to cubemap shader
Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION), Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/pbr.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/pbr.fs", GLSL_VERSION));
SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT); SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
@ -200,33 +200,33 @@ static Material LoadMaterialPBR(Color albedo, float metalness, float roughness)
UnloadTexture(panorama); UnloadTexture(panorama);
UnloadShader(shdrCubemap); UnloadShader(shdrCubemap);
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
// Generate irradiance map from cubemap texture // Generate irradiance map from cubemap texture
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
// Load irradiance (GI) calculation shader // Load irradiance (GI) calculation shader
Shader shdrIrradiance = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), Shader shdrIrradiance = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/irradiance.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/irradiance.fs", GLSL_VERSION));
SetShaderValue(shdrIrradiance, GetShaderLocation(shdrIrradiance, "environmentMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT); SetShaderValue(shdrIrradiance, GetShaderLocation(shdrIrradiance, "environmentMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
mat.maps[MATERIAL_MAP_IRRADIANCE].texture = GenTextureIrradiance(shdrIrradiance, cubemap, IRRADIANCE_SIZE); mat.maps[MATERIAL_MAP_IRRADIANCE].texture = GenTextureIrradiance(shdrIrradiance, cubemap, IRRADIANCE_SIZE);
UnloadShader(shdrIrradiance); UnloadShader(shdrIrradiance);
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
// Generate prefilter map from cubemap texture // Generate prefilter map from cubemap texture
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
// Load reflection prefilter calculation shader // Load reflection prefilter calculation shader
Shader shdrPrefilter = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), Shader shdrPrefilter = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/prefilter.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/prefilter.fs", GLSL_VERSION));
SetShaderValue(shdrPrefilter, GetShaderLocation(shdrPrefilter, "environmentMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT); SetShaderValue(shdrPrefilter, GetShaderLocation(shdrPrefilter, "environmentMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
mat.maps[MATERIAL_MAP_PREFILTER].texture = GenTexturePrefilter(shdrPrefilter, cubemap, PREFILTERED_SIZE); mat.maps[MATERIAL_MAP_PREFILTER].texture = GenTexturePrefilter(shdrPrefilter, cubemap, PREFILTERED_SIZE);
UnloadTexture(cubemap); UnloadTexture(cubemap);
UnloadShader(shdrPrefilter); UnloadShader(shdrPrefilter);
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
// Generate BRDF (bidirectional reflectance distribution function) texture (using shader) // Generate BRDF (bidirectional reflectance distribution function) texture (using shader)
//-------------------------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------------------------
Shader shdrBRDF = LoadShader(TextFormat("resources/shaders/glsl%i/brdf.vs", GLSL_VERSION), Shader shdrBRDF = LoadShader(TextFormat("resources/shaders/glsl%i/brdf.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/brdf.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/brdf.fs", GLSL_VERSION));
mat.maps[MATERIAL_MAP_BRDG].texture = GenTextureBRDF(shdrBRDF, BRDF_SIZE); mat.maps[MATERIAL_MAP_BRDG].texture = GenTextureBRDF(shdrBRDF, BRDF_SIZE);
@ -453,7 +453,7 @@ static TextureCubemap GenTexturePrefilter(Shader shader, TextureCubemap cubemap,
{ {
rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_VIEW], fboViews[i]); rlSetUniformMatrix(shader.locs[SHADER_LOC_MATRIX_VIEW], fboViews[i]);
rlFramebufferAttach(fbo, prefilter.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X + i, mip); rlFramebufferAttach(fbo, prefilter.id, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_CUBEMAP_POSITIVE_X + i, mip);
rlClearScreenBuffers(); rlClearScreenBuffers();
rlLoadDrawCube(); rlLoadDrawCube();
} }

View File

@ -11,7 +11,58 @@
#include "raylib.h" #include "raylib.h"
#define NUM_MODELS 8 // Parametric 3d shapes to generate #define NUM_MODELS 9 // Parametric 3d shapes to generate
void AllocateMeshData(Mesh* mesh, int triangleCount)
{
mesh->vertexCount = triangleCount * 3;
mesh->triangleCount = triangleCount;
mesh->vertices = (float*)MemAlloc(mesh->vertexCount * 3 * sizeof(float));
mesh->texcoords = (float*)MemAlloc(mesh->vertexCount * 2 * sizeof(float));
mesh->normals = (float*)MemAlloc(mesh->vertexCount * 3 * sizeof(float));
}
// generate a simple triangle mesh from code
Mesh MakeMesh()
{
Mesh mesh = { 0 };
AllocateMeshData(&mesh, 1);
// vertex at the origin
mesh.vertices[0] = 0;
mesh.vertices[1] = 0;
mesh.vertices[2] = 0;
mesh.normals[0] = 0;
mesh.normals[1] = 1;
mesh.normals[2] = 0;
mesh.texcoords[0] = 0;
mesh.texcoords[1] = 0;
// vertex at 1,0,2
mesh.vertices[3] = 1;
mesh.vertices[4] = 0;
mesh.vertices[5] = 2;
mesh.normals[3] = 0;
mesh.normals[4] = 1;
mesh.normals[5] = 0;
mesh.texcoords[2] = 0.5f;
mesh.texcoords[3] = 1.0f;
// vertex at 2,0,0
mesh.vertices[6] = 2;
mesh.vertices[7] = 0;
mesh.vertices[8] = 0;
mesh.normals[6] = 0;
mesh.normals[7] = 1;
mesh.normals[8] = 0;
mesh.texcoords[4] = 1;
mesh.texcoords[5] =0;
UploadMesh(&mesh, false);
return mesh;
}
int main(void) int main(void)
{ {
@ -37,6 +88,7 @@ int main(void)
models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32)); models[5] = LoadModelFromMesh(GenMeshTorus(0.25f, 4.0f, 16, 32));
models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128)); models[6] = LoadModelFromMesh(GenMeshKnot(1.0f, 2.0f, 16, 128));
models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f)); models[7] = LoadModelFromMesh(GenMeshPoly(5, 2.0f));
models[8] = LoadModelFromMesh(MakeMesh());
// Set checked texture as default diffuse component for all models material // Set checked texture as default diffuse component for all models material
for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; for (int i = 0; i < NUM_MODELS; i++) models[i].materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture;
@ -61,7 +113,7 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update internal camera and our camera UpdateCamera(&camera); // Update internal camera and our camera
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures currentModel = (currentModel + 1)%NUM_MODELS; // Cycle between the textures
} }
@ -86,9 +138,8 @@ int main(void)
BeginMode3D(camera); BeginMode3D(camera);
DrawModel(models[currentModel], position, 1.0f, WHITE); DrawModel(models[currentModel], position, 1.0f, WHITE);
DrawGrid(10, 1.0);
DrawGrid(10, 1.0);
EndMode3D(); EndMode3D();
@ -106,6 +157,7 @@ int main(void)
case 5: DrawText("TORUS", 680, 10, 20, DARKBLUE); break; case 5: DrawText("TORUS", 680, 10, 20, DARKBLUE); break;
case 6: DrawText("KNOT", 680, 10, 20, DARKBLUE); break; case 6: DrawText("KNOT", 680, 10, 20, DARKBLUE); break;
case 7: DrawText("POLY", 680, 10, 20, DARKBLUE); break; case 7: DrawText("POLY", 680, 10, 20, DARKBLUE); break;
case 8: DrawText("Parametric(custom)", 580, 10, 20, DARKBLUE); break;
default: break; default: break;
} }

View File

@ -40,7 +40,7 @@ int main(void)
tower.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set model diffuse texture tower.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; // Set model diffuse texture
Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position Vector3 towerPos = { 0.0f, 0.0f, 0.0f }; // Set model position
BoundingBox towerBBox = MeshBoundingBox(tower.meshes[0]); // Get mesh bounding box BoundingBox towerBBox = GetMeshBoundingBox(tower.meshes[0]); // Get mesh bounding box
bool hitMeshBBox = false; bool hitMeshBBox = false;
bool hitTriangle = false; bool hitTriangle = false;

View File

@ -135,7 +135,7 @@ void DrawSphereBasic(Color color)
{ {
int rings = 16; int rings = 16;
int slices = 16; int slices = 16;
// Make sure there is enough space in the internal render batch // Make sure there is enough space in the internal render batch
// buffer to store all required vertex, batch is reseted if required // buffer to store all required vertex, batch is reseted if required
rlCheckRenderBatchLimit((rings + 2)*slices*6); rlCheckRenderBatchLimit((rings + 2)*slices*6);

View File

@ -36,12 +36,12 @@ int main(void)
// Load skybox model // Load skybox model
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Model skybox = LoadModelFromMesh(cube); Model skybox = LoadModelFromMesh(cube);
bool useHDR = false; bool useHDR = false;
// Load skybox shader and set required locations // Load skybox shader and set required locations
// NOTE: Some locations are automatically set at shader loading // NOTE: Some locations are automatically set at shader loading
skybox.materials[0].shader = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION), skybox.materials[0].shader = LoadShader(TextFormat("resources/shaders/glsl%i/skybox.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/skybox.fs", GLSL_VERSION));
SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MATERIAL_MAP_CUBEMAP }, SHADER_UNIFORM_INT); SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "environmentMap"), (int[1]){ MATERIAL_MAP_CUBEMAP }, SHADER_UNIFORM_INT);
@ -49,7 +49,7 @@ int main(void)
SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "vflipped"), (int[1]){ useHDR ? 1 : 0 }, SHADER_UNIFORM_INT); SetShaderValue(skybox.materials[0].shader, GetShaderLocation(skybox.materials[0].shader, "vflipped"), (int[1]){ useHDR ? 1 : 0 }, SHADER_UNIFORM_INT);
// Load cubemap shader and setup required shader locations // Load cubemap shader and setup required shader locations
Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION), Shader shdrCubemap = LoadShader(TextFormat("resources/shaders/glsl%i/cubemap.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/cubemap.fs", GLSL_VERSION));
SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT); SetShaderValue(shdrCubemap, GetShaderLocation(shdrCubemap, "equirectangularMap"), (int[1]){ 0 }, SHADER_UNIFORM_INT);
@ -89,7 +89,7 @@ int main(void)
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
// Load new cubemap texture on drag&drop // Load new cubemap texture on drag&drop
if (IsFileDropped()) if (IsFileDropped())
{ {
@ -105,7 +105,7 @@ int main(void)
if (useHDR) if (useHDR)
{ {
Texture2D panorama = LoadTexture(droppedFiles[0]); Texture2D panorama = LoadTexture(droppedFiles[0]);
// Generate cubemap from panorama texture // Generate cubemap from panorama texture
skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8); skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture = GenTextureCubemap(shdrCubemap, panorama, 1024, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8);
UnloadTexture(panorama); UnloadTexture(panorama);
@ -132,16 +132,16 @@ int main(void)
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera); BeginMode3D(camera);
// We are inside the cube, we need to disable backface culling! // We are inside the cube, we need to disable backface culling!
rlDisableBackfaceCulling(); rlDisableBackfaceCulling();
rlDisableDepthMask(); rlDisableDepthMask();
DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE); DrawModel(skybox, (Vector3){0, 0, 0}, 1.0f, WHITE);
rlEnableBackfaceCulling(); rlEnableBackfaceCulling();
rlEnableDepthMask(); rlEnableDepthMask();
DrawGrid(10, 1.0f); DrawGrid(10, 1.0f);
EndMode3D(); EndMode3D();
if (useHDR) if (useHDR)
@ -159,7 +159,7 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadShader(skybox.materials[0].shader); UnloadShader(skybox.materials[0].shader);
UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture); UnloadTexture(skybox.materials[0].maps[MATERIAL_MAP_CUBEMAP].texture);
UnloadModel(skybox); // Unload skybox model UnloadModel(skybox); // Unload skybox model
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View File

@ -53,7 +53,7 @@ int main()
camera.position.x = (float)cos(cameraTime)*40.0f; camera.position.x = (float)cos(cameraTime)*40.0f;
camera.position.z = (float)sin(cameraTime)*40.0f; camera.position.z = (float)sin(cameraTime)*40.0f;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -64,11 +64,11 @@ int main()
DrawGrid(10, 5.0f); DrawGrid(10, 5.0f);
for (int x = 0; x < numBlocks; x++) for (int x = 0; x < numBlocks; x++)
{ {
for (int y = 0; y < numBlocks; y++) for (int y = 0; y < numBlocks; y++)
{ {
for (int z = 0; z < numBlocks; z++) for (int z = 0; z < numBlocks; z++)
{ {
// Scale of the blocks depends on x/y/z positions // Scale of the blocks depends on x/y/z positions
float blockScale = (x + y + z)/30.0f; float blockScale = (x + y + z)/30.0f;
@ -94,9 +94,9 @@ int main()
} }
} }
} }
EndMode3D(); EndMode3D();
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();

View File

@ -30,7 +30,7 @@ int main(void)
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 30.0f; // Camera field-of-view Y camera.fovy = 30.0f; // Camera field-of-view Y
camera.projection = CAMERA_PERSPECTIVE; // Camera type camera.projection = CAMERA_PERSPECTIVE; // Camera type
// Model loading // Model loading
// NOTE: Diffuse map loaded automatically // NOTE: Diffuse map loaded automatically
Model model = LoadModel("resources/plane/plane.gltf"); Model model = LoadModel("resources/plane/plane.gltf");
@ -77,8 +77,8 @@ int main(void)
// Tranformation matrix for rotations // Tranformation matrix for rotations
model.transform = MatrixRotateXYZ((Vector3){ DEG2RAD*pitch, DEG2RAD*yaw, DEG2RAD*roll }); model.transform = MatrixRotateXYZ((Vector3){ DEG2RAD*pitch, DEG2RAD*yaw, DEG2RAD*roll });
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -92,7 +92,7 @@ int main(void)
DrawGrid(10, 10.0f); DrawGrid(10, 10.0f);
EndMode3D(); EndMode3D();
// Draw controls info // Draw controls info
DrawRectangle(30, 370, 260, 70, Fade(GREEN, 0.5f)); DrawRectangle(30, 370, 260, 70, Fade(GREEN, 0.5f));
DrawRectangleLines(30, 370, 260, 70, Fade(DARKGREEN, 0.5f)); DrawRectangleLines(30, 370, 260, 70, Fade(DARKGREEN, 0.5f));
@ -107,7 +107,7 @@ int main(void)
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadModel(model); // Unload model data UnloadModel(model); // Unload model data
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View File

@ -40,16 +40,16 @@ static void NetworkConnect(void)
{ {
ping = true; ping = true;
connected = true; connected = true;
} }
else else
{ {
// If the client is connected, run the server code to check for a connection // If the client is connected, run the server code to check for a connection
if (clientConnected) if (clientConnected)
{ {
int active = CheckSockets(socketSet, 0); int active = CheckSockets(socketSet, 0);
if (active != 0) TraceLog(LOG_INFO, "There are currently %d socket(s) with data to be processed.", active); if (active != 0) TraceLog(LOG_INFO, "There are currently %d socket(s) with data to be processed.", active);
if (active > 0) if (active > 0)
{ {
if ((connection = SocketAccept(serverResult->socket, &connectionConfig)) != NULL) if ((connection = SocketAccept(serverResult->socket, &connectionConfig)) != NULL)
{ {
@ -58,7 +58,7 @@ static void NetworkConnect(void)
ping = true; ping = true;
} }
} }
} }
else else
{ {
// Check if we're connected every _delay_ seconds // Check if we're connected every _delay_ seconds
@ -66,7 +66,7 @@ static void NetworkConnect(void)
if (elapsed > delay) if (elapsed > delay)
{ {
if (IsSocketConnected(clientResult->socket)) clientConnected = true; if (IsSocketConnected(clientResult->socket)) clientConnected = true;
elapsed = 0.0f; elapsed = 0.0f;
} }
} }
@ -88,7 +88,7 @@ static void UpdateNetwork(void)
{ {
if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, msglen); if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, msglen);
if (IsSocketReady(serverResult->socket)) bytesRecv = SocketReceive(serverResult->socket, receiveBuffer, msglen); if (IsSocketReady(serverResult->socket)) bytesRecv = SocketReceive(serverResult->socket, receiveBuffer, msglen);
} }
else if (IsSocketReady(connection)) bytesRecv = SocketReceive(connection, receiveBuffer, msglen); else if (IsSocketReady(connection)) bytesRecv = SocketReceive(connection, receiveBuffer, msglen);
// If we received data, was that data a "Ping!" or a "Pong!" // If we received data, was that data a "Ping!" or a "Pong!"
@ -107,14 +107,14 @@ static void UpdateNetwork(void)
ping = false; ping = false;
if (serverConfig.type == SOCKET_UDP && clientConfig.type == SOCKET_UDP) SocketSend(clientResult->socket, pingmsg, msglen); if (serverConfig.type == SOCKET_UDP && clientConfig.type == SOCKET_UDP) SocketSend(clientResult->socket, pingmsg, msglen);
else SocketSend(clientResult->socket, pingmsg, msglen); else SocketSend(clientResult->socket, pingmsg, msglen);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
if (serverConfig.type == SOCKET_UDP && clientConfig.type == SOCKET_UDP) SocketSend(clientResult->socket, pongmsg, msglen); if (serverConfig.type == SOCKET_UDP && clientConfig.type == SOCKET_UDP) SocketSend(clientResult->socket, pongmsg, msglen);
else SocketSend(clientResult->socket, pongmsg, msglen); else SocketSend(clientResult->socket, pongmsg, msglen);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }
} }
@ -132,7 +132,7 @@ int main(void)
// Create the server: getaddrinfo + socket + setsockopt + bind + listen // Create the server: getaddrinfo + socket + setsockopt + bind + listen
serverResult = LoadSocketResult(); serverResult = LoadSocketResult();
if (!SocketCreate(&serverConfig, serverResult)) if (!SocketCreate(&serverConfig, serverResult))
{ {
TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status); TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status);
} }
@ -141,7 +141,7 @@ int main(void)
if (!SocketBind(&serverConfig, serverResult)) if (!SocketBind(&serverConfig, serverResult))
{ {
TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status); TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status);
} }
else else
{ {
if (!(serverConfig.type == SOCKET_UDP)) if (!(serverConfig.type == SOCKET_UDP))
@ -156,7 +156,7 @@ int main(void)
// Create the client: getaddrinfo + socket + setsockopt + connect (TCP only) // Create the client: getaddrinfo + socket + setsockopt + connect (TCP only)
clientResult = LoadSocketResult(); clientResult = LoadSocketResult();
if (!SocketCreate(&clientConfig, clientResult)) if (!SocketCreate(&clientConfig, clientResult))
{ {
TraceLog(LOG_WARNING, "Failed to open client: status %d, errno %d", clientResult->status, clientResult->socket->status); TraceLog(LOG_WARNING, "Failed to open client: status %d, errno %d", clientResult->status, clientResult->socket->status);
} }
@ -194,7 +194,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw relevant connection info // TODO: Draw relevant connection info
EndDrawing(); EndDrawing();
@ -204,7 +204,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -22,17 +22,17 @@ int main(void)
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [network] example - resolve host"); InitWindow(screenWidth, screenHeight, "raylib [network] example - resolve host");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
char buffer[ADDRESS_IPV6_ADDRSTRLEN]; char buffer[ADDRESS_IPV6_ADDRSTRLEN];
unsigned short port = 0; unsigned short port = 0;
AddressInformation *address = LoadAddressList(1); AddressInformation *address = LoadAddressList(1);
// Address info flags // Address info flags
// ADDRESS_INFO_NUMERICHOST // or try them in conjunction to // ADDRESS_INFO_NUMERICHOST // or try them in conjunction to
// ADDRESS_INFO_NUMERICSERV // specify custom behaviour from // ADDRESS_INFO_NUMERICSERV // specify custom behaviour from
// ADDRESS_INFO_DNS_ONLY // the function getaddrinfo() // ADDRESS_INFO_DNS_ONLY // the function getaddrinfo()
// ADDRESS_INFO_ALL // // ADDRESS_INFO_ALL //
// ADDRESS_INFO_FQDN // e.g. ADDRESS_INFO_CANONNAME | ADDRESS_INFO_NUMERICSERV // ADDRESS_INFO_FQDN // e.g. ADDRESS_INFO_CANONNAME | ADDRESS_INFO_NUMERICSERV
@ -70,7 +70,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -24,10 +24,10 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [network] example - tcp client"); InitWindow(screenWidth, screenHeight, "raylib [network] example - tcp client");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
const char *pingmsg = "Ping!"; const char *pingmsg = "Ping!";
const char *pongmsg = "Pong!"; const char *pongmsg = "Pong!";
bool ping = false; bool ping = false;
bool pong = false; bool pong = false;
float elapsed = 0.0f; float elapsed = 0.0f;
@ -35,12 +35,12 @@ int main(void)
bool connected = false; bool connected = false;
SocketConfig clientConfig = { SocketConfig clientConfig = {
.host = "127.0.0.1", .host = "127.0.0.1",
.port = "4950", .port = "4950",
.type = SOCKET_TCP, .type = SOCKET_TCP,
.nonblocking = true .nonblocking = true
}; };
SocketSet *socketSet = NULL; SocketSet *socketSet = NULL;
SocketResult *clientResult = NULL; SocketResult *clientResult = NULL;
char receiveBuffer[512] = { 0 }; char receiveBuffer[512] = { 0 };
@ -48,9 +48,9 @@ int main(void)
// Create the client: getaddrinfo + socket + setsockopt + connect (TCP only) // Create the client: getaddrinfo + socket + setsockopt + connect (TCP only)
clientResult = LoadSocketResult(); clientResult = LoadSocketResult();
if (!SocketCreate(&clientConfig, clientResult)) TraceLog(LOG_WARNING, "Failed to open client: status %d, errno %d", clientResult->status, clientResult->socket->status); if (!SocketCreate(&clientConfig, clientResult)) TraceLog(LOG_WARNING, "Failed to open client: status %d, errno %d", clientResult->status, clientResult->socket->status);
else else
{ {
if (!(clientConfig.type == SOCKET_UDP)) if (!(clientConfig.type == SOCKET_UDP))
{ {
if (!SocketConnect(&clientConfig, clientResult)) TraceLog(LOG_WARNING, "Failed to connect to server: status %d, errno %d", clientResult->status, clientResult->socket->status); if (!SocketConnect(&clientConfig, clientResult)) TraceLog(LOG_WARNING, "Failed to connect to server: status %d, errno %d", clientResult->status, clientResult->socket->status);
} }
@ -83,7 +83,7 @@ int main(void)
if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1); if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1);
// If we received data, was that data a "Ping!" or a "Pong!" // If we received data, was that data a "Ping!" or a "Pong!"
if (bytesRecv > 0) if (bytesRecv > 0)
{ {
if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; } if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; }
if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; } if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; }
@ -91,19 +91,19 @@ int main(void)
// After each delay has expired, send a response "Ping!" for a "Pong!" and vice versa // After each delay has expired, send a response "Ping!" for a "Pong!" and vice versa
elapsed += GetFrameTime(); elapsed += GetFrameTime();
if (elapsed > delay) if (elapsed > delay)
{ {
if (ping) if (ping)
{ {
ping = false; ping = false;
SocketSend(clientResult->socket, pingmsg, (int)strlen(pingmsg) + 1); SocketSend(clientResult->socket, pingmsg, (int)strlen(pingmsg) + 1);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
SocketSend(clientResult->socket, pongmsg, (int)strlen(pingmsg) + 1); SocketSend(clientResult->socket, pongmsg, (int)strlen(pingmsg) + 1);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }
} }
@ -124,7 +124,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw relevant connection info // TODO: Draw relevant connection info
EndDrawing(); EndDrawing();
@ -134,7 +134,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -24,10 +24,10 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [network] example - tcp server"); InitWindow(screenWidth, screenHeight, "raylib [network] example - tcp server");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
const char *pingmsg = "Ping!"; const char *pingmsg = "Ping!";
const char *pongmsg = "Pong!"; const char *pongmsg = "Pong!";
bool ping = false; bool ping = false;
bool pong = false; bool pong = false;
float elapsed = 0.0f; float elapsed = 0.0f;
@ -35,32 +35,32 @@ int main(void)
bool connected = false; bool connected = false;
SocketConfig serverConfig = { SocketConfig serverConfig = {
.host = "127.0.0.1", .host = "127.0.0.1",
.port = "4950", .port = "4950",
.type = SOCKET_TCP, .type = SOCKET_TCP,
.server = true, .server = true,
.nonblocking = true .nonblocking = true
}; };
SocketConfig connectionConfig = { .nonblocking = true }; SocketConfig connectionConfig = { .nonblocking = true };
Socket *connection = NULL; Socket *connection = NULL;
SocketSet *socketSet = NULL; SocketSet *socketSet = NULL;
SocketResult *serverResult = NULL; SocketResult *serverResult = NULL;
char receiveBuffer[512] = { 0 }; char receiveBuffer[512] = { 0 };
// Create the server: getaddrinfo + socket + setsockopt + bind + listen // Create the server: getaddrinfo + socket + setsockopt + bind + listen
serverResult = LoadSocketResult(); serverResult = LoadSocketResult();
if (!SocketCreate(&serverConfig, serverResult)) if (!SocketCreate(&serverConfig, serverResult))
{ {
TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status); TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status);
} }
else else
{ {
if (!SocketBind(&serverConfig, serverResult)) if (!SocketBind(&serverConfig, serverResult))
{ {
TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status); TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status);
} }
else else
{ {
if (!(serverConfig.type == SOCKET_UDP)) if (!(serverConfig.type == SOCKET_UDP))
@ -107,17 +107,17 @@ int main(void)
elapsed += GetFrameTime(); elapsed += GetFrameTime();
if (elapsed > delay) if (elapsed > delay)
{ {
if (ping) if (ping)
{ {
ping = false; ping = false;
SocketSend(connection, pingmsg, (int)strlen(pingmsg) + 1); SocketSend(connection, pingmsg, (int)strlen(pingmsg) + 1);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
SocketSend(connection, pongmsg, (int)strlen(pingmsg) + 1); SocketSend(connection, pongmsg, (int)strlen(pingmsg) + 1);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }
} }
@ -127,9 +127,9 @@ int main(void)
int active = CheckSockets(socketSet, 0); int active = CheckSockets(socketSet, 0);
if (active != 0) TraceLog(LOG_DEBUG, "There are currently %d socket(s) with data to be processed.", active); if (active != 0) TraceLog(LOG_DEBUG, "There are currently %d socket(s) with data to be processed.", active);
if (active > 0) if (active > 0)
{ {
if ((connection = SocketAccept(serverResult->socket, &connectionConfig)) != NULL) if ((connection = SocketAccept(serverResult->socket, &connectionConfig)) != NULL)
{ {
AddSocket(socketSet, connection); AddSocket(socketSet, connection);
connected = true; connected = true;
@ -144,7 +144,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw relevant connection info // TODO: Draw relevant connection info
EndDrawing(); EndDrawing();
@ -154,7 +154,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -85,7 +85,7 @@ void test_resolve_host()
const char *address = "localhost"; const char *address = "localhost";
const char *port = "80"; const char *port = "80";
AddressInformation *addr = LoadAddressList(3); AddressInformation *addr = LoadAddressList(3);
int count = ResolveHost(address, port, ADDRESS_TYPE_ANY, 0, addr); int count = ResolveHost(address, port, ADDRESS_TYPE_ANY, 0, addr);
assert(GetAddressFamily(addr[0]) == ADDRESS_TYPE_IPV6); assert(GetAddressFamily(addr[0]) == ADDRESS_TYPE_IPV6);
assert(GetAddressFamily(addr[1]) == ADDRESS_TYPE_IPV4); assert(GetAddressFamily(addr[1]) == ADDRESS_TYPE_IPV4);
@ -122,9 +122,9 @@ int main(void)
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [network] example - network test"); InitWindow(screenWidth, screenHeight, "raylib [network] example - network test");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
// Run some tests // Run some tests
test_resolve_host(); test_resolve_host();
//test_socket_create(); //test_socket_create();
@ -146,7 +146,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw relevant connection info // TODO: Draw relevant connection info
EndDrawing(); EndDrawing();
@ -156,7 +156,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -24,22 +24,22 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [network] example - udp client"); InitWindow(screenWidth, screenHeight, "raylib [network] example - udp client");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
const char *pingmsg = "Ping!"; const char *pingmsg = "Ping!";
const char *pongmsg = "Pong!"; const char *pongmsg = "Pong!";
bool ping = true; bool ping = true;
bool pong = false; bool pong = false;
float elapsed = 0.0f; float elapsed = 0.0f;
float delay = 1.0f; float delay = 1.0f;
SocketConfig clientConfig = { SocketConfig clientConfig = {
.host = "127.0.0.1", .host = "127.0.0.1",
.port = "4950", .port = "4950",
.type = SOCKET_UDP, .type = SOCKET_UDP,
.nonblocking = true .nonblocking = true
}; };
SocketResult *clientResult = NULL; SocketResult *clientResult = NULL;
SocketSet *socketSet = NULL; SocketSet *socketSet = NULL;
char receiveBuffer[512] = { 0 }; char receiveBuffer[512] = { 0 };
@ -76,7 +76,7 @@ int main(void)
if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1); if (IsSocketReady(clientResult->socket)) bytesRecv = SocketReceive(clientResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1);
// If we received data, was that data a "Ping!" or a "Pong!" // If we received data, was that data a "Ping!" or a "Pong!"
if (bytesRecv > 0) if (bytesRecv > 0)
{ {
if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; } if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; }
if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; } if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; }
@ -86,17 +86,17 @@ int main(void)
elapsed += GetFrameTime(); elapsed += GetFrameTime();
if (elapsed > delay) if (elapsed > delay)
{ {
if (ping) if (ping)
{ {
ping = false; ping = false;
SocketSend(clientResult->socket, pingmsg, (int)strlen(pingmsg) + 1); SocketSend(clientResult->socket, pingmsg, (int)strlen(pingmsg) + 1);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
SocketSend(clientResult->socket, pongmsg, (int)strlen(pongmsg) + 1); SocketSend(clientResult->socket, pongmsg, (int)strlen(pongmsg) + 1);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -106,7 +106,7 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// TODO: Draw relevant connection info // TODO: Draw relevant connection info
EndDrawing(); EndDrawing();
@ -116,7 +116,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -24,30 +24,30 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [network] example - udp server"); InitWindow(screenWidth, screenHeight, "raylib [network] example - udp server");
InitNetworkDevice(); // Init network communications InitNetworkDevice(); // Init network communications
const char *pingmsg = "Ping!"; const char *pingmsg = "Ping!";
const char *pongmsg = "Pong!"; const char *pongmsg = "Pong!";
bool ping = false; bool ping = false;
bool pong = false; bool pong = false;
float elapsed = 0.0f; float elapsed = 0.0f;
float delay = 1.0f; float delay = 1.0f;
SocketConfig serverConfig = { SocketConfig serverConfig = {
.host = "127.0.0.1", .host = "127.0.0.1",
.port = "4950", .port = "4950",
.server = true, .server = true,
.type = SOCKET_UDP, .type = SOCKET_UDP,
.nonblocking = true .nonblocking = true
}; };
SocketResult *serverResult = NULL; SocketResult *serverResult = NULL;
SocketSet *socketSet = NULL; SocketSet *socketSet = NULL;
char receiveBuffer[512] = { 0 }; char receiveBuffer[512] = { 0 };
// Create the server: getaddrinfo + socket + setsockopt + bind + listen // Create the server: getaddrinfo + socket + setsockopt + bind + listen
serverResult = LoadSocketResult(); serverResult = LoadSocketResult();
if (!SocketCreate(&serverConfig, serverResult)) TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status); if (!SocketCreate(&serverConfig, serverResult)) TraceLog(LOG_WARNING, "Failed to open server: status %d, errno %d", serverResult->status, serverResult->socket->status);
else if (!SocketBind(&serverConfig, serverResult)) TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status); else if (!SocketBind(&serverConfig, serverResult)) TraceLog(LOG_WARNING, "Failed to bind server: status %d, errno %d", serverResult->status, serverResult->socket->status);
@ -65,7 +65,7 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Once connected to the network, check the sockets for pending information // Once connected to the network, check the sockets for pending information
// and when information is ready, send either a Ping or a Pong. // and when information is ready, send either a Ping or a Pong.
// CheckSockets, if any of the sockets in the set are pending (received data, or requests) // CheckSockets, if any of the sockets in the set are pending (received data, or requests)
// then mark the socket as being ready. You can check this with IsSocketReady(client_res->socket) // then mark the socket as being ready. You can check this with IsSocketReady(client_res->socket)
int active = CheckSockets(socketSet, 0); int active = CheckSockets(socketSet, 0);
@ -79,7 +79,7 @@ int main(void)
int bytesRecv = SocketReceive(serverResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1); int bytesRecv = SocketReceive(serverResult->socket, receiveBuffer, (int)strlen(pingmsg) + 1);
// If we received data, is that data a "Ping!" or a "Pong!"? // If we received data, is that data a "Ping!" or a "Pong!"?
if (bytesRecv > 0) if (bytesRecv > 0)
{ {
if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; } if (strcmp(receiveBuffer, pingmsg) == 0) { pong = true; }
if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; } if (strcmp(receiveBuffer, pongmsg) == 0) { ping = true; }
@ -87,20 +87,20 @@ int main(void)
// After each delay has expired, send a response "Ping!" for a "Pong!" and vice-versa // After each delay has expired, send a response "Ping!" for a "Pong!" and vice-versa
elapsed += GetFrameTime(); elapsed += GetFrameTime();
if (elapsed > delay) if (elapsed > delay)
{ {
if (ping) if (ping)
{ {
ping = false; ping = false;
SocketSend(serverResult->socket, pingmsg, (int)strlen(pingmsg) + 1); SocketSend(serverResult->socket, pingmsg, (int)strlen(pingmsg) + 1);
} }
else if (pong) else if (pong)
{ {
pong = false; pong = false;
SocketSend(serverResult->socket, pongmsg, (int)strlen(pongmsg) + 1); SocketSend(serverResult->socket, pongmsg, (int)strlen(pongmsg) + 1);
} }
elapsed = 0.0f; elapsed = 0.0f;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -120,7 +120,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseNetworkDevice(); // Close network communication CloseNetworkDevice(); // Close network communication
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -107,7 +107,7 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [easings] example - easings testbed"); InitWindow(screenWidth, screenHeight, "raylib [easings] example - easings testbed");
Vector2 ballPosition = { 100.0f, 200.0f }; Vector2 ballPosition = { 100.0f, 200.0f };
float t = 0.0f; // Current time (in any unit measure, but same unit as duration) float t = 0.0f; // Current time (in any unit measure, but same unit as duration)
float d = 300.0f; // Total time it should take to complete (duration) float d = 300.0f; // Total time it should take to complete (duration)
bool paused = true; bool paused = true;

View File

@ -28,7 +28,7 @@ int main(void)
InitAudioDevice(); // Initialize audio device InitAudioDevice(); // Initialize audio device
// Loaded in CPU memory (RAM) from header file (audio_data.h) // Loaded in CPU memory (RAM) from header file (audio_data.h)
// Same as: Wave wave = LoadWave("sound.wav"); // Same as: Wave wave = LoadWave("sound.wav");
Wave wave = { Wave wave = {
.data = AUDIO_DATA, .data = AUDIO_DATA,
.sampleCount = AUDIO_SAMPLE_COUNT, .sampleCount = AUDIO_SAMPLE_COUNT,
@ -39,14 +39,14 @@ int main(void)
// Wave converted to Sound to be played // Wave converted to Sound to be played
Sound sound = LoadSoundFromWave(wave); Sound sound = LoadSoundFromWave(wave);
// With a Wave loaded from file, after Sound is loaded, we can unload Wave // With a Wave loaded from file, after Sound is loaded, we can unload Wave
// but in our case, Wave is embedded in executable, in program .data segment // but in our case, Wave is embedded in executable, in program .data segment
// we can not (and should not) try to free that private memory region // we can not (and should not) try to free that private memory region
//UnloadWave(wave); // Do not unload wave data! //UnloadWave(wave); // Do not unload wave data!
// Loaded in CPU memory (RAM) from header file (image_data.h) // Loaded in CPU memory (RAM) from header file (image_data.h)
// Same as: Image image = LoadImage("raylib_logo.png"); // Same as: Image image = LoadImage("raylib_logo.png");
Image image = { Image image = {
.data = IMAGE_DATA, .data = IMAGE_DATA,
.width = IMAGE_WIDTH, .width = IMAGE_WIDTH,
@ -54,15 +54,15 @@ int main(void)
.format = IMAGE_FORMAT, .format = IMAGE_FORMAT,
.mipmaps = 1 .mipmaps = 1
}; };
// Image converted to Texture (VRAM) to be drawn // Image converted to Texture (VRAM) to be drawn
Texture2D texture = LoadTextureFromImage(image); Texture2D texture = LoadTextureFromImage(image);
// With an Image loaded from file, after Texture is loaded, we can unload Image // With an Image loaded from file, after Texture is loaded, we can unload Image
// but in our case, Image is embedded in executable, in program .data segment // but in our case, Image is embedded in executable, in program .data segment
// we can not (and should not) try to free that private memory region // we can not (and should not) try to free that private memory region
//UnloadImage(image); // Do not unload image data! //UnloadImage(image); // Do not unload image data!
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 263 KiB

View File

@ -15,7 +15,7 @@
* *
* COMPILATION: * COMPILATION:
* gcc -o raudio_standalone.exe raudio_standalone.c ..\..\src\raudio.c / * gcc -o raudio_standalone.exe raudio_standalone.c ..\..\src\raudio.c /
* -I..\..\src -I..\..\src\external -L. -Wall -std=c99 -DRAUDIO_STANDALONE / * -I..\..\src -I..\..\src\external -L. -Wall -std=c99 -DRAUDIO_STANDALONE /
* -DSUPPORT_FILEFORMAT_WAV -DSUPPORT_FILEFORMAT_OGG -DSUPPORT_FILEFORMAT_MP3 * -DSUPPORT_FILEFORMAT_WAV -DSUPPORT_FILEFORMAT_OGG -DSUPPORT_FILEFORMAT_MP3
* *
* LICENSE: zlib/libpng * LICENSE: zlib/libpng
@ -61,7 +61,7 @@
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Module Functions Declaration // Module Functions Declaration
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
#if !defined(_MSC_VER) #if !defined(_WIN32)
static int kbhit(void); // Check if a key has been pressed static int kbhit(void); // Check if a key has been pressed
static char getch(); // Get pressed character static char getch(); // Get pressed character
#else #else
@ -96,7 +96,7 @@ int main(int argc, char *argv[])
if ((key == 's') || (key == 'S')) PlaySound(fxWav); if ((key == 's') || (key == 'S')) PlaySound(fxWav);
if ((key == 'd') || (key == 'D')) PlaySound(fxOgg); if ((key == 'd') || (key == 'D')) PlaySound(fxOgg);
key = 0; key = 0;
UpdateMusicStream(music); UpdateMusicStream(music);

View File

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

View File

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

View File

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

View File

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

View File

@ -9,7 +9,7 @@
* rlgl.h - OpenGL 1.1 immediate-mode style coding translation layer * rlgl.h - OpenGL 1.1 immediate-mode style coding translation layer
* glad.h - OpenGL extensions initialization library (required by rlgl) * glad.h - OpenGL extensions initialization library (required by rlgl)
* raymath.h - 3D math library (required by rlgl) * raymath.h - 3D math library (required by rlgl)
* glfw3 - Windows and context initialization library * glfw3 - Windows and context initialization library
* *
* rlgl library is provided as a single-file header-only library, this library * rlgl library is provided as a single-file header-only library, this library
* allows coding in a pseudo-OpenGL 1.1 style while translating calls to multiple * allows coding in a pseudo-OpenGL 1.1 style while translating calls to multiple
@ -95,18 +95,18 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
// GLFW3 Initialization + OpenGL 3.3 Context + Extensions // GLFW3 Initialization + OpenGL 3.3 Context + Extensions
//-------------------------------------------------------- //--------------------------------------------------------
glfwSetErrorCallback(ErrorCallback); glfwSetErrorCallback(ErrorCallback);
if (!glfwInit()) if (!glfwInit())
{ {
printf("GLFW3: Can not initialize GLFW\n"); printf("GLFW3: Can not initialize GLFW\n");
return 1; return 1;
} }
else printf("GLFW3: GLFW initialized successfully\n"); else printf("GLFW3: GLFW initialized successfully\n");
glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_DEPTH_BITS, 16); glfwWindowHint(GLFW_DEPTH_BITS, 16);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
@ -117,27 +117,27 @@ int main(void)
glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE ); glfwWindowHint( GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE );
#endif #endif
GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "rlgl standalone", NULL, NULL); GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "rlgl standalone", NULL, NULL);
if (!window) if (!window)
{ {
glfwTerminate(); glfwTerminate();
return 2; return 2;
} }
else printf("GLFW3: Window created successfully\n"); else printf("GLFW3: Window created successfully\n");
glfwSetWindowPos(window, 200, 200); glfwSetWindowPos(window, 200, 200);
glfwSetKeyCallback(window, KeyCallback); glfwSetKeyCallback(window, KeyCallback);
glfwMakeContextCurrent(window); glfwMakeContextCurrent(window);
glfwSwapInterval(0); glfwSwapInterval(0);
// Load OpenGL 3.3 supported extensions // Load OpenGL 3.3 supported extensions
rlLoadExtensions(glfwGetProcAddress); rlLoadExtensions(glfwGetProcAddress);
//-------------------------------------------------------- //--------------------------------------------------------
// Initialize OpenGL context (states and resources) // Initialize OpenGL context (states and resources)
rlglInit(screenWidth, screenHeight); rlglInit(screenWidth, screenHeight);
@ -151,18 +151,18 @@ int main(void)
rlClearColor(245, 245, 245, 255); // Define clear color rlClearColor(245, 245, 245, 255); // Define clear color
rlEnableDepthTest(); // Enable DEPTH_TEST for 3D rlEnableDepthTest(); // Enable DEPTH_TEST for 3D
Camera camera = { 0 }; Camera camera = { 0 };
camera.position = (Vector3){ 5.0f, 5.0f, 5.0f }; // Camera position camera.position = (Vector3){ 5.0f, 5.0f, 5.0f }; // Camera position
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y camera.fovy = 45.0f; // Camera field-of-view Y
Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; // Cube default position (center)
//--------------------------------------------------------------------------------------
// Main game loop Vector3 cubePosition = { 0.0f, 0.0f, 0.0f }; // Cube default position (center)
while (!glfwWindowShouldClose(window)) //--------------------------------------------------------------------------------------
// Main game loop
while (!glfwWindowShouldClose(window))
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -176,7 +176,7 @@ int main(void)
// Draw '3D' elements in the scene // Draw '3D' elements in the scene
//----------------------------------------------- //-----------------------------------------------
// Calculate projection matrix (from perspective) and view matrix from camera look at // Calculate projection matrix (from perspective) and view matrix from camera look at
Matrix matProj = MatrixPerspective(camera.fovy*DEG2RAD, (double)screenWidth/(double)screenHeight, 0.01, 1000.0); Matrix matProj = MatrixPerspective((double)(camera.fovy*DEG2RAD), (double)screenWidth/(double)screenHeight, 0.01, 1000.0);
Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up); Matrix matView = MatrixLookAt(camera.position, camera.target, camera.up);
rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader) rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader)
@ -189,14 +189,14 @@ int main(void)
// Draw internal render batch buffers (3D data) // Draw internal render batch buffers (3D data)
rlDrawRenderBatchActive(); rlDrawRenderBatchActive();
//----------------------------------------------- //-----------------------------------------------
// Draw '2D' elements in the scene (GUI) // Draw '2D' elements in the scene (GUI)
//----------------------------------------------- //-----------------------------------------------
#define RLGL_CREATE_MATRIX_MANUALLY #define RLGL_CREATE_MATRIX_MANUALLY
#if defined(RLGL_CREATE_MATRIX_MANUALLY) #if defined(RLGL_CREATE_MATRIX_MANUALLY)
matProj = MatrixOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0); matProj = MatrixOrtho(0.0, screenWidth, screenHeight, 0.0, 0.0, 1.0);
matView = MatrixIdentity(); matView = MatrixIdentity();
rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader) rlSetMatrixModelview(matView); // Set internal modelview matrix (default shader)
rlSetMatrixProjection(matProj); // Set internal projection matrix (default shader) rlSetMatrixProjection(matProj); // Set internal projection matrix (default shader)
@ -213,7 +213,7 @@ int main(void)
// Draw internal render batch buffers (3D data) // Draw internal render batch buffers (3D data)
rlDrawRenderBatchActive(); rlDrawRenderBatchActive();
//----------------------------------------------- //-----------------------------------------------
glfwSwapBuffers(window); glfwSwapBuffers(window);
glfwPollEvents(); glfwPollEvents();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -222,11 +222,11 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
rlglClose(); // Unload rlgl internal buffers and default shader/texture rlglClose(); // Unload rlgl internal buffers and default shader/texture
glfwDestroyWindow(window); // Close window glfwDestroyWindow(window); // Close window
glfwTerminate(); // Free GLFW3 resources glfwTerminate(); // Free GLFW3 resources
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View File

@ -54,7 +54,7 @@ int main(void)
if (IsKeyPressed(KEY_R)) // Reset physics system if (IsKeyPressed(KEY_R)) // Reset physics system
{ {
ResetPhysics(); ResetPhysics();
floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10); floor = CreatePhysicsBodyRectangle((Vector2){ screenWidth/2, screenHeight }, 500, 100, 10);
floor->enabled = false; floor->enabled = false;
@ -63,8 +63,8 @@ int main(void)
} }
// Physics body creation inputs // Physics body creation inputs
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) CreatePhysicsBodyPolygon(GetMousePosition(), GetRandomValue(20, 80), GetRandomValue(3, 8), 10); if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) CreatePhysicsBodyPolygon(GetMousePosition(), GetRandomValue(20, 80), GetRandomValue(3, 8), 10);
else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) CreatePhysicsBodyCircle(GetMousePosition(), GetRandomValue(10, 45), 10); else if (IsMouseButtonPressed(MOUSE_BUTTON_RIGHT)) CreatePhysicsBodyCircle(GetMousePosition(), GetRandomValue(10, 45), 10);
// Destroy falling physics bodies // Destroy falling physics bodies
int bodiesCount = GetPhysicsBodiesCount(); int bodiesCount = GetPhysicsBodiesCount();

View File

@ -48,7 +48,7 @@ int main(void)
// Restitution demo needs a very tiny physics time step for a proper simulation // Restitution demo needs a very tiny physics time step for a proper simulation
SetPhysicsTimeStep(1.0/60.0/100*1000); SetPhysicsTimeStep(1.0/60.0/100*1000);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -119,7 +119,7 @@ int main(void)
DestroyPhysicsBody(circleB); DestroyPhysicsBody(circleB);
DestroyPhysicsBody(circleC); DestroyPhysicsBody(circleC);
DestroyPhysicsBody(floor); DestroyPhysicsBody(floor);
ClosePhysics(); // Unitialize physics ClosePhysics(); // Unitialize physics
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View File

@ -35,7 +35,7 @@ int main(void)
SetPhysicsGravity(0, 0); SetPhysicsGravity(0, 0);
// Create random polygon physics body to shatter // Create random polygon physics body to shatter
CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); CreatePhysicsBodyPolygon((Vector2){ screenWidth/2.0f, screenHeight/2.0f }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10);
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -45,21 +45,21 @@ int main(void)
{ {
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdatePhysics(); // Update physics system UpdatePhysics(); // Update physics system
if (IsKeyPressed(KEY_R)) // Reset physics input if (IsKeyPressed(KEY_R)) // Reset physics input
{ {
ResetPhysics(); ResetPhysics();
CreatePhysicsBodyPolygon((Vector2){ screenWidth/2, screenHeight/2 }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10); CreatePhysicsBodyPolygon((Vector2){ screenWidth/2.0f, screenHeight/2.0f }, GetRandomValue(80, 200), GetRandomValue(3, 8), 10);
} }
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) // Physics shatter input if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) // Physics shatter input
{ {
int count = GetPhysicsBodiesCount(); int count = GetPhysicsBodiesCount();
for (int i = count - 1; i >= 0; i--) for (int i = count - 1; i >= 0; i--)
{ {
PhysicsBody currentBody = GetPhysicsBody(i); PhysicsBody currentBody = GetPhysicsBody(i);
if (currentBody != NULL) PhysicsShatter(currentBody, GetMousePosition(), 10/currentBody->inverseMass); if (currentBody != NULL) PhysicsShatter(currentBody, GetMousePosition(), 10/currentBody->inverseMass);
} }
} }

View File

@ -69,9 +69,9 @@ int main(void)
modelB.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; modelB.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture;
modelC.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; modelC.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture;
Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting.vs", GLSL_VERSION), Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/lighting.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/lighting.fs", GLSL_VERSION));
// Get some shader loactions // Get some shader loactions
shader.locs[SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel"); shader.locs[SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel");
shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos"); shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
@ -79,7 +79,7 @@ int main(void)
// ambient light level // ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient"); int ambientLoc = GetShaderLocation(shader, "ambient");
SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, SHADER_UNIFORM_VEC4); SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, SHADER_UNIFORM_VEC4);
float angle = 6.282f; float angle = 6.282f;
// All models use the same shader // All models use the same shader
@ -121,7 +121,7 @@ int main(void)
lights[2].position.z = sinf(angle*0.2f)*4.0f; lights[2].position.z = sinf(angle*0.2f)*4.0f;
lights[3].position.y = cosf(-angle*0.35f)*4.0f; lights[3].position.y = cosf(-angle*0.35f)*4.0f;
lights[3].position.z = sinf(-angle*0.35f)*4.0f; lights[3].position.z = sinf(-angle*0.35f)*4.0f;
UpdateLightValues(shader, lights[0]); UpdateLightValues(shader, lights[0]);
UpdateLightValues(shader, lights[1]); UpdateLightValues(shader, lights[1]);
UpdateLightValues(shader, lights[2]); UpdateLightValues(shader, lights[2]);
@ -146,8 +146,8 @@ int main(void)
// Draw the three models // Draw the three models
DrawModel(modelA, Vector3Zero(), 1.0f, WHITE); DrawModel(modelA, Vector3Zero(), 1.0f, WHITE);
DrawModel(modelB, (Vector3){-1.6,0,0}, 1.0f, WHITE); DrawModel(modelB, (Vector3){-1.6f,0.0f,0.0f}, 1.0f, WHITE);
DrawModel(modelC, (Vector3){ 1.6,0,0}, 1.0f, WHITE); DrawModel(modelC, (Vector3){ 1.6f,0.0f,0.0f}, 1.0f, WHITE);
// Draw markers to show where the lights are // Draw markers to show where the lights are
if (lights[0].enabled) { DrawSphereEx(lights[0].position, 0.2f, 8, 8, WHITE); } if (lights[0].enabled) { DrawSphereEx(lights[0].position, 0.2f, 8, 8, WHITE); }
@ -160,7 +160,7 @@ int main(void)
EndMode3D(); EndMode3D();
DrawFPS(10, 10); DrawFPS(10, 10);
DrawText("Use keys RGBW to toggle lights", 10, 30, 20, DARKGRAY); DrawText("Use keys RGBW to toggle lights", 10, 30, 20, DARKGRAY);
EndDrawing(); EndDrawing();
@ -172,7 +172,7 @@ int main(void)
UnloadModel(modelA); // Unload the modelA UnloadModel(modelA); // Unload the modelA
UnloadModel(modelB); // Unload the modelB UnloadModel(modelB); // Unload the modelB
UnloadModel(modelC); // Unload the modelC UnloadModel(modelC); // Unload the modelC
UnloadTexture(texture); // Unload the texture UnloadTexture(texture); // Unload the texture
UnloadShader(shader); // Unload shader UnloadShader(shader); // Unload shader

View File

@ -109,7 +109,7 @@ int main(void)
BeginShaderMode(shader); BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0, 0 }, WHITE); DrawTextureRec(target.texture, (Rectangle){ 0, 0, (float)target.texture.width, (float)-target.texture.height }, (Vector2){ 0, 0 }, WHITE);
EndShaderMode(); EndShaderMode();

View File

@ -41,7 +41,7 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - Sieve of Eratosthenes");
RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight); RenderTexture2D target = LoadRenderTexture(screenWidth, screenHeight);
// Load Eratosthenes shader // Load Eratosthenes shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION)); Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/eratosthenes.fs", GLSL_VERSION));
@ -75,7 +75,7 @@ int main(void)
BeginShaderMode(shader); BeginShaderMode(shader);
// NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) // NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom)
DrawTextureRec(target.texture, (Rectangle){ 0, 0, target.texture.width, -target.texture.height }, (Vector2){ 0.0f, 0.0f }, WHITE); DrawTextureRec(target.texture, (Rectangle){ 0, 0, (float)target.texture.width, (float)-target.texture.height }, (Vector2){ 0.0f, 0.0f }, WHITE);
EndShaderMode(); EndShaderMode();
EndDrawing(); EndDrawing();

View File

@ -49,7 +49,7 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - fog");
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera camera = { Camera camera = {
(Vector3){ 2.0f, 2.0f, 6.0f }, // position (Vector3){ 2.0f, 2.0f, 6.0f }, // position
(Vector3){ 0.0f, 0.5f, 0.0f }, // target (Vector3){ 0.0f, 0.5f, 0.0f }, // target
(Vector3){ 0.0f, 1.0f, 0.0f }, // up (Vector3){ 0.0f, 1.0f, 0.0f }, // up
@ -67,7 +67,7 @@ int main(void)
modelC.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture; modelC.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texture;
// Load shader and set up some uniforms // Load shader and set up some uniforms
Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting.vs", GLSL_VERSION), Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/fog.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/fog.fs", GLSL_VERSION));
shader.locs[SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel"); shader.locs[SHADER_LOC_MATRIX_MODEL] = GetShaderLocation(shader, "matModel");
shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos"); shader.locs[SHADER_LOC_VECTOR_VIEW] = GetShaderLocation(shader, "viewPos");
@ -75,7 +75,7 @@ int main(void)
// Ambient light level // Ambient light level
int ambientLoc = GetShaderLocation(shader, "ambient"); int ambientLoc = GetShaderLocation(shader, "ambient");
SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, SHADER_UNIFORM_VEC4); SetShaderValue(shader, ambientLoc, (float[4]){ 0.2f, 0.2f, 0.2f, 1.0f }, SHADER_UNIFORM_VEC4);
float fogDensity = 0.15f; float fogDensity = 0.15f;
int fogDensityLoc = GetShaderLocation(shader, "fogDensity"); int fogDensityLoc = GetShaderLocation(shader, "fogDensity");
SetShaderValue(shader, fogDensityLoc, &fogDensity, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, fogDensityLoc, &fogDensity, SHADER_UNIFORM_FLOAT);
@ -100,23 +100,23 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
if (IsKeyDown(KEY_UP)) if (IsKeyDown(KEY_UP))
{ {
fogDensity += 0.001; fogDensity += 0.001f;
if (fogDensity > 1.0) fogDensity = 1.0; if (fogDensity > 1.0f) fogDensity = 1.0f;
} }
if (IsKeyDown(KEY_DOWN)) if (IsKeyDown(KEY_DOWN))
{ {
fogDensity -= 0.001; fogDensity -= 0.001f;
if (fogDensity < 0.0) fogDensity = 0.0; if (fogDensity < 0.0f) fogDensity = 0.0f;
} }
SetShaderValue(shader, fogDensityLoc, &fogDensity, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, fogDensityLoc, &fogDensity, SHADER_UNIFORM_FLOAT);
// Rotate the torus // Rotate the torus
modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateX(-0.025)); modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateX(-0.025f));
modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateZ(0.012)); modelA.transform = MatrixMultiply(modelA.transform, MatrixRotateZ(0.012f));
// Update the light shader with the camera view position // Update the light shader with the camera view position
SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], &camera.position.x, SHADER_UNIFORM_VEC3); SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], &camera.position.x, SHADER_UNIFORM_VEC3);
@ -132,10 +132,10 @@ int main(void)
// Draw the three models // Draw the three models
DrawModel(modelA, Vector3Zero(), 1.0f, WHITE); DrawModel(modelA, Vector3Zero(), 1.0f, WHITE);
DrawModel(modelB, (Vector3){ -2.6, 0, 0 }, 1.0f, WHITE); DrawModel(modelB, (Vector3){ -2.6f, 0, 0 }, 1.0f, WHITE);
DrawModel(modelC, (Vector3){ 2.6, 0, 0 }, 1.0f, WHITE); DrawModel(modelC, (Vector3){ 2.6f, 0, 0 }, 1.0f, WHITE);
for (int i = -20; i < 20; i += 2) DrawModel(modelA,(Vector3){ i, 0, 2 }, 1.0f, WHITE); for (int i = -20; i < 20; i += 2) DrawModel(modelA,(Vector3){ (float)i, 0, 2 }, 1.0f, WHITE);
EndMode3D(); EndMode3D();

View File

@ -65,36 +65,36 @@ int main(void)
// Set shader required uniform values // Set shader required uniform values
SetShaderValue(shader, timeLoc, &totalTime, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, timeLoc, &totalTime, SHADER_UNIFORM_FLOAT);
SetShaderValue(shader, mouseLoc, mousePos, SHADER_UNIFORM_VEC2); SetShaderValue(shader, mouseLoc, mousePos, SHADER_UNIFORM_VEC2);
// Hot shader reloading // Hot shader reloading
if (shaderAutoReloading || (IsMouseButtonPressed(MOUSE_LEFT_BUTTON))) if (shaderAutoReloading || (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)))
{ {
long currentFragShaderModTime = GetFileModTime(TextFormat(fragShaderFileName, GLSL_VERSION)); long currentFragShaderModTime = GetFileModTime(TextFormat(fragShaderFileName, GLSL_VERSION));
// Check if shader file has been modified // Check if shader file has been modified
if (currentFragShaderModTime != fragShaderFileModTime) if (currentFragShaderModTime != fragShaderFileModTime)
{ {
// Try reloading updated shader // Try reloading updated shader
Shader updatedShader = LoadShader(0, TextFormat(fragShaderFileName, GLSL_VERSION)); Shader updatedShader = LoadShader(0, TextFormat(fragShaderFileName, GLSL_VERSION));
if (updatedShader.id != rlGetShaderDefault().id) // It was correctly loaded if (updatedShader.id != rlGetShaderDefault().id) // It was correctly loaded
{ {
UnloadShader(shader); UnloadShader(shader);
shader = updatedShader; shader = updatedShader;
// Get shader locations for required uniforms // Get shader locations for required uniforms
resolutionLoc = GetShaderLocation(shader, "resolution"); resolutionLoc = GetShaderLocation(shader, "resolution");
mouseLoc = GetShaderLocation(shader, "mouse"); mouseLoc = GetShaderLocation(shader, "mouse");
timeLoc = GetShaderLocation(shader, "time"); timeLoc = GetShaderLocation(shader, "time");
// Reset required uniforms // Reset required uniforms
SetShaderValue(shader, resolutionLoc, resolution, SHADER_UNIFORM_VEC2); SetShaderValue(shader, resolutionLoc, resolution, SHADER_UNIFORM_VEC2);
} }
fragShaderFileModTime = currentFragShaderModTime; fragShaderFileModTime = currentFragShaderModTime;
} }
} }
if (IsKeyPressed(KEY_A)) shaderAutoReloading = !shaderAutoReloading; if (IsKeyPressed(KEY_A)) shaderAutoReloading = !shaderAutoReloading;
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -109,10 +109,10 @@ int main(void)
DrawRectangle(0, 0, screenWidth, screenHeight, WHITE); DrawRectangle(0, 0, screenWidth, screenHeight, WHITE);
EndShaderMode(); EndShaderMode();
DrawText(TextFormat("PRESS [A] to TOGGLE SHADER AUTOLOADING: %s", DrawText(TextFormat("PRESS [A] to TOGGLE SHADER AUTOLOADING: %s",
shaderAutoReloading? "AUTO" : "MANUAL"), 10, 10, 10, shaderAutoReloading? RED : BLACK); shaderAutoReloading? "AUTO" : "MANUAL"), 10, 10, 10, shaderAutoReloading? RED : BLACK);
if (!shaderAutoReloading) DrawText("MOUSE CLICK to SHADER RE-LOADING", 10, 30, 10, BLACK); if (!shaderAutoReloading) DrawText("MOUSE CLICK to SHADER RE-LOADING", 10, 30, 10, BLACK);
DrawText(TextFormat("Shader last modification: %s", asctime(localtime(&fragShaderFileModTime))), 10, 430, 10, BLACK); DrawText(TextFormat("Shader last modification: %s", asctime(localtime(&fragShaderFileModTime))), 10, 430, 10, BLACK);
EndDrawing(); EndDrawing();

View File

@ -27,12 +27,12 @@
// A few good julia sets // A few good julia sets
const float pointsOfInterest[6][2] = const float pointsOfInterest[6][2] =
{ {
{ -0.348827, 0.607167 }, { -0.348827f, 0.607167f },
{ -0.786268, 0.169728 }, { -0.786268f, 0.169728f },
{ -0.8, 0.156 }, { -0.8f, 0.156f },
{ 0.285, 0.0 }, { 0.285f, 0.0f },
{ -0.835, -0.2321 }, { -0.835f, -0.2321f },
{ -0.70176, -0.3842 }, { -0.70176f, -0.3842f },
}; };
int main(void) int main(void)
@ -48,7 +48,7 @@ int main(void)
// Load julia set shader // Load julia set shader
// NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader // NOTE: Defining 0 (NULL) for vertex shader forces usage of internal default vertex shader
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/julia_set.fs", GLSL_VERSION)); Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/julia_set.fs", GLSL_VERSION));
// Create a RenderTexture2D to be used for render to texture // Create a RenderTexture2D to be used for render to texture
RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight()); RenderTexture2D target = LoadRenderTexture(GetScreenWidth(), GetScreenHeight());
@ -74,7 +74,7 @@ int main(void)
SetShaderValue(shader, cLoc, c, SHADER_UNIFORM_VEC2); SetShaderValue(shader, cLoc, c, SHADER_UNIFORM_VEC2);
SetShaderValue(shader, zoomLoc, &zoom, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, zoomLoc, &zoom, SHADER_UNIFORM_FLOAT);
SetShaderValue(shader, offsetLoc, offset, SHADER_UNIFORM_VEC2); SetShaderValue(shader, offsetLoc, offset, SHADER_UNIFORM_VEC2);
int incrementSpeed = 0; // Multiplier of speed to change c value int incrementSpeed = 0; // Multiplier of speed to change c value
bool showControls = true; // Show controls bool showControls = true; // Show controls
bool pause = false; // Pause animation bool pause = false; // Pause animation
@ -115,10 +115,10 @@ int main(void)
// TODO: The idea is to zoom and move around with mouse // TODO: The idea is to zoom and move around with mouse
// Probably offset movement should be proportional to zoom level // Probably offset movement should be proportional to zoom level
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) || IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) || IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{ {
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) zoom += zoom*0.003f; if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) zoom += zoom*0.003f;
if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) zoom -= zoom*0.003f; if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) zoom -= zoom*0.003f;
Vector2 mousePos = GetMousePosition(); Vector2 mousePos = GetMousePosition();

View File

@ -27,6 +27,8 @@
#define GLSL_VERSION 100 #define GLSL_VERSION 100
#endif #endif
#define MAX_INSTANCES 10000
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
// Program main entry point // Program main entry point
//------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------
@ -56,20 +58,19 @@ int main(void)
camera.fovy = 45.0f; camera.fovy = 45.0f;
camera.projection = CAMERA_PERSPECTIVE; camera.projection = CAMERA_PERSPECTIVE;
const int instances = 10000; // Number of instances to display
Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f); Mesh cube = GenMeshCube(1.0f, 1.0f, 1.0f);
Matrix *rotations = RL_MALLOC(instances*sizeof(Matrix)); // Rotation state of instances Matrix *rotations = RL_MALLOC(MAX_INSTANCES*sizeof(Matrix)); // Rotation state of instances
Matrix *rotationsInc = RL_MALLOC(instances*sizeof(Matrix)); // Per-frame rotation animation of instances Matrix *rotationsInc = RL_MALLOC(MAX_INSTANCES*sizeof(Matrix)); // Per-frame rotation animation of instances
Matrix *translations = RL_MALLOC(instances*sizeof(Matrix)); // Locations of instances Matrix *translations = RL_MALLOC(MAX_INSTANCES*sizeof(Matrix)); // Locations of instances
// Scatter random cubes around // Scatter random cubes around
for (int i = 0; i < instances; i++) for (int i = 0; i < MAX_INSTANCES; i++)
{ {
x = GetRandomValue(-50, 50); x = GetRandomValue(-50, 50);
y = GetRandomValue(-50, 50); y = GetRandomValue(-50, 50);
z = GetRandomValue(-50, 50); z = GetRandomValue(-50, 50);
translations[i] = MatrixTranslate(x, y, z); translations[i] = MatrixTranslate(x, y, z);
x = GetRandomValue(0, 360); x = GetRandomValue(0, 360);
y = GetRandomValue(0, 360); y = GetRandomValue(0, 360);
@ -81,9 +82,9 @@ int main(void)
rotations[i] = MatrixIdentity(); rotations[i] = MatrixIdentity();
} }
Matrix *transforms = RL_MALLOC(instances*sizeof(Matrix)); // Pre-multiplied transformations passed to rlgl Matrix *transforms = RL_MALLOC(MAX_INSTANCES*sizeof(Matrix)); // Pre-multiplied transformations passed to rlgl
Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting_instanced.vs", GLSL_VERSION), Shader shader = LoadShader(TextFormat("resources/shaders/glsl%i/base_lighting_instanced.vs", GLSL_VERSION),
TextFormat("resources/shaders/glsl%i/lighting.fs", GLSL_VERSION)); TextFormat("resources/shaders/glsl%i/lighting.fs", GLSL_VERSION));
// Get some shader loactions // Get some shader loactions
@ -102,7 +103,7 @@ int main(void)
Material material = LoadMaterialDefault(); Material material = LoadMaterialDefault();
material.shader = shader; material.shader = shader;
material.maps[MATERIAL_MAP_DIFFUSE].color = RED; material.maps[MATERIAL_MAP_DIFFUSE].color = RED;
SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode SetCameraMode(camera, CAMERA_ORBITAL); // Set an orbital camera mode
int textPositionY = 300; int textPositionY = 300;
@ -134,10 +135,10 @@ int main(void)
if (IsKeyDown(KEY_EIGHT)) groups = 8; if (IsKeyDown(KEY_EIGHT)) groups = 8;
if (IsKeyDown(KEY_NINE)) groups = 9; if (IsKeyDown(KEY_NINE)) groups = 9;
if (IsKeyDown(KEY_W)) { groups = 7; amp = 25; speed = 18; variance = 0.70f; } if (IsKeyDown(KEY_W)) { groups = 7; amp = 25; speed = 18; variance = 0.70f; }
if (IsKeyDown(KEY_EQUAL)) speed = (speed <= (fps*0.25f))? (fps*0.25f) : (speed*0.95f); if (IsKeyDown(KEY_EQUAL)) speed = (speed <= (fps*0.25f))? (fps*0.25f) : (speed*0.95f);
if (IsKeyDown(KEY_KP_ADD)) speed = (speed <= (fps*0.25f))? (fps*0.25f) : (speed*0.95f); if (IsKeyDown(KEY_KP_ADD)) speed = (speed <= (fps*0.25f))? (fps*0.25f) : (speed*0.95f);
if (IsKeyDown(KEY_MINUS)) speed = fmaxf(speed*1.02f, speed + 1); if (IsKeyDown(KEY_MINUS)) speed = fmaxf(speed*1.02f, speed + 1);
if (IsKeyDown(KEY_KP_SUBTRACT)) speed = fmaxf(speed*1.02f, speed + 1); if (IsKeyDown(KEY_KP_SUBTRACT)) speed = fmaxf(speed*1.02f, speed + 1);
@ -146,23 +147,23 @@ int main(void)
SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], cameraPos, SHADER_UNIFORM_VEC3); SetShaderValue(shader, shader.locs[SHADER_LOC_VECTOR_VIEW], cameraPos, SHADER_UNIFORM_VEC3);
// Apply per-instance transformations // Apply per-instance transformations
for (int i = 0; i < instances; i++) for (int i = 0; i < MAX_INSTANCES; i++)
{ {
rotations[i] = MatrixMultiply(rotations[i], rotationsInc[i]); rotations[i] = MatrixMultiply(rotations[i], rotationsInc[i]);
transforms[i] = MatrixMultiply(rotations[i], translations[i]); transforms[i] = MatrixMultiply(rotations[i], translations[i]);
// Get the animation cycle's framesCounter for this instance // Get the animation cycle's framesCounter for this instance
loop = (float)((framesCounter + (int)(((float)(i%groups)/groups)*speed))%speed)/speed; loop = (float)((framesCounter + (int)(((float)(i%groups)/groups)*speed))%speed)/speed;
// Calculate the y according to loop cycle // Calculate the y according to loop cycle
y = (sinf(loop*PI*2))*amp*((1 - variance) + (variance*(float)(i%(groups*10))/(groups*10))); y = (sinf(loop*PI*2))*amp*((1 - variance) + (variance*(float)(i%(groups*10))/(groups*10)));
// Clamp to floor // Clamp to floor
y = (y < 0)? 0.0f : y; y = (y < 0)? 0.0f : y;
transforms[i] = MatrixMultiply(transforms[i], MatrixTranslate(0.0f, y, 0.0f)); transforms[i] = MatrixMultiply(transforms[i], MatrixTranslate(0.0f, y, 0.0f));
} }
UpdateCamera(&camera); UpdateCamera(&camera);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -174,40 +175,40 @@ int main(void)
BeginMode3D(camera); BeginMode3D(camera);
//DrawMesh(cube, material, MatrixIdentity()); //DrawMesh(cube, material, MatrixIdentity());
DrawMeshInstanced(cube, material, transforms, instances); DrawMeshInstanced(cube, material, transforms, MAX_INSTANCES);
EndMode3D(); EndMode3D();
DrawText("A CUBE OF DANCING CUBES!", 490, 10, 20, MAROON); DrawText("A CUBE OF DANCING CUBES!", 490, 10, 20, MAROON);
DrawText("PRESS KEYS:", 10, textPositionY, 20, BLACK); DrawText("PRESS KEYS:", 10, textPositionY, 20, BLACK);
DrawText("1 - 9", 10, textPositionY += 25, 10, BLACK); DrawText("1 - 9", 10, textPositionY += 25, 10, BLACK);
DrawText(": Number of groups", 50, textPositionY , 10, BLACK); DrawText(": Number of groups", 50, textPositionY , 10, BLACK);
DrawText(TextFormat(": %d", groups), 160, textPositionY , 10, BLACK); DrawText(TextFormat(": %d", groups), 160, textPositionY , 10, BLACK);
DrawText("UP", 10, textPositionY += 15, 10, BLACK); DrawText("UP", 10, textPositionY += 15, 10, BLACK);
DrawText(": increase amplitude", 50, textPositionY, 10, BLACK); DrawText(": increase amplitude", 50, textPositionY, 10, BLACK);
DrawText(TextFormat(": %.2f", amp), 160, textPositionY , 10, BLACK); DrawText(TextFormat(": %.2f", amp), 160, textPositionY , 10, BLACK);
DrawText("DOWN", 10, textPositionY += 15, 10, BLACK); DrawText("DOWN", 10, textPositionY += 15, 10, BLACK);
DrawText(": decrease amplitude", 50, textPositionY, 10, BLACK); DrawText(": decrease amplitude", 50, textPositionY, 10, BLACK);
DrawText("LEFT", 10, textPositionY += 15, 10, BLACK); DrawText("LEFT", 10, textPositionY += 15, 10, BLACK);
DrawText(": decrease variance", 50, textPositionY, 10, BLACK); DrawText(": decrease variance", 50, textPositionY, 10, BLACK);
DrawText(TextFormat(": %.2f", variance), 160, textPositionY , 10, BLACK); DrawText(TextFormat(": %.2f", variance), 160, textPositionY , 10, BLACK);
DrawText("RIGHT", 10, textPositionY += 15, 10, BLACK); DrawText("RIGHT", 10, textPositionY += 15, 10, BLACK);
DrawText(": increase variance", 50, textPositionY, 10, BLACK); DrawText(": increase variance", 50, textPositionY, 10, BLACK);
DrawText("+/=", 10, textPositionY += 15, 10, BLACK); DrawText("+/=", 10, textPositionY += 15, 10, BLACK);
DrawText(": increase speed", 50, textPositionY, 10, BLACK); DrawText(": increase speed", 50, textPositionY, 10, BLACK);
DrawText(TextFormat(": %d = %f loops/sec", speed, ((float)fps / speed)), 160, textPositionY , 10, BLACK); DrawText(TextFormat(": %d = %f loops/sec", speed, ((float)fps / speed)), 160, textPositionY , 10, BLACK);
DrawText("-", 10, textPositionY += 15, 10, BLACK); DrawText("-", 10, textPositionY += 15, 10, BLACK);
DrawText(": decrease speed", 50, textPositionY, 10, BLACK); DrawText(": decrease speed", 50, textPositionY, 10, BLACK);
DrawText("W", 10, textPositionY += 15, 10, BLACK); DrawText("W", 10, textPositionY += 15, 10, BLACK);
DrawText(": Wild setup!", 50, textPositionY, 10, BLACK); DrawText(": Wild setup!", 50, textPositionY, 10, BLACK);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();

View File

@ -42,10 +42,10 @@ int main(void)
UnloadImage(imBlue); UnloadImage(imBlue);
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/color_mix.fs", GLSL_VERSION)); Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/color_mix.fs", GLSL_VERSION));
// Get an additional sampler2D location to be enabled on drawing // Get an additional sampler2D location to be enabled on drawing
int texBlueLoc = GetShaderLocation(shader, "texture1"); int texBlueLoc = GetShaderLocation(shader, "texture1");
// Get shader uniform for divider // Get shader uniform for divider
int dividerLoc = GetShaderLocation(shader, "divider"); int dividerLoc = GetShaderLocation(shader, "divider");
float dividerValue = 0.5f; float dividerValue = 0.5f;
@ -60,34 +60,34 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsKeyDown(KEY_RIGHT)) dividerValue += 0.01f; if (IsKeyDown(KEY_RIGHT)) dividerValue += 0.01f;
else if (IsKeyDown(KEY_LEFT)) dividerValue -= 0.01f; else if (IsKeyDown(KEY_LEFT)) dividerValue -= 0.01f;
if (dividerValue < 0.0f) dividerValue = 0.0f; if (dividerValue < 0.0f) dividerValue = 0.0f;
else if (dividerValue > 1.0f) dividerValue = 1.0f; else if (dividerValue > 1.0f) dividerValue = 1.0f;
SetShaderValue(shader, dividerLoc, &dividerValue, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, dividerLoc, &dividerValue, SHADER_UNIFORM_FLOAT);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginShaderMode(shader); BeginShaderMode(shader);
// WARNING: Additional samplers are enabled for all draw calls in the batch, // WARNING: Additional samplers are enabled for all draw calls in the batch,
// EndShaderMode() forces batch drawing and consequently resets active textures // EndShaderMode() forces batch drawing and consequently resets active textures
// to let other sampler2D to be activated on consequent drawings (if required) // to let other sampler2D to be activated on consequent drawings (if required)
SetShaderValueTexture(shader, texBlueLoc, texBlue); SetShaderValueTexture(shader, texBlueLoc, texBlue);
// We are drawing texRed using default sampler2D texture0 but // We are drawing texRed using default sampler2D texture0 but
// an additional texture units is enabled for texBlue (sampler2D texture1) // an additional texture units is enabled for texBlue (sampler2D texture1)
DrawTexture(texRed, 0, 0, WHITE); DrawTexture(texRed, 0, 0, WHITE);
EndShaderMode(); EndShaderMode();
DrawText("Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", 80, GetScreenHeight() - 40, 20, RAYWHITE); DrawText("Use KEY_LEFT/KEY_RIGHT to move texture mixing in shader!", 80, GetScreenHeight() - 40, 20, RAYWHITE);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }

View File

@ -73,7 +73,7 @@ int main(void)
SetShaderValue(shader, viewEyeLoc, cameraPos, SHADER_UNIFORM_VEC3); SetShaderValue(shader, viewEyeLoc, cameraPos, SHADER_UNIFORM_VEC3);
SetShaderValue(shader, viewCenterLoc, cameraTarget, SHADER_UNIFORM_VEC3); SetShaderValue(shader, viewCenterLoc, cameraTarget, SHADER_UNIFORM_VEC3);
SetShaderValue(shader, runTimeLoc, &runTime, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, runTimeLoc, &runTime, SHADER_UNIFORM_FLOAT);
// Check if screen is resized // Check if screen is resized
if (IsWindowResized()) if (IsWindowResized())
{ {

View File

@ -57,7 +57,7 @@ int main(void)
// Load the shader // Load the shader
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/mask.fs", GLSL_VERSION)); Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/mask.fs", GLSL_VERSION));
// Load and apply the diffuse texture (colour map) // Load and apply the diffuse texture (colour map)
Texture texDiffuse = LoadTexture("resources/plasma.png"); Texture texDiffuse = LoadTexture("resources/plasma.png");
model1.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texDiffuse; model1.materials[0].maps[MATERIAL_MAP_DIFFUSE].texture = texDiffuse;
@ -131,10 +131,10 @@ int main(void)
UnloadModel(model1); UnloadModel(model1);
UnloadModel(model2); UnloadModel(model2);
UnloadModel(model3); UnloadModel(model3);
UnloadTexture(texDiffuse); // Unload default diffuse texture UnloadTexture(texDiffuse); // Unload default diffuse texture
UnloadTexture(texMask); // Unload texture mask UnloadTexture(texMask); // Unload texture mask
UnloadShader(shader); // Unload shader UnloadShader(shader); // Unload shader
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context

View File

@ -5,7 +5,7 @@
* This example has been created using raylib 2.5 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
* Example contributed by Chris Camacho (@chriscamacho - http://bedroomcoders.co.uk/) * Example contributed by Chris Camacho (@chriscamacho - http://bedroomcoders.co.uk/)
* and reviewed by Ramon Santamaria (@raysan5) * and reviewed by Ramon Santamaria (@raysan5)
* *
* Copyright (c) 2019 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5) * Copyright (c) 2019 Chris Camacho (@chriscamacho) and Ramon Santamaria (@raysan5)
@ -14,13 +14,13 @@
* *
* The shader makes alpha holes in the forground to give the apearance of a top * 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... * 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 * 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 * going on without the spot light, great for a stealth type game where you
* have to avoid the spotlights. * have to avoid the spotlights.
* *
* The left hand side of the screen is in pitch dark except for where the spotlights are. * 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 * 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 * the two techniques, but by scaling the actual colour of the render texture rather
* than using alpha as a mask. * than using alpha as a mask.
@ -43,12 +43,12 @@
#define MAX_STARS 400 #define MAX_STARS 400
// Spot data // Spot data
typedef struct { typedef struct {
Vector2 pos; Vector2 pos;
Vector2 vel; Vector2 vel;
float inner; float inner;
float radius; float radius;
// Shader locations // Shader locations
unsigned int posLoc; unsigned int posLoc;
unsigned int innerLoc; unsigned int innerLoc;
@ -75,26 +75,26 @@ int main(void)
HideCursor(); HideCursor();
Texture texRay = LoadTexture("resources/raysan.png"); Texture texRay = LoadTexture("resources/raysan.png");
Star stars[MAX_STARS] = { 0 }; Star stars[MAX_STARS] = { 0 };
for (int n = 0; n < MAX_STARS; n++) ResetStar(&stars[n]); for (int n = 0; n < MAX_STARS; n++) ResetStar(&stars[n]);
// Progress all the stars on, so they don't all start in the centre // 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 m = 0; m < screenWidth/2.0; m++)
{ {
for (int n = 0; n < MAX_STARS; n++) UpdateStar(&stars[n]); for (int n = 0; n < MAX_STARS; n++) UpdateStar(&stars[n]);
} }
int frameCounter = 0; int frameCounter = 0;
// Use default vert shader // Use default vert shader
Shader shdrSpot = LoadShader(0, TextFormat("resources/shaders/glsl%i/spotlight.fs", GLSL_VERSION)); Shader shdrSpot = LoadShader(0, TextFormat("resources/shaders/glsl%i/spotlight.fs", GLSL_VERSION));
// Get the locations of spots in the shader // Get the locations of spots in the shader
Spot spots[MAX_SPOTS]; Spot spots[MAX_SPOTS];
for (int i = 0; i < MAX_SPOTS; i++) for (int i = 0; i < MAX_SPOTS; i++)
{ {
char posName[32] = "spots[x].pos\0"; char posName[32] = "spots[x].pos\0";
char innerName[32] = "spots[x].inner\0"; char innerName[32] = "spots[x].inner\0";
@ -103,36 +103,36 @@ int main(void)
posName[6] = '0' + i; posName[6] = '0' + i;
innerName[6] = '0' + i; innerName[6] = '0' + i;
radiusName[6] = '0' + i; radiusName[6] = '0' + i;
spots[i].posLoc = GetShaderLocation(shdrSpot, posName); spots[i].posLoc = GetShaderLocation(shdrSpot, posName);
spots[i].innerLoc = GetShaderLocation(shdrSpot, innerName); spots[i].innerLoc = GetShaderLocation(shdrSpot, innerName);
spots[i].radiusLoc = GetShaderLocation(shdrSpot, radiusName); spots[i].radiusLoc = GetShaderLocation(shdrSpot, radiusName);
} }
// Tell the shader how wide the screen is so we can have // Tell the shader how wide the screen is so we can have
// a pitch black half and a dimly lit half. // a pitch black half and a dimly lit half.
unsigned int wLoc = GetShaderLocation(shdrSpot, "screenWidth"); unsigned int wLoc = GetShaderLocation(shdrSpot, "screenWidth");
float sw = (float)GetScreenWidth(); float sw = (float)GetScreenWidth();
SetShaderValue(shdrSpot, wLoc, &sw, SHADER_UNIFORM_FLOAT); SetShaderValue(shdrSpot, wLoc, &sw, SHADER_UNIFORM_FLOAT);
// Randomise the locations and velocities of the spotlights // Randomize the locations and velocities of the spotlights
// and initialise the shader locations // and initialize the shader locations
for (int i = 0; i < MAX_SPOTS; i++) for (int i = 0; i < MAX_SPOTS; i++)
{ {
spots[i].pos.x = GetRandomValue(64, screenWidth - 64); spots[i].pos.x = GetRandomValue(64.0f, screenWidth - 64.0f);
spots[i].pos.y = GetRandomValue(64, screenHeight - 64); spots[i].pos.y = GetRandomValue(64.0f, screenHeight - 64.0f);
spots[i].vel = (Vector2){ 0, 0 }; spots[i].vel = (Vector2){ 0, 0 };
while ((fabs(spots[i].vel.x) + fabs(spots[i].vel.y)) < 2) while ((fabs(spots[i].vel.x) + fabs(spots[i].vel.y)) < 2)
{ {
spots[i].vel.x = GetRandomValue(-40, 40)/10.0; spots[i].vel.x = GetRandomValue(-400.f, 40.0f) / 10.0f;
spots[i].vel.y = GetRandomValue(-40, 40)/10.0; spots[i].vel.y = GetRandomValue(-400.f, 40.0f) / 10.0f;
} }
spots[i].inner = 28 * (i + 1); spots[i].inner = 28.0f * (i + 1);
spots[i].radius = 48 * (i + 1); spots[i].radius = 48.0f * (i + 1);
SetShaderValue(shdrSpot, spots[i].posLoc, &spots[i].pos.x, SHADER_UNIFORM_VEC2); SetShaderValue(shdrSpot, spots[i].posLoc, &spots[i].pos.x, SHADER_UNIFORM_VEC2);
SetShaderValue(shdrSpot, spots[i].innerLoc, &spots[i].inner, SHADER_UNIFORM_FLOAT); SetShaderValue(shdrSpot, spots[i].innerLoc, &spots[i].inner, SHADER_UNIFORM_FLOAT);
SetShaderValue(shdrSpot, spots[i].radiusLoc, &spots[i].radius, SHADER_UNIFORM_FLOAT); SetShaderValue(shdrSpot, spots[i].radiusLoc, &spots[i].radius, SHADER_UNIFORM_FLOAT);
@ -140,7 +140,7 @@ int main(void)
SetTargetFPS(60); // Set to run at 60 frames-per-second SetTargetFPS(60); // Set to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
@ -157,23 +157,23 @@ int main(void)
if (i == 0) if (i == 0)
{ {
Vector2 mp = GetMousePosition(); Vector2 mp = GetMousePosition();
spots[i].pos.x = mp.x; spots[i].pos.x = mp.x;
spots[i].pos.y = screenHeight - mp.y; spots[i].pos.y = screenHeight - mp.y;
} }
else else
{ {
spots[i].pos.x += spots[i].vel.x; spots[i].pos.x += spots[i].vel.x;
spots[i].pos.y += spots[i].vel.y; 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 < 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.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 < 64) spots[i].vel.y = -spots[i].vel.y;
if (spots[i].pos.y > (screenHeight - 64)) spots[i].vel.y = -spots[i].vel.y; if (spots[i].pos.y > (screenHeight - 64)) spots[i].vel.y = -spots[i].vel.y;
} }
SetShaderValue(shdrSpot, spots[i].posLoc, &spots[i].pos.x, SHADER_UNIFORM_VEC2); SetShaderValue(shdrSpot, spots[i].posLoc, &spots[i].pos.x, SHADER_UNIFORM_VEC2);
} }
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -184,14 +184,14 @@ int main(void)
for (int n = 0; n < MAX_STARS; n++) for (int n = 0; n < MAX_STARS; n++)
{ {
// Single pixel is just too small these days! // Single pixel is just too small these days!
DrawRectangle(stars[n].pos.x, stars[n].pos.y, 2, 2, WHITE); DrawRectangle((int)stars[n].pos.x, (int)stars[n].pos.y, 2, 2, WHITE);
} }
for (int i = 0; i < 16; i++) for (int i = 0; i < 16; i++)
{ {
DrawTexture(texRay, DrawTexture(texRay,
(screenWidth/2.0) + cos((frameCounter + i*8)/51.45f)*(screenWidth/2.2) - 32, (screenWidth/2.0f) + cos((frameCounter + i*8)/51.45f)*(screenWidth/2.2f) - 32,
(screenHeight/2.0) + sin((frameCounter + i*8)/17.87f)*(screenHeight/4.2), WHITE); (screenHeight/2.0f) + sin((frameCounter + i*8)/17.87f)*(screenHeight/4.2f), WHITE);
} }
// Draw spot lights // Draw spot lights
@ -204,11 +204,11 @@ int main(void)
EndShaderMode(); EndShaderMode();
DrawFPS(10, 10); DrawFPS(10, 10);
DrawText("Move the mouse!", 10, 30, 20, GREEN); DrawText("Move the mouse!", 10, 30, 20, GREEN);
DrawText("Pitch Black", screenWidth*0.2f, screenHeight/2, 20, GREEN); DrawText("Pitch Black", screenWidth*0.2f, screenHeight/2, 20, GREEN);
DrawText("Dark", screenWidth*.66f, screenHeight/2, 20, GREEN); DrawText("Dark", screenWidth*.66f, screenHeight/2, 20, GREEN);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -229,21 +229,21 @@ int main(void)
void ResetStar(Star *s) void ResetStar(Star *s)
{ {
s->pos = (Vector2){ GetScreenWidth()/2.0f, GetScreenHeight()/2.0f }; s->pos = (Vector2){ GetScreenWidth()/2.0f, GetScreenHeight()/2.0f };
do do
{ {
s->vel.x = (float)GetRandomValue(-1000, 1000)/100.0f; s->vel.x = (float)GetRandomValue(-1000, 1000)/100.0f;
s->vel.y = (float)GetRandomValue(-1000, 1000)/100.0f; s->vel.y = (float)GetRandomValue(-1000, 1000)/100.0f;
} while (!(fabs(s->vel.x) + (fabs(s->vel.y) > 1))); } while (!(fabs(s->vel.x) + (fabs(s->vel.y) > 1)));
s->pos = Vector2Add(s->pos, Vector2Multiply(s->vel, (Vector2){ 8.0f, 8.0f })); s->pos = Vector2Add(s->pos, Vector2Multiply(s->vel, (Vector2){ 8.0f, 8.0f }));
} }
void UpdateStar(Star *s) void UpdateStar(Star *s)
{ {
s->pos = Vector2Add(s->pos, s->vel); s->pos = Vector2Add(s->pos, s->vel);
if ((s->pos.x < 0) || (s->pos.x > GetScreenWidth()) || if ((s->pos.x < 0) || (s->pos.x > GetScreenWidth()) ||
(s->pos.y < 0) || (s->pos.y > GetScreenHeight())) (s->pos.y < 0) || (s->pos.y > GetScreenHeight()))
{ {

View File

@ -34,10 +34,10 @@ int main(void)
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture waves"); InitWindow(screenWidth, screenHeight, "raylib [shaders] example - texture waves");
// Load texture texture to apply shaders // Load texture texture to apply shaders
Texture2D texture = LoadTexture("resources/space.png"); Texture2D texture = LoadTexture("resources/space.png");
// Load shader and setup location points and values // Load shader and setup location points and values
Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/wave.fs", GLSL_VERSION)); Shader shader = LoadShader(0, TextFormat("resources/shaders/glsl%i/wave.fs", GLSL_VERSION));
@ -77,7 +77,7 @@ int main(void)
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
seconds += GetFrameTime(); seconds += GetFrameTime();
SetShaderValue(shader, secondsLoc, &seconds, SHADER_UNIFORM_FLOAT); SetShaderValue(shader, secondsLoc, &seconds, SHADER_UNIFORM_FLOAT);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -88,10 +88,10 @@ int main(void)
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginShaderMode(shader); BeginShaderMode(shader);
DrawTexture(texture, 0, 0, WHITE); DrawTexture(texture, 0, 0, WHITE);
DrawTexture(texture, texture.width, 0, WHITE); DrawTexture(texture, texture.width, 0, WHITE);
EndShaderMode(); EndShaderMode();
EndDrawing(); EndDrawing();
@ -102,7 +102,7 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadShader(shader); // Unload shader UnloadShader(shader); // Unload shader
UnloadTexture(texture); // Unload texture UnloadTexture(texture); // Unload texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -39,27 +39,32 @@ int main(void)
DrawText("some basic shapes available on raylib", 20, 20, 20, DARKGRAY); DrawText("some basic shapes available on raylib", 20, 20, 20, DARKGRAY);
DrawCircle(screenWidth/4, 120, 35, DARKBLUE); // Circle shapes and lines
DrawCircle(screenWidth/5, 120, 35, DARKBLUE);
DrawCircleGradient(screenWidth/5, 220, 60, GREEN, SKYBLUE);
DrawCircleLines(screenWidth/5, 340, 80, DARKBLUE);
// Rectangle shapes and ines
DrawRectangle(screenWidth/4*2 - 60, 100, 120, 60, RED); DrawRectangle(screenWidth/4*2 - 60, 100, 120, 60, RED);
DrawRectangleLines(screenWidth/4*2 - 40, 320, 80, 60, ORANGE); // NOTE: Uses QUADS internally, not lines
DrawRectangleGradientH(screenWidth/4*2 - 90, 170, 180, 130, MAROON, GOLD); DrawRectangleGradientH(screenWidth/4*2 - 90, 170, 180, 130, MAROON, GOLD);
DrawRectangleLines(screenWidth/4*2 - 40, 320, 80, 60, ORANGE); // NOTE: Uses QUADS internally, not lines
DrawTriangle((Vector2){screenWidth/4*3, 80}, // Triangle shapes and lines
(Vector2){screenWidth/4*3 - 60, 150}, DrawTriangle((Vector2){screenWidth/4.0f *3.0f, 80.0f},
(Vector2){screenWidth/4*3 + 60, 150}, VIOLET); (Vector2){screenWidth/4.0f *3.0f - 60.0f, 150.0f},
(Vector2){screenWidth/4.0f *3.0f + 60.0f, 150.0f}, VIOLET);
DrawTriangleLines((Vector2){screenWidth/4.0f*3.0f, 160.0f},
(Vector2){screenWidth/4.0f*3.0f - 20.0f, 230.0f},
(Vector2){screenWidth/4.0f*3.0f + 20.0f, 230.0f}, DARKBLUE);
// Polygon shapes and lines
DrawPoly((Vector2){screenWidth/4*3, 320}, 6, 80, 0, BROWN); DrawPoly((Vector2){screenWidth/4*3, 320}, 6, 80, 0, BROWN);
DrawPolyLinesEx((Vector2){screenWidth/4*3, 320}, 6, 80, 0, 6, BEIGE);
DrawCircleGradient(screenWidth/4, 220, 60, GREEN, SKYBLUE);
// NOTE: We draw all LINES based shapes together to optimize internal drawing, // NOTE: We draw all LINES based shapes together to optimize internal drawing,
// this way, all LINES are rendered in a single draw pass // this way, all LINES are rendered in a single draw pass
DrawLine(18, 42, screenWidth - 18, 42, BLACK); DrawLine(18, 42, screenWidth - 18, 42, BLACK);
DrawCircleLines(screenWidth/4, 340, 80, DARKBLUE);
DrawTriangleLines((Vector2){screenWidth/4*3, 160},
(Vector2){screenWidth/4*3 - 20, 230},
(Vector2){screenWidth/4*3 + 20, 230}, DARKBLUE);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }

View File

@ -37,10 +37,10 @@ int main(void)
// Fills colorsRecs data (for every rectangle) // Fills colorsRecs data (for every rectangle)
for (int i = 0; i < MAX_COLORS_COUNT; i++) for (int i = 0; i < MAX_COLORS_COUNT; i++)
{ {
colorsRecs[i].x = 20 + 100*(i%7) + 10*(i%7); colorsRecs[i].x = 20.0f + 100.0f *(i%7) + 10.0f *(i%7);
colorsRecs[i].y = 80 + 100*(i/7) + 10*(i/7); colorsRecs[i].y = 80.0f + 100.0f *(i/7) + 10.0f *(i/7);
colorsRecs[i].width = 100; colorsRecs[i].width = 100.0f;
colorsRecs[i].height = 100; colorsRecs[i].height = 100.0f;
} }
int colorState[MAX_COLORS_COUNT] = { 0 }; // Color state: 0-DEFAULT, 1-MOUSE_HOVER int colorState[MAX_COLORS_COUNT] = { 0 }; // Color state: 0-DEFAULT, 1-MOUSE_HOVER

View File

@ -43,39 +43,39 @@ int main(void)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// NOTE: All variables update happens inside GUI control functions // NOTE: All variables update happens inside GUI control functions
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawLine(500, 0, 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f)); DrawLine(500, 0, 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.6f));
DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f)); DrawRectangle(500, 0, GetScreenWidth() - 500, GetScreenHeight(), Fade(LIGHTGRAY, 0.3f));
DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, Fade(MAROON, 0.3)); DrawCircleSector(center, outerRadius, startAngle, endAngle, segments, Fade(MAROON, 0.3));
DrawCircleSectorLines(center, outerRadius, startAngle, endAngle, segments, Fade(MAROON, 0.6)); DrawCircleSectorLines(center, outerRadius, startAngle, endAngle, segments, Fade(MAROON, 0.6));
// Draw GUI controls // Draw GUI controls
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
startAngle = GuiSliderBar((Rectangle){ 600, 40, 120, 20}, "StartAngle", NULL, startAngle, 0, 720); startAngle = GuiSliderBar((Rectangle){ 600, 40, 120, 20}, "StartAngle", NULL, startAngle, 0, 720);
endAngle = GuiSliderBar((Rectangle){ 600, 70, 120, 20}, "EndAngle", NULL, endAngle, 0, 720); endAngle = GuiSliderBar((Rectangle){ 600, 70, 120, 20}, "EndAngle", NULL, endAngle, 0, 720);
outerRadius = GuiSliderBar((Rectangle){ 600, 140, 120, 20}, "Radius", NULL, outerRadius, 0, 200); outerRadius = GuiSliderBar((Rectangle){ 600, 140, 120, 20}, "Radius", NULL, outerRadius, 0, 200);
segments = GuiSliderBar((Rectangle){ 600, 170, 120, 20}, "Segments", NULL, segments, 0, 100); segments = GuiSliderBar((Rectangle){ 600, 170, 120, 20}, "Segments", NULL, segments, 0, 100);
//------------------------------------------------------------------------------ //------------------------------------------------------------------------------
minSegments = (int)ceilf((endAngle - startAngle) / 90); minSegments = (int)ceilf((endAngle - startAngle) / 90);
DrawText(TextFormat("MODE: %s", (segments >= minSegments)? "MANUAL" : "AUTO"), 600, 200, 10, (segments >= minSegments)? MAROON : DARKGRAY); DrawText(TextFormat("MODE: %s", (segments >= minSegments)? "MANUAL" : "AUTO"), 600, 200, 10, (segments >= minSegments)? MAROON : DARKGRAY);
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -22,12 +22,12 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - following eyes");
Vector2 scleraLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 scleraLeftPosition = { GetScreenWidth()/2.0f - 100.0f, GetScreenHeight()/2.0f };
Vector2 scleraRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2 }; Vector2 scleraRightPosition = { GetScreenWidth()/2.0f + 100.0f, GetScreenHeight()/2.0f };
float scleraRadius = 80; float scleraRadius = 80;
Vector2 irisLeftPosition = { GetScreenWidth()/2 - 100, GetScreenHeight()/2 }; Vector2 irisLeftPosition = { GetScreenWidth()/2.0f - 100.0f, GetScreenHeight()/2.0f };
Vector2 irisRightPosition = { GetScreenWidth()/2 + 100, GetScreenHeight()/2}; Vector2 irisRightPosition = { GetScreenWidth()/2.0f + 100.0f, GetScreenHeight()/2.0f };
float irisRadius = 24; float irisRadius = 24;
float angle = 0.0f; float angle = 0.0f;

View File

@ -22,7 +22,7 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines"); InitWindow(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines");
Vector2 start = { 0, 0 }; Vector2 start = { 0, 0 };
Vector2 end = { screenWidth, screenHeight }; Vector2 end = { (float)screenWidth, (float)screenHeight };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -32,8 +32,8 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) start = GetMousePosition(); if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) start = GetMousePosition();
else if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) end = GetMousePosition(); else if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) end = GetMousePosition();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw

View File

@ -45,7 +45,7 @@ int main(void)
CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE })) CheckCollisionPointRec(mousePosition, (Rectangle){ rec.x + rec.width - MOUSE_SCALE_MARK_SIZE, rec.y + rec.height - MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE, MOUSE_SCALE_MARK_SIZE }))
{ {
mouseScaleReady = true; mouseScaleReady = true;
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) mouseScaleMode = true; if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT)) mouseScaleMode = true;
} }
else mouseScaleReady = false; else mouseScaleReady = false;
@ -59,7 +59,7 @@ int main(void)
if (rec.width < MOUSE_SCALE_MARK_SIZE) rec.width = MOUSE_SCALE_MARK_SIZE; 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 (rec.height < MOUSE_SCALE_MARK_SIZE) rec.height = MOUSE_SCALE_MARK_SIZE;
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) mouseScaleMode = false; if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) mouseScaleMode = false;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------

View File

@ -12,14 +12,14 @@ uniform vec4 colDiffuse;
out vec4 finalColor; out vec4 finalColor;
// NOTE: Add here your custom variables // NOTE: Add here your custom variables
const float smoothing = 1.0/16.0;
void main() void main()
{ {
// Texel color fetching from texture sampler // Texel color fetching from texture sampler
// NOTE: Calculate alpha using signed distance field (SDF) // NOTE: Calculate alpha using signed distance field (SDF)
float distance = texture(texture0, fragTexCoord).a; float distanceFromOutline = texture(texture0, fragTexCoord).a - 0.5;
float alpha = smoothstep(0.5 - smoothing, 0.5 + smoothing, distance); float distanceChangePerFragment = length(vec2(dFdx(distanceFromOutline), dFdy(distanceFromOutline)));
float alpha = smoothstep(-distanceChangePerFragment, distanceChangePerFragment, distanceFromOutline);
// Calculate final fragment color // Calculate final fragment color
finalColor = vec4(fragColor.rgb, fragColor.a*alpha); finalColor = vec4(fragColor.rgb, fragColor.a*alpha);

View File

@ -3,17 +3,17 @@
* raylib [text] example - Draw 2D text in 3D * raylib [text] example - Draw 2D text in 3D
* *
* Draw a 2D text in 3D space, each letter is drawn in a quad (or 2 quads if backface is set) * Draw a 2D text in 3D space, each letter is drawn in a quad (or 2 quads if backface is set)
* where the texture coodinates of each quad map to the texture coordinates of the glyphs * where the texture coodinates of each quad map to the texture coordinates of the glyphs
* inside the font texture. * inside the font texture.
* A more efficient approach, i believe, would be to render the text in a render texture and * A more efficient approach, i believe, would be to render the text in a render texture and
* map that texture to a plane and render that, or maybe a shader but my method allows more * map that texture to a plane and render that, or maybe a shader but my method allows more
* flexibility...for example to change position of each letter individually to make somethink * flexibility...for example to change position of each letter individually to make somethink
* like a wavy text effect. * like a wavy text effect.
* *
* Special thanks to: * Special thanks to:
* @Nighten for the DrawTextStyle() code https://github.com/NightenDushi/Raylib_DrawTextStyle * @Nighten for the DrawTextStyle() code https://github.com/NightenDushi/Raylib_DrawTextStyle
* Chris Camacho (codifies - http://bedroomcoders.co.uk/) for the alpha discard shader * Chris Camacho (codifies - http://bedroomcoders.co.uk/) for the alpha discard shader
* *
* This example has been created using raylib 3.5 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
@ -26,7 +26,7 @@
#include "raylib.h" #include "raylib.h"
#include "rlgl.h" #include "rlgl.h"
#include <stddef.h> // Required for: NULL #include <stddef.h> // Required for: NULL
#include <math.h> // Required for: sinf() #include <math.h> // Required for: sinf()
// To make it work with the older RLGL module just comment the line below // To make it work with the older RLGL module just comment the line below
@ -80,13 +80,13 @@ int main(void)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
const int screenWidth = 800; const int screenWidth = 800;
const int screenHeight = 450; const int screenHeight = 450;
SetConfigFlags(FLAG_MSAA_4X_HINT|FLAG_VSYNC_HINT); SetConfigFlags(FLAG_MSAA_4X_HINT|FLAG_VSYNC_HINT);
InitWindow(screenWidth, screenHeight, "raylib [text] example - draw 2D text in 3D"); InitWindow(screenWidth, screenHeight, "raylib [text] example - draw 2D text in 3D");
bool spin = true; // Spin the camera? bool spin = true; // Spin the camera?
bool multicolor = false; // Multicolor mode bool multicolor = false; // Multicolor mode
// Define the camera to look into our 3d world // Define the camera to look into our 3d world
Camera3D camera = { 0 }; Camera3D camera = { 0 };
camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position
@ -94,41 +94,41 @@ int main(void)
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y camera.fovy = 45.0f; // Camera field-of-view Y
camera.projection = CAMERA_PERSPECTIVE; // Camera mode type camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
SetCameraMode(camera, CAMERA_ORBITAL); SetCameraMode(camera, CAMERA_ORBITAL);
Vector3 cubePosition = { 0.0f, 1.0f, 0.0f }; Vector3 cubePosition = { 0.0f, 1.0f, 0.0f };
Vector3 cubeSize = { 2.0f, 2.0f, 2.0f }; Vector3 cubeSize = { 2.0f, 2.0f, 2.0f };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
// Use the default font // Use the default font
Font font = GetFontDefault(); Font font = GetFontDefault();
float fontSize = 8.0f; float fontSize = 8.0f;
float fontSpacing = 0.5f; float fontSpacing = 0.5f;
float lineSpacing = -1.0f; float lineSpacing = -1.0f;
// Set the text (using markdown!) // Set the text (using markdown!)
char text[64] = "Hello ~~World~~ in 3D!"; char text[64] = "Hello ~~World~~ in 3D!";
Vector3 tbox = {0}; Vector3 tbox = {0};
int layers = 1; int layers = 1;
int quads = 0; int quads = 0;
float layerDistance = 0.01f; float layerDistance = 0.01f;
WaveTextConfig wcfg; WaveTextConfig wcfg;
wcfg.waveSpeed.x = wcfg.waveSpeed.y = 3.0f; wcfg.waveSpeed.z = 0.5f; wcfg.waveSpeed.x = wcfg.waveSpeed.y = 3.0f; wcfg.waveSpeed.z = 0.5f;
wcfg.waveOffset.x = wcfg.waveOffset.y = wcfg.waveOffset.z = 0.35f; wcfg.waveOffset.x = wcfg.waveOffset.y = wcfg.waveOffset.z = 0.35f;
wcfg.waveRange.x = wcfg.waveRange.y = wcfg.waveRange.z = 0.45f; wcfg.waveRange.x = wcfg.waveRange.y = wcfg.waveRange.z = 0.45f;
float time = 0.0f; float time = 0.0f;
// Setup a light and dark color // Setup a light and dark color
Color light = MAROON; Color light = MAROON;
Color dark = RED; Color dark = RED;
// Load the alpha discard shader // Load the alpha discard shader
Shader alphaDiscard = LoadShader(NULL, "resources/shaders/glsl330/alpha_discard.fs"); Shader alphaDiscard = LoadShader(NULL, "resources/shaders/glsl330/alpha_discard.fs");
// Array filled with multiple random colors (when multicolor mode is set) // Array filled with multiple random colors (when multicolor mode is set)
Color multi[TEXT_MAX_LAYERS] = {0}; Color multi[TEXT_MAX_LAYERS] = {0};
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
@ -150,7 +150,7 @@ int main(void)
UnloadFont(font); UnloadFont(font);
font = LoadFontEx(droppedFiles[0], fontSize, 0, 0); font = LoadFontEx(droppedFiles[0], fontSize, 0, 0);
} }
else if (IsFileExtension(droppedFiles[0], ".fnt")) else if (IsFileExtension(droppedFiles[0], ".fnt"))
{ {
UnloadFont(font); UnloadFont(font);
font = LoadFont(droppedFiles[0]); font = LoadFont(droppedFiles[0]);
@ -158,35 +158,35 @@ int main(void)
} }
ClearDroppedFiles(); ClearDroppedFiles();
} }
// Handle Events // Handle Events
if (IsKeyPressed(KEY_F1)) SHOW_LETTER_BOUNDRY = !SHOW_LETTER_BOUNDRY; if (IsKeyPressed(KEY_F1)) SHOW_LETTER_BOUNDRY = !SHOW_LETTER_BOUNDRY;
if (IsKeyPressed(KEY_F2)) SHOW_TEXT_BOUNDRY = !SHOW_TEXT_BOUNDRY; if (IsKeyPressed(KEY_F2)) SHOW_TEXT_BOUNDRY = !SHOW_TEXT_BOUNDRY;
if (IsKeyPressed(KEY_F3)) if (IsKeyPressed(KEY_F3))
{ {
// Handle camera change // Handle camera change
spin = !spin; spin = !spin;
// we need to reset the camera when changing modes // we need to reset the camera when changing modes
camera = (Camera3D){ 0 }; camera = (Camera3D){ 0 };
camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point camera.target = (Vector3){ 0.0f, 0.0f, 0.0f }; // Camera looking at point
camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target) camera.up = (Vector3){ 0.0f, 1.0f, 0.0f }; // Camera up vector (rotation towards target)
camera.fovy = 45.0f; // Camera field-of-view Y camera.fovy = 45.0f; // Camera field-of-view Y
camera.projection = CAMERA_PERSPECTIVE; // Camera mode type camera.projection = CAMERA_PERSPECTIVE; // Camera mode type
if (spin) if (spin)
{ {
camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position camera.position = (Vector3){ -10.0f, 15.0f, -10.0f }; // Camera position
SetCameraMode(camera, CAMERA_ORBITAL); SetCameraMode(camera, CAMERA_ORBITAL);
} }
else else
{ {
camera.position = (Vector3){ 10.0f, 10.0f, -10.0f }; // Camera position camera.position = (Vector3){ 10.0f, 10.0f, -10.0f }; // Camera position
SetCameraMode(camera, CAMERA_FREE); SetCameraMode(camera, CAMERA_FREE);
} }
} }
// Handle clicking the cube // Handle clicking the cube
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
Ray ray = GetMouseRay(GetMousePosition(), camera); Ray ray = GetMouseRay(GetMousePosition(), camera);
@ -194,18 +194,18 @@ int main(void)
bool collision = CheckCollisionRayBox(ray, bool collision = CheckCollisionRayBox(ray,
(BoundingBox){(Vector3){ cubePosition.x - cubeSize.x/2, cubePosition.y - cubeSize.y/2, cubePosition.z - cubeSize.z/2 }, (BoundingBox){(Vector3){ cubePosition.x - cubeSize.x/2, cubePosition.y - cubeSize.y/2, cubePosition.z - cubeSize.z/2 },
(Vector3){ cubePosition.x + cubeSize.x/2, cubePosition.y + cubeSize.y/2, cubePosition.z + cubeSize.z/2 }}); (Vector3){ cubePosition.x + cubeSize.x/2, cubePosition.y + cubeSize.y/2, cubePosition.z + cubeSize.z/2 }});
if (collision) if (collision)
{ {
// Generate new random colors // Generate new random colors
light = GenerateRandomColor(0.5f, 0.78f); light = GenerateRandomColor(0.5f, 0.78f);
dark = GenerateRandomColor(0.4f, 0.58f); dark = GenerateRandomColor(0.4f, 0.58f);
} }
} }
// Handle text layers changes // Handle text layers changes
if (IsKeyPressed(KEY_HOME)) { if (layers > 1) --layers; } if (IsKeyPressed(KEY_HOME)) { if (layers > 1) --layers; }
else if (IsKeyPressed(KEY_END)) { if (layers < TEXT_MAX_LAYERS) ++layers; } else if (IsKeyPressed(KEY_END)) { if (layers < TEXT_MAX_LAYERS) ++layers; }
// Handle text changes // Handle text changes
if (IsKeyPressed(KEY_LEFT)) fontSize -= 0.5f; if (IsKeyPressed(KEY_LEFT)) fontSize -= 0.5f;
else if (IsKeyPressed(KEY_RIGHT)) fontSize += 0.5f; else if (IsKeyPressed(KEY_RIGHT)) fontSize += 0.5f;
@ -215,53 +215,53 @@ int main(void)
else if (IsKeyPressed(KEY_PAGE_DOWN)) lineSpacing += 0.1f; else if (IsKeyPressed(KEY_PAGE_DOWN)) lineSpacing += 0.1f;
else if (IsKeyDown(KEY_INSERT)) layerDistance -= 0.001f; else if (IsKeyDown(KEY_INSERT)) layerDistance -= 0.001f;
else if (IsKeyDown(KEY_DELETE)) layerDistance += 0.001f; else if (IsKeyDown(KEY_DELETE)) layerDistance += 0.001f;
else if (IsKeyPressed(KEY_TAB)) else if (IsKeyPressed(KEY_TAB))
{ {
multicolor = !multicolor; // Enable /disable multicolor mode multicolor = !multicolor; // Enable /disable multicolor mode
if (multicolor) if (multicolor)
{ {
// Fill color array with random colors // Fill color array with random colors
for (int i = 0; i < TEXT_MAX_LAYERS; ++i) for (int i = 0; i < TEXT_MAX_LAYERS; ++i)
{ {
multi[i] = GenerateRandomColor(0.5f, 0.8f); multi[i] = GenerateRandomColor(0.5f, 0.8f);
multi[i].a = GetRandomValue(0, 255); multi[i].a = GetRandomValue(0, 255);
} }
} }
} }
// Handle text input // Handle text input
int ch = GetCharPressed(); int ch = GetCharPressed();
if (IsKeyPressed(KEY_BACKSPACE)) if (IsKeyPressed(KEY_BACKSPACE))
{ {
// Remove last char // Remove last char
int len = TextLength(text); int len = TextLength(text);
if (len > 0) text[len - 1] = '\0'; if (len > 0) text[len - 1] = '\0';
} }
else if (IsKeyPressed(KEY_ENTER)) else if (IsKeyPressed(KEY_ENTER))
{ {
// handle newline // handle newline
int len = TextLength(text); int len = TextLength(text);
if (len < sizeof(text) - 1) if (len < sizeof(text) - 1)
{ {
text[len] = '\n'; text[len] = '\n';
text[len+1] ='\0'; text[len+1] ='\0';
} }
} }
else else
{ {
// append only printable chars // append only printable chars
int len = TextLength(text); int len = TextLength(text);
if (len < sizeof(text) - 1) if (len < sizeof(text) - 1)
{ {
text[len] = ch; text[len] = ch;
text[len+1] ='\0'; text[len+1] ='\0';
} }
} }
// Measure 3D text so we can center it // Measure 3D text so we can center it
tbox = MeasureTextWave3D(font, text, fontSize, fontSpacing, lineSpacing); tbox = MeasureTextWave3D(font, text, fontSize, fontSpacing, lineSpacing);
UpdateCamera(&camera); // Update camera UpdateCamera(&camera); // Update camera
quads = 0; // Reset quad counter quads = 0; // Reset quad counter
time += GetFrameTime(); // Update timer needed by `DrawTextWave3D()` time += GetFrameTime(); // Update timer needed by `DrawTextWave3D()`
@ -272,37 +272,37 @@ int main(void)
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
BeginMode3D(camera); BeginMode3D(camera);
DrawCubeV(cubePosition, cubeSize, dark); DrawCubeV(cubePosition, cubeSize, dark);
DrawCubeWires(cubePosition, 2.1f, 2.1f, 2.1f, light); DrawCubeWires(cubePosition, 2.1f, 2.1f, 2.1f, light);
DrawGrid(10, 2.0f); DrawGrid(10, 2.0f);
// Use a shader to handle the depth buffer issue with transparent textures // Use a shader to handle the depth buffer issue with transparent textures
// NOTE: more info at https://bedroomcoders.co.uk/raylib-billboards-advanced-use/ // NOTE: more info at https://bedroomcoders.co.uk/raylib-billboards-advanced-use/
BeginShaderMode(alphaDiscard); BeginShaderMode(alphaDiscard);
// Draw the 3D text above the red cube // Draw the 3D text above the red cube
rlPushMatrix(); rlPushMatrix();
rlRotatef(90.0f, 1.0f, 0.0f, 0.0f); rlRotatef(90.0f, 1.0f, 0.0f, 0.0f);
rlRotatef(90.0f, 0.0f, 0.0f, -1.0f); rlRotatef(90.0f, 0.0f, 0.0f, -1.0f);
for (int i = 0; i < layers; ++i) for (int i = 0; i < layers; ++i)
{ {
Color clr = light; Color clr = light;
if(multicolor) clr = multi[i]; if(multicolor) clr = multi[i];
DrawTextWave3D(font, text, (Vector3){ -tbox.x/2.0f, layerDistance*i, -4.5f }, fontSize, fontSpacing, lineSpacing, true, &wcfg, time, clr); DrawTextWave3D(font, text, (Vector3){ -tbox.x/2.0f, layerDistance*i, -4.5f }, fontSize, fontSpacing, lineSpacing, true, &wcfg, time, clr);
} }
// Draw the text boundry if set // Draw the text boundry if set
if (SHOW_TEXT_BOUNDRY) DrawCubeWiresV((Vector3){ 0.0f, 0.0f, -4.5f + tbox.z/2 }, tbox, dark); if (SHOW_TEXT_BOUNDRY) DrawCubeWiresV((Vector3){ 0.0f, 0.0f, -4.5f + tbox.z/2 }, tbox, dark);
rlPopMatrix(); rlPopMatrix();
// Don't draw the letter boundries for the 3D text below // Don't draw the letter boundries for the 3D text below
bool slb = SHOW_LETTER_BOUNDRY; bool slb = SHOW_LETTER_BOUNDRY;
SHOW_LETTER_BOUNDRY = false; SHOW_LETTER_BOUNDRY = false;
// Draw 3D options (use default font) // Draw 3D options (use default font)
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
rlPushMatrix(); rlPushMatrix();
@ -313,35 +313,35 @@ int main(void)
Vector3 pos = { -m.x/2.0f, 0.01f, 2.0f}; Vector3 pos = { -m.x/2.0f, 0.01f, 2.0f};
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = (char *)TextFormat("< SPACING: %2.1f >", fontSpacing); opt = (char *)TextFormat("< SPACING: %2.1f >", fontSpacing);
quads += TextLength(opt); quads += TextLength(opt);
m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = (char *)TextFormat("< LINE: %2.1f >", lineSpacing); opt = (char *)TextFormat("< LINE: %2.1f >", lineSpacing);
quads += TextLength(opt); quads += TextLength(opt);
m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, BLUE);
pos.z += 1.0f + m.z; pos.z += 1.0f + m.z;
opt = (char *)TextFormat("< LBOX: %3s >", slb? "ON" : "OFF"); opt = (char *)TextFormat("< LBOX: %3s >", slb? "ON" : "OFF");
quads += TextLength(opt); quads += TextLength(opt);
m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = (char *)TextFormat("< TBOX: %3s >", SHOW_TEXT_BOUNDRY? "ON" : "OFF"); opt = (char *)TextFormat("< TBOX: %3s >", SHOW_TEXT_BOUNDRY? "ON" : "OFF");
quads += TextLength(opt); quads += TextLength(opt);
m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, RED);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = (char *)TextFormat("< LAYER DISTANCE: %.3f >", layerDistance); opt = (char *)TextFormat("< LAYER DISTANCE: %.3f >", layerDistance);
quads += TextLength(opt); quads += TextLength(opt);
m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 8.0f, 1.0f, 0.0f);
@ -349,7 +349,7 @@ int main(void)
DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, DARKPURPLE); DrawText3D(GetFontDefault(), opt, pos, 8.0f, 1.0f, 0.0f, false, DARKPURPLE);
rlPopMatrix(); rlPopMatrix();
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
// Draw 3D info text (use default font) // Draw 3D info text (use default font)
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
opt = "All the text displayed here is in 3D"; opt = "All the text displayed here is in 3D";
@ -358,74 +358,74 @@ int main(void)
pos = (Vector3){-m.x/2.0f, 0.01f, 2.0f}; pos = (Vector3){-m.x/2.0f, 0.01f, 2.0f};
DrawText3D(GetFontDefault(), opt, pos, 10.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 10.0f, 0.5f, 0.0f, false, DARKBLUE);
pos.z += 1.5f + m.z; pos.z += 1.5f + m.z;
opt = "press [Left]/[Right] to change the font size"; opt = "press [Left]/[Right] to change the font size";
quads += 44; quads += 44;
m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = "press [Up]/[Down] to change the font spacing"; opt = "press [Up]/[Down] to change the font spacing";
quads += 44; quads += 44;
m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = "press [PgUp]/[PgDown] to change the line spacing"; opt = "press [PgUp]/[PgDown] to change the line spacing";
quads += 48; quads += 48;
m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = "press [F1] to toggle the letter boundry"; opt = "press [F1] to toggle the letter boundry";
quads += 39; quads += 39;
m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
pos.z += 0.5f + m.z; pos.z += 0.5f + m.z;
opt = "press [F2] to toggle the text boundry"; opt = "press [F2] to toggle the text boundry";
quads += 37; quads += 37;
m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f); m = MeasureText3D(GetFontDefault(), opt, 6.0f, 0.5f, 0.0f);
pos.x = -m.x/2.0f; pos.x = -m.x/2.0f;
DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE); DrawText3D(GetFontDefault(), opt, pos, 6.0f, 0.5f, 0.0f, false, DARKBLUE);
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
SHOW_LETTER_BOUNDRY = slb; SHOW_LETTER_BOUNDRY = slb;
EndShaderMode(); EndShaderMode();
EndMode3D(); EndMode3D();
// Draw 2D info text & stats // Draw 2D info text & stats
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
DrawText("Drag & drop a font file to change the font!\nType something, see what happens!\n\n" DrawText("Drag & drop a font file to change the font!\nType something, see what happens!\n\n"
"Press [F3] to toggle the camera", 10, 35, 10, BLACK); "Press [F3] to toggle the camera", 10, 35, 10, BLACK);
quads += TextLength(text)*2*layers; quads += TextLength(text)*2*layers;
char *tmp = (char *)TextFormat("%2i layer(s) | %s camera | %4i quads (%4i verts)", layers, spin? "ORBITAL" : "FREE", quads, quads*4); char *tmp = (char *)TextFormat("%2i layer(s) | %s camera | %4i quads (%4i verts)", layers, spin? "ORBITAL" : "FREE", quads, quads*4);
int width = MeasureText(tmp, 10); int width = MeasureText(tmp, 10);
DrawText(tmp, screenWidth - 20 - width, 10, 10, DARKGREEN); DrawText(tmp, screenWidth - 20 - width, 10, 10, DARKGREEN);
tmp = "[Home]/[End] to add/remove 3D text layers"; tmp = "[Home]/[End] to add/remove 3D text layers";
width = MeasureText(tmp, 10); width = MeasureText(tmp, 10);
DrawText(tmp, screenWidth - 20 - width, 25, 10, DARKGRAY); DrawText(tmp, screenWidth - 20 - width, 25, 10, DARKGRAY);
tmp = "[Insert]/[Delete] to increase/decrease distance between layers"; tmp = "[Insert]/[Delete] to increase/decrease distance between layers";
width = MeasureText(tmp, 10); width = MeasureText(tmp, 10);
DrawText(tmp, screenWidth - 20 - width, 40, 10, DARKGRAY); DrawText(tmp, screenWidth - 20 - width, 40, 10, DARKGRAY);
tmp = "click the [CUBE] for a random color"; tmp = "click the [CUBE] for a random color";
width = MeasureText(tmp, 10); width = MeasureText(tmp, 10);
DrawText(tmp, screenWidth - 20 - width, 55, 10, DARKGRAY); DrawText(tmp, screenWidth - 20 - width, 55, 10, DARKGRAY);
tmp = "[Tab] to toggle multicolor mode"; tmp = "[Tab] to toggle multicolor mode";
width = MeasureText(tmp, 10); width = MeasureText(tmp, 10);
DrawText(tmp, screenWidth - 20 - width, 70, 10, DARKGRAY); DrawText(tmp, screenWidth - 20 - width, 70, 10, DARKGRAY);
//------------------------------------------------------------------------- //-------------------------------------------------------------------------
DrawFPS(10, 10); DrawFPS(10, 10);
EndDrawing(); EndDrawing();
@ -461,22 +461,22 @@ void DrawTextCodepoint3D(Font font, int codepoint, Vector3 position, float fontS
// NOTE: We consider chars padding when drawing, it could be required for outline/glow shader effects // NOTE: We consider chars padding when drawing, it could be required for outline/glow shader effects
Rectangle srcRec = { font.recs[index].x - (float)font.charsPadding, font.recs[index].y - (float)font.charsPadding, Rectangle srcRec = { font.recs[index].x - (float)font.charsPadding, font.recs[index].y - (float)font.charsPadding,
font.recs[index].width + 2.0f*font.charsPadding, font.recs[index].height + 2.0f*font.charsPadding }; font.recs[index].width + 2.0f*font.charsPadding, font.recs[index].height + 2.0f*font.charsPadding };
float width = (float)(font.recs[index].width + 2.0f*font.charsPadding)/(float)font.baseSize*scale; float width = (float)(font.recs[index].width + 2.0f*font.charsPadding)/(float)font.baseSize*scale;
float height = (float)(font.recs[index].height + 2.0f*font.charsPadding)/(float)font.baseSize*scale; float height = (float)(font.recs[index].height + 2.0f*font.charsPadding)/(float)font.baseSize*scale;
if(font.texture.id > 0) if(font.texture.id > 0)
{ {
const float x = 0.0f; const float x = 0.0f;
const float y = 0.0f; const float y = 0.0f;
const float z = 0.0f; const float z = 0.0f;
// normalized texture coordinates of the glyph inside the font texture (0.0f -> 1.0f) // normalized texture coordinates of the glyph inside the font texture (0.0f -> 1.0f)
const float tx = srcRec.x/font.texture.width; const float tx = srcRec.x/font.texture.width;
const float ty = srcRec.y/font.texture.height; const float ty = srcRec.y/font.texture.height;
const float tw = (srcRec.x+srcRec.width)/font.texture.width; const float tw = (srcRec.x+srcRec.width)/font.texture.width;
const float th = (srcRec.y+srcRec.height)/font.texture.height; const float th = (srcRec.y+srcRec.height)/font.texture.height;
if(SHOW_LETTER_BOUNDRY) if(SHOW_LETTER_BOUNDRY)
DrawCubeWiresV((Vector3){ position.x + width/2, position.y, position.z + height/2}, (Vector3){ width, LETTER_BOUNDRY_SIZE, height }, LETTER_BOUNDRY_COLOR); DrawCubeWiresV((Vector3){ position.x + width/2, position.y, position.z + height/2}, (Vector3){ width, LETTER_BOUNDRY_SIZE, height }, LETTER_BOUNDRY_COLOR);
@ -489,17 +489,17 @@ void DrawTextCodepoint3D(Font font, int codepoint, Vector3 position, float fontS
#endif #endif
rlPushMatrix(); rlPushMatrix();
rlTranslatef(position.x, position.y, position.z); rlTranslatef(position.x, position.y, position.z);
rlBegin(RL_QUADS); rlBegin(RL_QUADS);
rlColor4ub(tint.r, tint.g, tint.b, tint.a); rlColor4ub(tint.r, tint.g, tint.b, tint.a);
// Front Face // Front Face
rlNormal3f(0.0f, 1.0f, 0.0f); // Normal Pointing Up rlNormal3f(0.0f, 1.0f, 0.0f); // Normal Pointing Up
rlTexCoord2f(tx, ty); rlVertex3f(x, y, z); // Top Left Of The Texture and Quad rlTexCoord2f(tx, ty); rlVertex3f(x, y, z); // Top Left Of The Texture and Quad
rlTexCoord2f(tx, th); rlVertex3f(x, y, z + height); // Bottom Left Of The Texture and Quad rlTexCoord2f(tx, th); rlVertex3f(x, y, z + height); // Bottom Left Of The Texture and Quad
rlTexCoord2f(tw, th); rlVertex3f(x + width, y, z + height); // Bottom Right Of The Texture and Quad rlTexCoord2f(tw, th); rlVertex3f(x + width, y, z + height); // Bottom Right Of The Texture and Quad
rlTexCoord2f(tw, ty); rlVertex3f(x + width, y, z); // Top Right Of The Texture and Quad rlTexCoord2f(tw, ty); rlVertex3f(x + width, y, z); // Top Right Of The Texture and Quad
if (backface) if (backface)
{ {
// Back Face // Back Face
@ -526,9 +526,9 @@ void DrawText3D(Font font, const char *text, Vector3 position, float fontSize, f
float textOffsetY = 0.0f; // Offset between lines (on line break '\n') float textOffsetY = 0.0f; // Offset between lines (on line break '\n')
float textOffsetX = 0.0f; // Offset X to next character to draw float textOffsetX = 0.0f; // Offset X to next character to draw
float scale = fontSize/(float)font.baseSize; float scale = fontSize/(float)font.baseSize;
for (int i = 0; i < length;) for (int i = 0; i < length;)
{ {
// Get next codepoint from byte string and glyph index in font // Get next codepoint from byte string and glyph index in font
@ -562,12 +562,12 @@ void DrawText3D(Font font, const char *text, Vector3 position, float fontSize, f
} }
} }
Vector3 MeasureText3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing) Vector3 MeasureText3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing)
{ {
int len = TextLength(text); int len = TextLength(text);
int tempLen = 0; // Used to count longer text line num chars int tempLen = 0; // Used to count longer text line num chars
int lenCounter = 0; int lenCounter = 0;
float tempTextWidth = 0.0f; // Used to count longer text line width float tempTextWidth = 0.0f; // Used to count longer text line width
float scale = fontSize/(float)font.baseSize; float scale = fontSize/(float)font.baseSize;
@ -623,9 +623,9 @@ void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSiz
float textOffsetY = 0.0f; // Offset between lines (on line break '\n') float textOffsetY = 0.0f; // Offset between lines (on line break '\n')
float textOffsetX = 0.0f; // Offset X to next character to draw float textOffsetX = 0.0f; // Offset X to next character to draw
float scale = fontSize/(float)font.baseSize; float scale = fontSize/(float)font.baseSize;
bool wave = false; bool wave = false;
for (int i = 0, k = 0; i < length; ++k) for (int i = 0, k = 0; i < length; ++k)
@ -649,7 +649,7 @@ void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSiz
} }
else if (codepoint == '~') else if (codepoint == '~')
{ {
if (GetNextCodepoint(&text[i+1], &codepointByteCount) == '~') if (GetNextCodepoint(&text[i+1], &codepointByteCount) == '~')
{ {
codepointByteCount += 1; codepointByteCount += 1;
wave = !wave; wave = !wave;
@ -666,7 +666,7 @@ void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSiz
pos.y += sinf(time*config->waveSpeed.y-k*config->waveOffset.y)*config->waveRange.y; pos.y += sinf(time*config->waveSpeed.y-k*config->waveOffset.y)*config->waveRange.y;
pos.z += sinf(time*config->waveSpeed.z-k*config->waveOffset.z)*config->waveRange.z; pos.z += sinf(time*config->waveSpeed.z-k*config->waveOffset.z)*config->waveRange.z;
} }
DrawTextCodepoint3D(font, codepoint, (Vector3){ pos.x + textOffsetX, pos.y, pos.z + textOffsetY }, fontSize, backface, tint); DrawTextCodepoint3D(font, codepoint, (Vector3){ pos.x + textOffsetX, pos.y, pos.z + textOffsetY }, fontSize, backface, tint);
} }
@ -678,12 +678,12 @@ void DrawTextWave3D(Font font, const char *text, Vector3 position, float fontSiz
} }
} }
Vector3 MeasureTextWave3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing) Vector3 MeasureTextWave3D(Font font, const char* text, float fontSize, float fontSpacing, float lineSpacing)
{ {
int len = TextLength(text); int len = TextLength(text);
int tempLen = 0; // Used to count longer text line num chars int tempLen = 0; // Used to count longer text line num chars
int lenCounter = 0; int lenCounter = 0;
float tempTextWidth = 0.0f; // Used to count longer text line width float tempTextWidth = 0.0f; // Used to count longer text line width
float scale = fontSize/(float)font.baseSize; float scale = fontSize/(float)font.baseSize;

View File

@ -35,8 +35,8 @@ int main(void)
// NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR // NOTE: On 2D drawing it won't be noticeable, it looks like FILTER_BILINEAR
GenTextureMipmaps(&font.texture); GenTextureMipmaps(&font.texture);
float fontSize = font.baseSize; float fontSize = (float)font.baseSize;
Vector2 fontPosition = { 40, screenHeight/2 - 80 }; Vector2 fontPosition = { 40.0f, screenHeight/2.0f - 80.0f };
Vector2 textSize = { 0.0f, 0.0f }; Vector2 textSize = { 0.0f, 0.0f };
// Setup texture scaling filter // Setup texture scaling filter
@ -86,7 +86,7 @@ int main(void)
if (IsFileExtension(droppedFiles[0], ".ttf")) if (IsFileExtension(droppedFiles[0], ".ttf"))
{ {
UnloadFont(font); UnloadFont(font);
font = LoadFontEx(droppedFiles[0], fontSize, 0, 0); font = LoadFontEx(droppedFiles[0], (int)fontSize, 0, 0);
ClearDroppedFiles(); ClearDroppedFiles();
} }
} }

View File

@ -9,7 +9,7 @@
* - BMFonts > Angel code font fileformat, sprite font image must be provided * - BMFonts > Angel code font fileformat, sprite font image must be provided
* together with the .fnt file, font generation cna not be configured * together with the .fnt file, font generation cna not be configured
* - XNA Spritefont > Sprite font image, following XNA Spritefont conventions, * - XNA Spritefont > Sprite font image, following XNA Spritefont conventions,
* Characters in image must follow some spacing and order rules * Characters in image must follow some spacing and order rules
* *
* This example has been created using raylib 2.6 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)

View File

@ -31,7 +31,7 @@ int main(void)
// NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures/Fonts MUST be loaded after Window initialization (OpenGL context is required)
const char msg[50] = "Signed Distance Fields"; const char msg[50] = "Signed Distance Fields";
// Loading file to memory // Loading file to memory
unsigned int fileSize = 0; unsigned int fileSize = 0;
unsigned char *fileData = LoadFileData("resources/anonymous_pro_bold.ttf", &fileSize); unsigned char *fileData = LoadFileData("resources/anonymous_pro_bold.ttf", &fileSize);
@ -40,7 +40,7 @@ int main(void)
Font fontDefault = { 0 }; Font fontDefault = { 0 };
fontDefault.baseSize = 16; fontDefault.baseSize = 16;
fontDefault.charsCount = 95; fontDefault.charsCount = 95;
// Loading font data from memory data // Loading font data from memory data
// Parameters > font size: 16, no chars array provided (0), chars count: 95 (autogenerate chars array) // Parameters > font size: 16, no chars array provided (0), chars count: 95 (autogenerate chars array)
fontDefault.chars = LoadFontData(fileData, fileSize, 16, 0, 95, FONT_DEFAULT); fontDefault.chars = LoadFontData(fileData, fileSize, 16, 0, 95, FONT_DEFAULT);
@ -59,7 +59,7 @@ int main(void)
atlas = GenImageFontAtlas(fontSDF.chars, &fontSDF.recs, 95, 16, 0, 1); atlas = GenImageFontAtlas(fontSDF.chars, &fontSDF.recs, 95, 16, 0, 1);
fontSDF.texture = LoadTextureFromImage(atlas); fontSDF.texture = LoadTextureFromImage(atlas);
UnloadImage(atlas); UnloadImage(atlas);
UnloadFileData(fileData); // Free memory from loaded file UnloadFileData(fileData); // Free memory from loaded file
// Load SDF required shader (we use default vertex shader) // Load SDF required shader (we use default vertex shader)
@ -70,7 +70,7 @@ int main(void)
Vector2 textSize = { 0.0f, 0.0f }; Vector2 textSize = { 0.0f, 0.0f };
float fontSize = 16.0f; float fontSize = 16.0f;
int currentFont = 0; // 0 - fontDefault, 1 - fontSDF int currentFont = 0; // 0 - fontDefault, 1 - fontSDF
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -8,8 +8,8 @@
* - Every character and every line must be separated the same distance * - Every character and every line must be separated the same distance
* - Rectangles must be defined by a MAGENTA color background * - Rectangles must be defined by a MAGENTA color background
* *
* If following this constraints, a font can be provided just by an image, * 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 is quite handy to avoid additional information files (like BMFonts use).
* *
* This example has been created using raylib 1.0 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
@ -38,14 +38,14 @@ int main(void)
Font font2 = LoadFont("resources/custom_alagard.png"); // Font loading Font font2 = LoadFont("resources/custom_alagard.png"); // Font loading
Font font3 = LoadFont("resources/custom_jupiter_crash.png"); // Font loading Font font3 = LoadFont("resources/custom_jupiter_crash.png"); // Font loading
Vector2 fontPosition1 = { screenWidth/2 - MeasureTextEx(font1, msg1, (float)font1.baseSize, -3).x/2, Vector2 fontPosition1 = { screenWidth/2.0f - MeasureTextEx(font1, msg1, (float)font1.baseSize, -3).x/2,
screenHeight/2 - font1.baseSize/2 - 80 }; screenHeight/2.0f - font1.baseSize/2.0f - 80.0f };
Vector2 fontPosition2 = { screenWidth/2 - MeasureTextEx(font2, msg2, (float)font2.baseSize, -2).x/2, Vector2 fontPosition2 = { screenWidth/2.0f - MeasureTextEx(font2, msg2, (float)font2.baseSize, -2.0f).x/2.0f,
screenHeight/2 - font2.baseSize/2 - 10 }; screenHeight/2.0f - font2.baseSize/2.0f - 10.0f };
Vector2 fontPosition3 = { screenWidth/2.0f - MeasureTextEx(font3, msg3, (float)font3.baseSize, 2).x/2, Vector2 fontPosition3 = { screenWidth/2.0f - MeasureTextEx(font3, msg3, (float)font3.baseSize, 2.0f).x/2.0f,
screenHeight/2.0f - font3.baseSize/2 + 50 }; screenHeight/2.0f - font3.baseSize/2.0f + 50.0f };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -58,7 +58,7 @@ int main(void)
name[letterCount] = (char)key; name[letterCount] = (char)key;
letterCount++; letterCount++;
} }
key = GetCharPressed(); // Check next character in the queue key = GetCharPressed(); // Check next character in the queue
} }

View File

@ -52,8 +52,8 @@ int main(void)
for (int i = 0; i < MAX_FONTS; i++) for (int i = 0; i < MAX_FONTS; i++)
{ {
positions[i].x = screenWidth/2.0f - MeasureTextEx(fonts[i], messages[i], fonts[i].baseSize*2.0f, spacings[i]).x/2.0f; positions[i].x = screenWidth/2.0f - MeasureTextEx(fonts[i], messages[i], fonts[i].baseSize*2.0f, (float)spacings[i]).x/2.0f;
positions[i].y = 60 + fonts[i].baseSize + 45*i; positions[i].y = 60.0f + fonts[i].baseSize + 45.0f*i;
} }
// Small Y position corrections // Small Y position corrections
@ -62,7 +62,7 @@ int main(void)
positions[7].y -= 8; positions[7].y -= 8;
Color colors[MAX_FONTS] = { MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, LIME, GOLD, RED }; Color colors[MAX_FONTS] = { MAROON, ORANGE, DARKGREEN, DARKBLUE, DARKPURPLE, LIME, GOLD, RED };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

View File

@ -29,14 +29,14 @@ tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet ris
bool resizing = false; bool resizing = false;
bool wordWrap = true; bool wordWrap = true;
Rectangle container = { 25, 25, screenWidth - 50, screenHeight - 250}; Rectangle container = { 25.0f, 25.0f, screenWidth - 50.0f, screenHeight - 250.0f };
Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 }; Rectangle resizer = { container.x + container.width - 17, container.y + container.height - 17, 14, 14 };
// Minimum width and heigh for the container rectangle // Minimum width and heigh for the container rectangle
const float minWidth = 60; const float minWidth = 60;
const float minHeight = 60; const float minHeight = 60;
const float maxWidth = screenWidth - 50; const float maxWidth = screenWidth - 50.0f;
const float maxHeight = screenHeight - 160; const float maxHeight = screenHeight - 160.0f;
Vector2 lastMouse = { 0.0f, 0.0f }; // Stores last mouse coordinates Vector2 lastMouse = { 0.0f, 0.0f }; // Stores last mouse coordinates
Color borderColor = MAROON; // Container border color Color borderColor = MAROON; // Container border color
@ -61,7 +61,7 @@ tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet ris
// Container resizing logic // Container resizing logic
if (resizing) if (resizing)
{ {
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) resizing = false; if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) resizing = false;
float width = container.width + (mouse.x - lastMouse.x); float width = container.width + (mouse.x - lastMouse.x);
container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth; container.width = (width > minWidth)? ((width < maxWidth)? width : maxWidth) : minWidth;
@ -72,7 +72,7 @@ tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet ris
else else
{ {
// Check if we're resizing // Check if we're resizing
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) && CheckCollisionPointRec(mouse, resizer)) resizing = true; if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) && CheckCollisionPointRec(mouse, resizer)) resizing = true;
} }
// Move resizer rectangle properly // Move resizer rectangle properly
@ -99,16 +99,16 @@ tempor incididunt ut labore et dolore magna aliqua. Nec ullamcorper sit amet ris
// Draw bottom info // Draw bottom info
DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY); DrawRectangle(0, screenHeight - 54, screenWidth, 54, GRAY);
DrawRectangleRec((Rectangle){ 382, screenHeight - 34, 12, 12 }, MAROON); DrawRectangleRec((Rectangle){ 382.0f, screenHeight - 34.0f, 12.0f, 12.0f }, MAROON);
DrawText("Word Wrap: ", 313, screenHeight-115, 20, BLACK); DrawText("Word Wrap: ", 313, screenHeight-115, 20, BLACK);
if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED); if (wordWrap) DrawText("ON", 447, screenHeight - 115, 20, RED);
else DrawText("OFF", 447, screenHeight - 115, 20, BLACK); else DrawText("OFF", 447, screenHeight - 115, 20, BLACK);
DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 86, 20, GRAY); DrawText("Press [SPACE] to toggle word wrap", 218, screenHeight - 86, 20, GRAY);
DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE); DrawText("Click hold & drag the to resize the container", 155, screenHeight - 38, 20, RAYWHITE);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }

View File

@ -180,7 +180,7 @@ int main(int argc, char **argv)
if (IsKeyPressed(KEY_SPACE)) RandomizeEmoji(); if (IsKeyPressed(KEY_SPACE)) RandomizeEmoji();
// Set the selected emoji and copy its text to clipboard // Set the selected emoji and copy its text to clipboard
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) && (hovered != -1) && (hovered != selected)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) && (hovered != -1) && (hovered != selected))
{ {
selected = hovered; selected = hovered;
selectedPos = hoveredPos; selectedPos = hoveredPos;

View File

@ -32,12 +32,12 @@ int main(void)
Texture2D fgTexture = LoadTextureFromImage(fgImage); // Image converted to texture, GPU memory (VRAM) Texture2D fgTexture = LoadTextureFromImage(fgImage); // Image converted to texture, GPU memory (VRAM)
// Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM // Once image has been converted to texture and uploaded to VRAM, it can be unloaded from RAM
UnloadImage(bgImage); UnloadImage(bgImage);
UnloadImage(fgImage); UnloadImage(fgImage);
const int blendCountMax = 4; const int blendCountMax = 4;
BlendMode blendMode = 0; BlendMode blendMode = 0;
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
@ -49,7 +49,7 @@ int main(void)
else blendMode++; else blendMode++;
} }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
@ -65,7 +65,7 @@ int main(void)
// Draw the texts // Draw the texts
DrawText("Press SPACE to change blend modes.", 310, 350, 10, GRAY); DrawText("Press SPACE to change blend modes.", 310, 350, 10, GRAY);
switch (blendMode) switch (blendMode)
{ {
case BLEND_ALPHA: DrawText("Current: BLEND_ALPHA", (screenWidth / 2) - 60, 370, 10, GRAY); break; case BLEND_ALPHA: DrawText("Current: BLEND_ALPHA", (screenWidth / 2) - 60, 370, 10, GRAY); break;
@ -74,7 +74,7 @@ int main(void)
case BLEND_ADD_COLORS: DrawText("Current: BLEND_ADD_COLORS", (screenWidth / 2) - 60, 370, 10, GRAY); break; case BLEND_ADD_COLORS: DrawText("Current: BLEND_ADD_COLORS", (screenWidth / 2) - 60, 370, 10, GRAY); break;
default: break; default: break;
} }
DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", screenWidth - 330, screenHeight - 20, 10, GRAY); DrawText("(c) Cyberpunk Street Environment by Luis Zuno (@ansimuz)", screenWidth - 330, screenHeight - 20, 10, GRAY);
EndDrawing(); EndDrawing();
@ -88,6 +88,6 @@ int main(void)
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View File

@ -49,7 +49,7 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) if (IsMouseButtonDown(MOUSE_BUTTON_LEFT))
{ {
// Create more bunnies // Create more bunnies
for (int i = 0; i < 100; i++) for (int i = 0; i < 100; i++)

View File

@ -21,24 +21,24 @@ int main(int argc, char **argv)
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
int screenWidth = 800; int screenWidth = 800;
int screenHeight = 450; int screenHeight = 450;
SetConfigFlags(FLAG_WINDOW_RESIZABLE); // Make the window resizable SetConfigFlags(FLAG_WINDOW_RESIZABLE); // Make the window resizable
InitWindow(screenWidth, screenHeight, "raylib [textures] example - Draw part of a texture tiled"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - Draw part of a texture tiled");
// NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) // NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required)
Texture texPattern = LoadTexture("resources/patterns.png"); Texture texPattern = LoadTexture("resources/patterns.png");
SetTextureFilter(texPattern, TEXTURE_FILTER_TRILINEAR); // Makes the texture smoother when upscaled SetTextureFilter(texPattern, TEXTURE_FILTER_TRILINEAR); // Makes the texture smoother when upscaled
// Coordinates for all patterns inside the texture // Coordinates for all patterns inside the texture
const Rectangle recPattern[] = { const Rectangle recPattern[] = {
(Rectangle){ 3, 3, 66, 66 }, (Rectangle){ 3, 3, 66, 66 },
(Rectangle){ 75, 3, 100, 100 }, (Rectangle){ 75, 3, 100, 100 },
(Rectangle){ 3, 75, 66, 66 }, (Rectangle){ 3, 75, 66, 66 },
(Rectangle){ 7, 156, 50, 50 }, (Rectangle){ 7, 156, 50, 50 },
(Rectangle){ 85, 106, 90, 45 }, (Rectangle){ 85, 106, 90, 45 },
(Rectangle){ 75, 154, 100, 60} (Rectangle){ 75, 154, 100, 60}
}; };
// Setup colors // Setup colors
const Color colors[] = { BLACK, MAROON, ORANGE, BLUE, PURPLE, BEIGE, LIME, RED, DARKGRAY, SKYBLUE }; const Color colors[] = { BLACK, MAROON, ORANGE, BLUE, PURPLE, BEIGE, LIME, RED, DARKGRAY, SKYBLUE };
enum { MAX_COLORS = SIZEOF(colors) }; enum { MAX_COLORS = SIZEOF(colors) };
@ -51,21 +51,21 @@ int main(int argc, char **argv)
colorRec[i].y = 22.0f + 256.0f + MARGIN_SIZE + y; colorRec[i].y = 22.0f + 256.0f + MARGIN_SIZE + y;
colorRec[i].width = COLOR_SIZE*2.0f; colorRec[i].width = COLOR_SIZE*2.0f;
colorRec[i].height = (float)COLOR_SIZE; colorRec[i].height = (float)COLOR_SIZE;
if (i == (MAX_COLORS/2 - 1)) if (i == (MAX_COLORS/2 - 1))
{ {
x = 0; x = 0;
y += COLOR_SIZE + MARGIN_SIZE; y += COLOR_SIZE + MARGIN_SIZE;
} }
else x += (COLOR_SIZE*2 + MARGIN_SIZE); else x += (COLOR_SIZE*2 + MARGIN_SIZE);
} }
int activePattern = 0, activeCol = 0; int activePattern = 0, activeCol = 0;
float scale = 1.0f, rotation = 0.0f; float scale = 1.0f, rotation = 0.0f;
SetTargetFPS(60); SetTargetFPS(60);
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------
// Main game loop // Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key while (!WindowShouldClose()) // Detect window close button or ESC key
{ {
@ -73,22 +73,22 @@ int main(int argc, char **argv)
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
screenWidth = GetScreenWidth(); screenWidth = GetScreenWidth();
screenHeight = GetScreenHeight(); screenHeight = GetScreenHeight();
// Handle mouse // Handle mouse
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
const Vector2 mouse = GetMousePosition(); const Vector2 mouse = GetMousePosition();
// Check which pattern was clicked and set it as the active pattern // Check which pattern was clicked and set it as the active pattern
for (int i = 0; i < SIZEOF(recPattern); i++) for (int i = 0; i < SIZEOF(recPattern); i++)
{ {
if (CheckCollisionPointRec(mouse, (Rectangle){ 2 + MARGIN_SIZE + recPattern[i].x, 40 + MARGIN_SIZE + recPattern[i].y, recPattern[i].width, recPattern[i].height })) if (CheckCollisionPointRec(mouse, (Rectangle){ 2 + MARGIN_SIZE + recPattern[i].x, 40 + MARGIN_SIZE + recPattern[i].y, recPattern[i].width, recPattern[i].height }))
{ {
activePattern = i; activePattern = i;
break; break;
} }
} }
// Check to see which color was clicked and set it as the active color // Check to see which color was clicked and set it as the active color
for (int i = 0; i < MAX_COLORS; ++i) for (int i = 0; i < MAX_COLORS; ++i)
{ {
@ -99,67 +99,67 @@ int main(int argc, char **argv)
} }
} }
} }
// Handle keys // Handle keys
// Change scale // Change scale
if (IsKeyPressed(KEY_UP)) scale += 0.25f; if (IsKeyPressed(KEY_UP)) scale += 0.25f;
if (IsKeyPressed(KEY_DOWN)) scale -= 0.25f; if (IsKeyPressed(KEY_DOWN)) scale -= 0.25f;
if (scale > 10.0f) scale = 10.0f; if (scale > 10.0f) scale = 10.0f;
else if ( scale <= 0.0f) scale = 0.25f; else if ( scale <= 0.0f) scale = 0.25f;
// Change rotation // Change rotation
if (IsKeyPressed(KEY_LEFT)) rotation -= 25.0f; if (IsKeyPressed(KEY_LEFT)) rotation -= 25.0f;
if (IsKeyPressed(KEY_RIGHT)) rotation += 25.0f; if (IsKeyPressed(KEY_RIGHT)) rotation += 25.0f;
// Reset // Reset
if (IsKeyPressed(KEY_SPACE)) { rotation = 0.0f; scale = 1.0f; } if (IsKeyPressed(KEY_SPACE)) { rotation = 0.0f; scale = 1.0f; }
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Draw // Draw
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
BeginDrawing(); BeginDrawing();
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
// Draw the tiled area // Draw the tiled area
DrawTextureTiled(texPattern, recPattern[activePattern], (Rectangle){(float)OPT_WIDTH+MARGIN_SIZE, (float)MARGIN_SIZE, screenWidth - OPT_WIDTH - 2.0f*MARGIN_SIZE, screenHeight - 2.0f*MARGIN_SIZE}, DrawTextureTiled(texPattern, recPattern[activePattern], (Rectangle){(float)OPT_WIDTH+MARGIN_SIZE, (float)MARGIN_SIZE, screenWidth - OPT_WIDTH - 2.0f*MARGIN_SIZE, screenHeight - 2.0f*MARGIN_SIZE},
(Vector2){0.0f, 0.0f}, rotation, scale, colors[activeCol]); (Vector2){0.0f, 0.0f}, rotation, scale, colors[activeCol]);
// Draw options // Draw options
DrawRectangle(MARGIN_SIZE, MARGIN_SIZE, OPT_WIDTH - MARGIN_SIZE, screenHeight - 2*MARGIN_SIZE, ColorAlpha(LIGHTGRAY, 0.5f)); DrawRectangle(MARGIN_SIZE, MARGIN_SIZE, OPT_WIDTH - MARGIN_SIZE, screenHeight - 2*MARGIN_SIZE, ColorAlpha(LIGHTGRAY, 0.5f));
DrawText("Select Pattern", 2 + MARGIN_SIZE, 30 + MARGIN_SIZE, 10, BLACK); DrawText("Select Pattern", 2 + MARGIN_SIZE, 30 + MARGIN_SIZE, 10, BLACK);
DrawTexture(texPattern, 2 + MARGIN_SIZE, 40 + MARGIN_SIZE, BLACK); DrawTexture(texPattern, 2 + MARGIN_SIZE, 40 + MARGIN_SIZE, BLACK);
DrawRectangle(2 + MARGIN_SIZE + (int)recPattern[activePattern].x, 40 + MARGIN_SIZE + (int)recPattern[activePattern].y, (int)recPattern[activePattern].width, (int)recPattern[activePattern].height, ColorAlpha(DARKBLUE, 0.3f)); DrawRectangle(2 + MARGIN_SIZE + (int)recPattern[activePattern].x, 40 + MARGIN_SIZE + (int)recPattern[activePattern].y, (int)recPattern[activePattern].width, (int)recPattern[activePattern].height, ColorAlpha(DARKBLUE, 0.3f));
DrawText("Select Color", 2+MARGIN_SIZE, 10+256+MARGIN_SIZE, 10, BLACK); DrawText("Select Color", 2+MARGIN_SIZE, 10+256+MARGIN_SIZE, 10, BLACK);
for (int i = 0; i < MAX_COLORS; i++) for (int i = 0; i < MAX_COLORS; i++)
{ {
DrawRectangleRec(colorRec[i], colors[i]); DrawRectangleRec(colorRec[i], colors[i]);
if (activeCol == i) DrawRectangleLinesEx(colorRec[i], 3, ColorAlpha(WHITE, 0.5f)); if (activeCol == i) DrawRectangleLinesEx(colorRec[i], 3, ColorAlpha(WHITE, 0.5f));
} }
DrawText("Scale (UP/DOWN to change)", 2 + MARGIN_SIZE, 80 + 256 + MARGIN_SIZE, 10, BLACK); DrawText("Scale (UP/DOWN to change)", 2 + MARGIN_SIZE, 80 + 256 + MARGIN_SIZE, 10, BLACK);
DrawText(TextFormat("%.2fx", scale), 2 + MARGIN_SIZE, 92 + 256 + MARGIN_SIZE, 20, BLACK); DrawText(TextFormat("%.2fx", scale), 2 + MARGIN_SIZE, 92 + 256 + MARGIN_SIZE, 20, BLACK);
DrawText("Rotation (LEFT/RIGHT to change)", 2 + MARGIN_SIZE, 122 + 256 + MARGIN_SIZE, 10, BLACK); DrawText("Rotation (LEFT/RIGHT to change)", 2 + MARGIN_SIZE, 122 + 256 + MARGIN_SIZE, 10, BLACK);
DrawText(TextFormat("%.0f degrees", rotation), 2 + MARGIN_SIZE, 134 + 256 + MARGIN_SIZE, 20, BLACK); DrawText(TextFormat("%.0f degrees", rotation), 2 + MARGIN_SIZE, 134 + 256 + MARGIN_SIZE, 20, BLACK);
DrawText("Press [SPACE] to reset", 2 + MARGIN_SIZE, 164 + 256 + MARGIN_SIZE, 10, DARKBLUE); DrawText("Press [SPACE] to reset", 2 + MARGIN_SIZE, 164 + 256 + MARGIN_SIZE, 10, DARKBLUE);
// Draw FPS // Draw FPS
DrawText(TextFormat("%i FPS", GetFPS()), 2 + MARGIN_SIZE, 2 + MARGIN_SIZE, 20, BLACK); DrawText(TextFormat("%i FPS", GetFPS()), 2 + MARGIN_SIZE, 2 + MARGIN_SIZE, 20, BLACK);
EndDrawing(); EndDrawing();
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
} }
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texPattern); // Unload texture UnloadTexture(texPattern); // Unload texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
return 0; return 0;
} }

View File

@ -59,7 +59,7 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON) || IsKeyPressed(KEY_RIGHT)) if (IsMouseButtonPressed(MOUSE_BUTTON_LEFT) || IsKeyPressed(KEY_RIGHT))
{ {
currentTexture = (currentTexture + 1)%NUM_TEXTURES; // Cycle between the textures currentTexture = (currentTexture + 1)%NUM_TEXTURES; // Cycle between the textures
} }

View File

@ -53,7 +53,7 @@ int main(void)
Image imOrigin = LoadImage("resources/parrots.png"); // Loaded in CPU memory (RAM) Image imOrigin = LoadImage("resources/parrots.png"); // Loaded in CPU memory (RAM)
ImageFormat(&imOrigin, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8); // Format image to RGBA 32bit (required for texture update) <-- ISSUE ImageFormat(&imOrigin, PIXELFORMAT_UNCOMPRESSED_R8G8B8A8); // Format image to RGBA 32bit (required for texture update) <-- ISSUE
Texture2D texture = LoadTextureFromImage(imOrigin); // Image converted to texture, GPU memory (VRAM) Texture2D texture = LoadTextureFromImage(imOrigin); // Image converted to texture, GPU memory (VRAM)
Image imCopy = ImageCopy(imOrigin); Image imCopy = ImageCopy(imOrigin);
int currentProcess = NONE; int currentProcess = NONE;
@ -72,7 +72,7 @@ int main(void)
{ {
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
// Mouse toggle group logic // Mouse toggle group logic
for (int i = 0; i < NUM_PROCESSES; i++) for (int i = 0; i < NUM_PROCESSES; i++)
{ {
@ -80,7 +80,7 @@ int main(void)
{ {
mouseHoverRec = i; mouseHoverRec = i;
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT))
{ {
currentProcess = i; currentProcess = i;
textureReload = true; textureReload = true;
@ -89,7 +89,7 @@ int main(void)
} }
else mouseHoverRec = -1; else mouseHoverRec = -1;
} }
// Keyboard toggle group logic // Keyboard toggle group logic
if (IsKeyPressed(KEY_DOWN)) if (IsKeyPressed(KEY_DOWN))
{ {
@ -109,7 +109,7 @@ int main(void)
{ {
UnloadImage(imCopy); // Unload image-copy data UnloadImage(imCopy); // Unload image-copy data
imCopy = ImageCopy(imOrigin); // Restore image-copy from image-origin imCopy = ImageCopy(imOrigin); // Restore image-copy from image-origin
// NOTE: Image processing is a costly CPU process to be done every frame, // NOTE: Image processing is a costly CPU process to be done every frame,
// If image processing is required in a frame-basis, it should be done // If image processing is required in a frame-basis, it should be done
// with a texture and by shaders // with a texture and by shaders

View File

@ -19,7 +19,7 @@ int main(void)
const int screenHeight = 450; const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [texture] example - image text drawing"); InitWindow(screenWidth, screenHeight, "raylib [texture] example - image text drawing");
Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM) Image parrots = LoadImage("resources/parrots.png"); // Load image in CPU memory (RAM)
// TTF Font loading with custom generation parameters // TTF Font loading with custom generation parameters

View File

@ -88,7 +88,7 @@ int main(void)
else colorMouseHover = -1; else colorMouseHover = -1;
} }
if ((colorMouseHover >= 0) && IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) if ((colorMouseHover >= 0) && IsMouseButtonPressed(MOUSE_BUTTON_LEFT))
{ {
colorSelected = colorMouseHover; colorSelected = colorMouseHover;
colorSelectedPrev = colorSelected; colorSelectedPrev = colorSelected;
@ -107,7 +107,7 @@ int main(void)
EndTextureMode(); EndTextureMode();
} }
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON) || (GetGestureDetected() == GESTURE_DRAG)) if (IsMouseButtonDown(MOUSE_BUTTON_LEFT) || (GetGestureDetected() == GESTURE_DRAG))
{ {
// Paint circle into render texture // Paint circle into render texture
// NOTE: To avoid discontinuous circles, we could store // NOTE: To avoid discontinuous circles, we could store
@ -117,7 +117,7 @@ int main(void)
EndTextureMode(); EndTextureMode();
} }
if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT))
{ {
if (!mouseWasPressed) if (!mouseWasPressed)
{ {
@ -132,7 +132,7 @@ int main(void)
if (mousePos.y > 50) DrawCircle((int)mousePos.x, (int)mousePos.y, brushSize, colors[0]); if (mousePos.y > 50) DrawCircle((int)mousePos.x, (int)mousePos.y, brushSize, colors[0]);
EndTextureMode(); EndTextureMode();
} }
else if (IsMouseButtonReleased(MOUSE_RIGHT_BUTTON) && mouseWasPressed) else if (IsMouseButtonReleased(MOUSE_BUTTON_RIGHT) && mouseWasPressed)
{ {
colorSelected = colorSelectedPrev; colorSelected = colorSelectedPrev;
mouseWasPressed = false; mouseWasPressed = false;
@ -144,7 +144,7 @@ int main(void)
// Image saving logic // Image saving logic
// NOTE: Saving painted texture to a default named image // NOTE: Saving painted texture to a default named image
if ((btnSaveMouseHover && IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) || IsKeyPressed(KEY_S)) if ((btnSaveMouseHover && IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) || IsKeyPressed(KEY_S))
{ {
Image image = GetTextureData(target.texture); Image image = GetTextureData(target.texture);
ImageFlipVertical(&image); ImageFlipVertical(&image);
@ -177,7 +177,7 @@ int main(void)
// Draw drawing circle for reference // Draw drawing circle for reference
if (mousePos.y > 50) if (mousePos.y > 50)
{ {
if (IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) DrawCircleLines(mousePos.x, mousePos.y, brushSize, GRAY); if (IsMouseButtonDown(MOUSE_BUTTON_RIGHT)) DrawCircleLines((int)mousePos.x, (int)mousePos.y, brushSize, GRAY);
else DrawCircle(GetMouseX(), GetMouseY(), brushSize, colors[colorSelected]); else DrawCircle(GetMouseX(), GetMouseY(), brushSize, colors[colorSelected]);
} }

View File

@ -5,7 +5,7 @@
* This example has been created using raylib 3.7 (www.raylib.com) * 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) * raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details)
* *
* Example contributed by Chris Camacho (@codifies - bedroomcoders.co.uk) and * Example contributed by Chris Camacho (@codifies - bedroomcoders.co.uk) and
* reviewed by Ramon Santamaria (@raysan5) * reviewed by Ramon Santamaria (@raysan5)
* *
* Copyright (c) 2021 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5) * Copyright (c) 2021 Chris Camacho (@codifies) and Ramon Santamaria (@raysan5)
@ -52,7 +52,7 @@ int main(void)
InitWindow(screenWidth, screenHeight, "raylib [textures] example - textured polygon"); InitWindow(screenWidth, screenHeight, "raylib [textures] example - textured polygon");
Texture texture = LoadTexture("resources/cat.png"); Texture texture = LoadTexture("resources/cat.png");
float ang = 0; float ang = 0;
SetTargetFPS(60); // Set our game to run at 60 frames-per-second SetTargetFPS(60); // Set our game to run at 60 frames-per-second
@ -64,9 +64,9 @@ int main(void)
// Update // Update
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
ang++; ang++;
Vector2 positions[MAX_POINTS] = { 0 }; Vector2 positions[MAX_POINTS] = { 0 };
for (int i = 0; i < MAX_POINTS; i++) positions[i] = Vector2Rotate(points[i], ang); for (int i = 0; i < MAX_POINTS; i++) positions[i] = Vector2Rotate(points[i], ang);
//---------------------------------------------------------------------------------- //----------------------------------------------------------------------------------
@ -77,8 +77,8 @@ int main(void)
ClearBackground(RAYWHITE); ClearBackground(RAYWHITE);
DrawText("textured polygon", 20, 20, 20, DARKGRAY); DrawText("textured polygon", 20, 20, 20, DARKGRAY);
DrawTexturePoly(texture, (Vector2){ GetScreenWidth()/2, GetScreenHeight()/2 }, DrawTexturePoly(texture, (Vector2){ GetScreenWidth()/2, GetScreenHeight()/2 },
positions, texcoords, MAX_POINTS, WHITE); positions, texcoords, MAX_POINTS, WHITE);
EndDrawing(); EndDrawing();
@ -88,7 +88,7 @@ int main(void)
// De-Initialization // De-Initialization
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------
UnloadTexture(texture); // Unload texture UnloadTexture(texture); // Unload texture
CloseWindow(); // Close window and OpenGL context CloseWindow(); // Close window and OpenGL context
//-------------------------------------------------------------------------------------- //--------------------------------------------------------------------------------------

Binary file not shown.

After

Width:  |  Height:  |  Size: 190 KiB

View File

@ -54,8 +54,8 @@ int main(void)
.height = height, .height = height,
.format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, .format = PIXELFORMAT_UNCOMPRESSED_R8G8B8A8,
.mipmaps = 1 .mipmaps = 1
}; };
Texture2D checked = LoadTextureFromImage(checkedIm); Texture2D checked = LoadTextureFromImage(checkedIm);
UnloadImage(checkedIm); // Unload CPU (RAM) image data (pixels) UnloadImage(checkedIm); // Unload CPU (RAM) image data (pixels)
//--------------------------------------------------------------------------------------- //---------------------------------------------------------------------------------------

View File

@ -53,10 +53,10 @@ int main(void)
// Check button state // Check button state
if (CheckCollisionPointRec(mousePoint, btnBounds)) if (CheckCollisionPointRec(mousePoint, btnBounds))
{ {
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) btnState = 2; if (IsMouseButtonDown(MOUSE_BUTTON_LEFT)) btnState = 2;
else btnState = 1; else btnState = 1;
if (IsMouseButtonReleased(MOUSE_LEFT_BUTTON)) btnAction = true; if (IsMouseButtonReleased(MOUSE_BUTTON_LEFT)) btnAction = true;
} }
else btnState = 0; else btnState = 0;

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