48 Commits

Author SHA1 Message Date
26c08059be update splib version
Some checks failed
Linux arm64 / Build (push) Failing after 9s
2025-03-04 23:16:17 +01:00
87b4bf20b7 remove unused include 2025-03-04 12:29:58 +01:00
06c17abd40 complete splib migration
Some checks failed
Linux arm64 / Build (push) Failing after 58s
2025-03-03 11:27:42 +01:00
000970dcb9 fix colored text serialize issues
Some checks failed
Linux arm64 / Build (push) Failing after 9s
2025-02-23 22:43:48 +01:00
df15e5efd5 remove unused code 2025-02-23 22:36:42 +01:00
a34e217e98 migrate to splib 2025-02-23 22:33:50 +01:00
74aac7a03a begin splib migration
Some checks failed
Linux arm64 / Build (push) Failing after 1m58s
2025-02-23 13:26:33 +01:00
63536535f6 use splib VarInt 2025-02-23 11:19:04 +01:00
67cb368297 change libsdl to libsdl2 2025-02-23 11:13:52 +01:00
5fc9125c67 imgui include 2025-02-23 11:13:31 +01:00
e80c6a3c60 action: cache only packages
All checks were successful
Linux arm64 / Build (push) Successful in 3m15s
2024-06-03 22:25:23 +02:00
680c180b4b action: update xmake cache name
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2024-06-03 20:03:29 +02:00
a4e90b455d updated runner
Some checks failed
Linux arm64 / Build (push) Has been cancelled
2024-06-03 20:02:19 +02:00
e2f1850987 move VarInt.cpp
All checks were successful
Linux arm64 / Build (push) Successful in 4m47s
2024-04-15 17:02:47 +02:00
95e6967d0d fart sound on death
All checks were successful
Linux arm64 / Build (push) Successful in 4m29s
2024-04-15 16:53:44 +02:00
b2323d2761 Update MainRenderer.cpp to load GLB model for the world with better map
All checks were successful
Linux arm64 / Build (push) Successful in 4m36s
2024-04-15 16:40:58 +02:00
84ae607cd1 footsteps velocity
All checks were successful
Linux arm64 / Build (push) Successful in 4m27s
2024-04-15 16:05:28 +02:00
e254d677d0 add foosteps
All checks were successful
Linux arm64 / Build (push) Successful in 4m32s
2024-04-15 15:58:45 +02:00
f0023c1b22 Update display name in ClientMain.cpp to Blitz
All checks were successful
Linux arm64 / Build (push) Successful in 4m20s
2024-04-14 22:14:06 +02:00
71600e7a8b Map with thick walls for collisions and update MainRenderer.cpp 2024-04-14 22:13:39 +02:00
b917a8d1fa fix endgame gui timers
All checks were successful
Linux arm64 / Build (push) Successful in 4m42s
2024-04-14 19:55:51 +02:00
8880056b1c move Client to client namespace
All checks were successful
Linux arm64 / Build (push) Successful in 5m17s
2024-04-14 19:27:42 +02:00
9bb5c85f41 refactor ColoredPart 2024-04-14 19:15:28 +02:00
c6c811ca17 refactor PlayerInfo 2024-04-14 19:11:08 +02:00
40c551a4dc move KeyAction to input 2024-04-14 19:06:29 +02:00
a5bb2f74dd move VarInt to protocol 2024-04-14 19:01:59 +02:00
d9cc43a7a1 rename display to input 2024-04-14 18:58:12 +02:00
9a297026cd move EMASmoother to maths 2024-04-14 18:53:22 +02:00
2f141698ad better ObjectNotifier doc 2024-04-14 18:41:56 +02:00
af5f084234 moved client listeners 2024-04-14 18:40:45 +02:00
fd61870ebe include wiki in readme
All checks were successful
Linux arm64 / Build (push) Successful in 4m28s
2024-04-14 18:13:31 +02:00
5595213f3d Add valgrind testing to readme
All checks were successful
Linux arm64 / Build (push) Successful in 4m21s
2024-04-14 13:09:59 +02:00
8158dda315 fix mainmenu client when server crashes
All checks were successful
Linux arm64 / Build (push) Successful in 4m17s
2024-04-13 19:12:34 +02:00
026a841a04 change default game port
All checks were successful
Linux arm64 / Build (push) Successful in 4m49s
2024-04-13 17:29:47 +02:00
56e2f2f434 reset game state when kicked 2024-04-13 17:28:34 +02:00
a5debe81ac fix valgrind error 2024-04-13 17:22:58 +02:00
7157e45eac disconnect clients when server forcefully shuts down 2024-04-13 16:56:34 +02:00
8f51d468d2 fixing crash 2024-04-13 16:54:18 +02:00
8ed7044733 hide options on kick 2024-04-13 16:52:51 +02:00
b85115b364 add end game music 2024-04-13 16:42:19 +02:00
5cf539fb6f fix server handshake 2024-04-13 16:41:59 +02:00
34365714de freeze imgui and sdl version 2024-04-13 16:32:23 +02:00
391e4b8a33 arrange assets folder 2024-04-13 16:29:56 +02:00
231db48bab remove libs folder 2024-04-13 16:25:40 +02:00
21aa1b0241 refactor listeners 2024-04-13 16:25:25 +02:00
e04444125d refactor PacketFactory 2024-04-13 16:13:10 +02:00
33f1c53148 fix server handshake 2024-04-13 16:04:58 +02:00
af0ef9eeb5 refactor tcpsocket 2024-04-13 15:58:28 +02:00
154 changed files with 1968 additions and 68780 deletions

View File

@@ -6,12 +6,7 @@ on: [push]
jobs: jobs:
Build: Build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Install deps
run : |
apt update
apt install -y libsdl2-dev libassimp-dev libglew-dev
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v3 uses: actions/checkout@v3
@@ -20,7 +15,7 @@ jobs:
with: with:
xmake-version: latest xmake-version: latest
actions-cache-folder: '.xmake-cache' actions-cache-folder: '.xmake-cache'
actions-cache-key: 'ubuntu' actions-cache-key: 'xmake-ubuntu'
- name: Calc deps hash - name: Calc deps hash
uses: seepine/hash-files@v1 uses: seepine/hash-files@v1
@@ -33,14 +28,14 @@ jobs:
- name: Packages cache - name: Packages cache
uses: actions/cache@v4 uses: actions/cache@v4
with: with:
path: ~/.xmake path: ~/.xmake/packages
key: ${{ runner.os }}-${{ steps.get-hash.outputs.hash }} key: ${{ runner.os }}-${{ steps.get-hash.outputs.hash }}
- name: XMake config - name: XMake config
run: xmake f -p linux -y --root run: xmake f -p linux -y
- name: Build - name: Build
run: xmake --root run: xmake
- name: Test - name: Test
run: xmake test --root run: xmake test

View File

@@ -86,3 +86,25 @@ xmake project -k compile_commands
``` ```
Alternatively, you can install the [XMake extension](https://marketplace.visualstudio.com/items?itemName=tboox.xmake-vscode) for VsCode. Alternatively, you can install the [XMake extension](https://marketplace.visualstudio.com/items?itemName=tboox.xmake-vscode) for VsCode.
# Valgrind 🔍
We can inspect the client binary to look for memory leak.
First, switch compilation mode to valgrind :
```
xmake f -m valgrind
```
Then build and run :
```
xmake
xmake run
```
# Wiki 📚
Available [here](https://git.ale-pri.com/Blitz/Blitz/wiki)

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,797 @@
# Blender 4.0.2
# www.blender.org
mtllib base_deambu.mtl
o sol
v -50.000000 0.150000 18.150000
v 50.000000 0.150000 18.150000
v -50.000000 0.150000 -18.150000
v 50.000000 0.150000 -18.150000
v -50.000000 0.000000 18.150000
v 50.000000 0.000000 18.150000
v -50.000000 0.000000 -18.150000
v 50.000000 0.000000 -18.150000
vn -0.0000 1.0000 -0.0000
vn -0.0000 -1.0000 -0.0000
vn -1.0000 -0.0000 -0.0000
vn -0.0000 -0.0000 1.0000
vn 1.0000 -0.0000 -0.0000
vn -0.0000 -0.0000 -1.0000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 1.000000 1.000000
vt 0.000000 1.000000
s 0
f 1/1/1 2/2/1 4/3/1 3/4/1
f 5/1/2 7/4/2 8/3/2 6/2/2
f 1/1/3 3/4/3 7/4/3 5/1/3
f 2/2/4 1/1/4 5/1/4 6/2/4
f 4/3/5 2/2/5 6/2/5 8/3/5
f 3/4/6 4/3/6 8/3/6 7/4/6
o mur_dc_partie_basse
v 40.400005 0.000003 -9.649998
v -32.133335 -0.000002 -9.650001
v 40.400005 2.500000 -9.649998
v -32.133335 2.500000 -9.650001
v 40.400005 2.500000 -9.079998
v -32.133335 2.500000 -9.080001
v 40.400005 2.650000 -9.079998
v -32.133335 2.650000 -9.080001
v 40.400005 2.650000 -7.729998
v -32.133335 2.650000 -7.730001
v 40.400005 2.750000 -7.729998
v -32.133335 2.750000 -7.730001
v 40.400005 2.750000 -7.669998
v -32.133335 2.750000 -7.670001
v 40.400005 4.250000 -7.669998
v -32.133335 4.250000 -7.670001
v 40.400005 4.250000 -7.669998
v -32.133335 4.250000 -7.670001
v 40.400005 4.250000 -7.969998
v -32.133335 4.250000 -7.970001
v 40.400005 6.000000 -7.969998
v -32.133335 6.000000 -7.970001
v 40.400005 2.500000 -9.649998
v -32.133335 2.500000 -9.650001
v 40.400005 6.000000 -9.649998
v 40.400005 6.000000 -9.079998
v 40.400005 4.250000 -9.079998
v 40.400005 4.250000 -7.729998
v 40.400005 4.250000 -7.729998
v 40.400005 4.250000 -7.669998
v 40.400005 4.250000 -9.085698
v 40.400005 6.000000 -9.085698
v -32.133335 6.000000 -9.650001
v -32.133335 6.000000 -9.080001
v -32.133335 4.250000 -9.080001
v -32.133335 4.250000 -7.730001
v -32.133335 4.250000 -7.730001
v -32.133335 4.250000 -7.670001
v -32.133335 4.250000 -9.085701
v -32.133335 6.000000 -9.085701
v -50.000000 5.999996 -9.650001
v -50.000000 -0.000004 -9.650001
v 40.400005 6.000003 -9.649997
v -40.666664 5.999997 -9.650001
v -40.666668 -0.000003 -9.650001
v -32.133335 -0.000002 -9.650000
v -32.133339 5.999998 -9.650000
v -40.666664 11.999997 -9.650001
v -40.666668 -0.000003 -9.650001
v -32.133335 -0.000002 -9.650000
v -32.133339 11.999998 -9.650000
v -40.666664 5.999997 -18.150002
v -40.666668 -0.000003 -18.150002
v -32.133335 -0.000002 -18.150000
v -32.133339 5.999998 -18.150000
v 40.400005 2.500000 -9.649997
v -32.133335 2.500000 -9.650000
v -50.000000 5.999996 -18.150002
v -50.000000 -0.000004 -18.150002
v 50.000000 6.000004 -18.149998
v 50.000000 0.000004 -18.149998
v 50.000000 5.761985 18.149998
v 50.000000 0.000004 18.149998
v -50.000000 5.761978 18.150002
v -50.000000 -0.000004 18.150002
v -50.000000 6.000000 18.150002
v -50.000000 0.000000 18.150002
v -50.000000 6.000000 -18.149998
v -50.000000 0.000000 -18.149998
v 50.000000 0.000000 18.150002
v 50.000000 6.000000 18.150002
v 50.000000 0.000000 -18.149998
v 50.000000 6.000000 -18.149998
v 47.300003 6.000003 1.649999
v 47.299999 0.000003 1.649999
v 32.900002 0.000002 1.650000
v 32.900005 6.000002 1.650000
v 29.699999 0.000002 1.649999
v 29.699999 6.000002 1.649999
v 32.900002 0.000002 1.650000
v 32.900005 12.000002 1.650000
v 29.699999 0.000002 1.649999
v 29.699999 12.000002 1.649999
v 15.300000 0.000001 1.650001
v 15.299998 6.000001 1.650001
v 12.099999 0.000001 1.650001
v 12.100004 6.000001 1.650001
v 15.300000 0.000001 1.650001
v 15.299998 12.000001 1.650001
v 12.099999 0.000001 1.650001
v 12.100005 12.000001 1.650001
v -2.300000 0.000000 1.650001
v -2.300000 6.000000 1.650001
v -5.500000 -0.000000 1.650002
v -5.500001 6.000000 1.650002
v -2.300000 0.000000 1.650001
v -2.300001 12.000000 1.650001
v -5.500000 -0.000000 1.650002
v -5.500001 12.000000 1.650002
v -19.899998 -0.000001 1.650002
v -19.900000 5.999999 1.650002
v -19.899998 -0.000001 1.650002
v -19.900000 11.999998 1.650002
v -22.600000 -0.000002 1.650002
v -22.600000 11.999998 1.650002
v 32.900002 0.000002 12.316666
v 32.900005 6.000002 12.316666
v 29.699997 0.000002 12.316666
v 29.699997 6.000002 12.316666
v 15.300002 0.000001 12.316668
v 15.300000 6.000001 12.316668
v 12.099999 0.000001 12.316668
v 12.100004 6.000001 12.316668
v -2.300000 0.000000 12.316668
v -2.300001 6.000000 12.316668
v -5.500000 -0.000000 12.316668
v -5.500001 6.000000 12.316668
v 15.300000 0.000002 12.316666
v 15.300000 6.000002 12.316666
v -2.300000 0.000001 12.316668
v -2.299995 6.000001 12.316668
v -19.900000 -0.000000 12.316668
v -19.900000 6.000000 12.316668
v 45.200001 6.000003 -9.649997
v 45.199997 0.000003 -9.649997
v 45.200001 6.000003 -18.183331
v 45.199997 0.000003 -18.183331
v 45.200001 6.000003 -8.633330
v 45.199997 0.000003 -8.633330
v 40.400002 6.000003 -9.649997
v 40.399994 0.000003 -9.649997
v 40.400002 6.000003 -18.183331
v 40.399994 0.000003 -18.183331
v 47.300003 6.000003 1.649999
v 47.299999 0.000003 1.649999
v 47.300003 6.000003 12.316666
v 47.299999 0.000003 12.316666
v 32.900005 6.000004 12.316666
v 32.900002 0.000003 12.316666
v -19.899998 -0.000001 1.650002
v -19.900000 5.999999 1.650002
v -19.900000 -0.000001 12.316669
v -19.900000 5.999999 12.316669
v -23.099998 -0.000001 1.650002
v -23.100000 5.999998 1.650002
v -23.100000 -0.000001 12.316668
v -23.100000 5.999998 12.316668
v -37.500000 -0.000001 12.316668
v -37.500000 5.999999 12.316668
v -37.500000 -0.000001 1.650001
v -37.500000 5.999999 1.650001
v -23.100000 -0.000001 1.650002
v -23.100000 5.999998 1.650002
v -19.899998 -0.000001 1.650002
v -19.900000 11.999998 1.650002
v -23.099998 -0.000001 1.650002
v -23.100000 11.999998 1.650002
v -37.500000 -0.000001 1.650001
v -37.500000 11.999998 1.650001
v -40.700001 -0.000001 1.650002
v -40.700001 11.999998 1.650002
v -40.700001 -0.000001 1.650002
v -40.700001 5.999999 1.650002
v -40.700001 -0.000001 18.150002
v -40.700001 5.999999 18.150002
v -40.700001 -0.000001 1.650002
v -40.700001 5.999999 1.650002
v -40.700001 -0.000001 0.050001
v -40.700001 5.999999 0.050001
v -40.700001 -0.000001 0.050001
v -40.700001 11.999998 0.050001
v -48.166668 -0.000001 0.050001
v -48.166668 11.999998 0.050001
v -48.166668 -0.000001 6.450001
v -48.166668 11.999998 6.450001
v -40.699997 -0.000001 6.450001
v -40.699997 11.999998 6.450001
v -40.700001 -0.000001 -6.349998
v -40.700001 5.999999 -6.349998
v -48.166668 -0.000001 -6.349998
v -48.166668 5.999999 -6.349998
v -48.166668 -0.000001 0.050002
v -48.166668 5.999999 0.050002
v -40.700001 -0.000001 0.050002
v -40.700001 5.999999 0.050002
v 50.000000 5.761985 18.149998
v -50.000000 5.761978 18.150002
v 50.000000 5.761985 18.149998
v -50.000000 5.761978 18.150002
v 50.000000 5.761985 18.149998
v -50.000000 5.761978 18.150002
v 50.000000 5.761985 18.149998
v -50.000000 5.761978 18.150002
v 49.999996 5.761985 -18.157017
v -50.000000 5.761978 -18.157013
v 40.400005 0.000003 -9.659998
v -32.133335 -0.000002 -9.660001
v 40.195881 2.524495 -9.658163
v -31.929211 2.524495 -9.658166
v 40.111332 2.534641 -9.085772
v -31.844660 2.534641 -9.085774
v 40.111332 2.684641 -9.085772
v -31.844660 2.684641 -9.085774
v 40.111332 2.684641 -7.735771
v -31.844660 2.684641 -7.735775
v 40.111332 2.784641 -7.735771
v -31.844660 2.784641 -7.735775
v 40.111332 2.784641 -7.675771
v -31.844660 2.784641 -7.675775
v 40.400005 4.250000 -7.679998
v -32.133335 4.250000 -7.680001
v 40.400005 4.207573 -7.677069
v -32.133335 4.207573 -7.677072
v 40.111332 4.215359 -7.975771
v -31.844660 4.215359 -7.975775
v 40.046452 6.000000 -7.977069
v -31.779781 6.000000 -7.977072
v 40.400005 2.500000 -9.659998
v -32.133335 2.500000 -9.660001
v 39.900005 6.000000 -9.649998
v 39.900005 6.000000 -9.079998
v 39.900005 4.250000 -9.079998
v 39.900005 4.250000 -7.729998
v 39.900005 4.250000 -7.729998
v 39.900005 4.250000 -7.669998
v 39.900005 4.250000 -9.085698
v 39.900005 6.000000 -9.085698
v -31.633335 6.000000 -9.650001
v -31.633335 6.000000 -9.080001
v -31.633335 4.250000 -9.080001
v -31.633335 4.250000 -7.730001
v -31.633335 4.250000 -7.730001
v -31.633335 4.250000 -7.670001
v -31.633335 4.250000 -9.085701
v -31.633335 6.000000 -9.085701
v -50.000000 5.999996 -9.660001
v -50.000000 -0.000004 -9.660001
v 40.400005 6.000003 -9.659997
v -41.020218 5.999997 -9.657071
v -41.020222 -0.000003 -9.657071
v -31.633335 -0.000002 -9.650000
v -31.779787 5.999998 -9.657071
v -40.351173 11.953449 -9.650001
v -40.351181 0.046545 -9.650001
v -31.863012 0.050473 -9.650000
v -31.863018 11.949522 -9.650000
v -41.166664 5.999997 -18.150002
v -41.166668 -0.000003 -18.150002
v -31.633335 -0.000002 -18.150000
v -31.633341 5.999998 -18.150000
v 40.400005 2.500000 -9.659997
v -31.686121 2.500000 -9.654472
v -50.000000 5.999996 -18.160000
v -50.000000 -0.000004 -18.160000
v 50.000000 6.000004 -18.159996
v 50.000000 0.000004 -18.159996
v 50.499897 5.761985 18.149799
v 50.000000 0.000004 18.159998
v -49.500099 5.761978 18.149803
v -49.999996 -0.000004 18.160002
v -50.500000 6.000000 18.150002
v -50.500000 0.000000 18.150002
v -50.500000 6.000000 -18.149998
v -50.500000 0.000000 -18.149998
v 50.500000 0.000000 18.150002
v 50.500000 6.000000 18.150002
v 50.500000 0.000000 -18.149998
v 50.500000 6.000000 -18.149998
v 47.300007 6.000004 1.659999
v 47.300003 0.000003 1.659999
v 33.253555 0.000002 1.657071
v 33.253559 6.000002 1.657071
v 29.346449 0.000002 1.657070
v 29.346449 6.000002 1.657070
v 32.871048 0.005282 1.640056
v 32.871052 11.994722 1.640056
v 29.673853 0.005284 1.640051
v 29.673853 11.994720 1.640051
v 15.653554 0.000001 1.657072
v 15.653553 6.000001 1.657072
v 11.746446 0.000001 1.657072
v 11.746451 6.000001 1.657072
v 15.286518 0.005288 1.640043
v 15.286516 11.994714 1.640043
v 12.089335 0.005289 1.640041
v 12.089341 11.994713 1.640041
v -1.946446 0.000000 1.657072
v -1.946447 6.000000 1.657072
v -5.853553 -0.000000 1.657073
v -5.853554 6.000000 1.657073
v -2.297972 0.005289 1.640039
v -2.297973 11.994711 1.640039
v -5.495152 0.005289 1.640041
v -5.495153 11.994711 1.640041
v -19.899998 -0.000001 1.660002
v -19.899998 5.999999 1.660002
v -19.882467 0.005284 1.640046
v -19.882469 11.994713 1.640046
v -22.580095 0.005283 1.640048
v -22.580095 11.994713 1.640048
v 33.400002 0.000002 12.316666
v 33.400005 6.000002 12.316666
v 29.346443 0.000002 12.309595
v 29.346443 6.000002 12.309595
v 15.800001 0.000001 12.316668
v 15.800000 6.000001 12.316668
v 11.746446 0.000001 12.309597
v 11.746451 6.000001 12.309597
v -1.800000 0.000000 12.316668
v -1.800001 6.000000 12.316668
v -5.853553 -0.000000 12.309597
v -5.853554 6.000000 12.309597
v 15.299997 0.000002 12.306665
v 15.299997 6.000002 12.306665
v -2.300000 0.000001 12.306667
v -2.299995 6.000001 12.306667
v -19.900000 -0.000000 12.306667
v -19.900000 6.000000 12.306667
v 44.700005 6.000003 -9.649997
v 44.699997 0.000003 -9.649997
v 44.700005 6.000003 -18.183331
v 44.699997 0.000003 -18.183331
v 44.700005 6.000003 -8.633330
v 44.699997 0.000003 -8.633330
v 39.900002 6.000003 -9.649997
v 39.899998 0.000003 -9.649997
v 39.900002 6.000003 -18.183331
v 39.899998 0.000003 -18.183331
v 46.800007 6.000003 1.649999
v 46.799999 0.000003 1.649999
v 46.946449 6.000004 12.309595
v 46.946445 0.000003 12.309595
v 32.900005 6.000004 12.306665
v 32.900002 0.000003 12.306665
v -19.400000 -0.000001 1.650002
v -19.400002 5.999999 1.650002
v -19.400000 -0.000001 12.316669
v -19.400002 5.999999 12.316669
v -23.599998 -0.000001 1.650002
v -23.600000 5.999998 1.650002
v -23.453554 -0.000001 12.309597
v -23.453554 5.999998 12.309597
v -37.146446 -0.000001 12.309597
v -37.146446 5.999999 12.309597
v -37.146446 -0.000001 1.657072
v -37.146446 5.999999 1.657072
v -23.100000 -0.000001 1.660002
v -23.100000 5.999998 1.660002
v -19.882467 0.005284 1.640046
v -19.882469 11.994713 1.640046
v -23.079653 0.005283 1.640049
v -23.079655 11.994713 1.640049
v -37.467014 0.005276 1.640061
v -37.467014 11.994720 1.640061
v -40.664215 0.005274 1.640066
v -40.664215 11.994723 1.640066
v -41.200001 -0.000001 1.650002
v -41.200001 5.999998 1.650002
v -41.200001 -0.000001 18.150002
v -41.200001 5.999998 18.150002
v -41.200001 -0.000001 1.650002
v -41.200001 5.999998 1.650002
v -41.200001 -0.000001 0.050001
v -41.200001 5.999998 0.050001
v -40.658409 0.006130 0.040089
v -40.658409 11.993867 0.040089
v -48.117512 0.006122 0.040102
v -48.117512 11.993876 0.040102
v -48.136864 0.003712 6.440039
v -48.136864 11.996285 6.440039
v -40.674801 0.003714 6.440033
v -40.674801 11.996284 6.440033
v -41.053551 -0.000001 -6.342928
v -41.053551 5.999998 -6.342928
v -47.813114 -0.000001 -6.342927
v -47.813114 5.999999 -6.342927
v -47.813114 -0.000001 0.042931
v -47.813114 5.999999 0.042931
v -40.700001 -0.000001 0.040002
v -40.700001 5.999999 0.040002
v 50.000000 5.761985 18.139997
v -50.000000 5.761978 18.140001
v 50.000000 5.761985 18.139997
v -50.000000 5.761978 18.140001
v 50.000000 5.761985 18.139997
v -50.000000 5.761978 18.140001
v 50.000000 5.804412 18.142927
v -50.000000 5.804404 18.142931
v 49.999996 5.821985 -18.157017
v -50.000000 5.821978 -18.157013
vn -0.0000 -0.0000 1.0000
vn -0.0000 -1.0000 -0.0000
vn -0.0000 1.0000 -0.0000
vn 1.0000 -0.0000 -0.0000
vn -1.0000 -0.0000 -0.0000
vn -0.0000 -0.0000 -1.0000
vn -0.0000 0.0007 -1.0000
vn -0.0000 0.9998 -0.0177
vn -0.0000 -0.0029 -1.0000
vn -0.0000 0.0689 0.9976
vn -0.0000 -0.9997 -0.0261
vn -0.0000 -0.0007 -1.0000
vn -0.0000 0.0747 -0.9972
vn -0.9947 -0.0725 -0.0730
vn -0.9910 -0.1338 -0.0000
vn -0.9898 -0.1427 -0.0000
vn -0.9871 -0.0181 0.1589
vn 0.9947 -0.0725 -0.0730
vn 0.9910 -0.1338 -0.0000
vn 0.9898 -0.1427 -0.0000
vn 0.9871 -0.0181 0.1589
vn 0.0003 -0.0000 -1.0000
vn 0.9999 0.0122 0.0081
vn -0.9999 -0.0000 0.0172
vn -0.0001 -0.0004 -1.0000
vn -0.0000 0.0018 1.0000
vn -0.0002 -0.0000 1.0000
vn 0.0002 -0.0000 1.0000
vn 0.9999 -0.0000 -0.0137
vn 0.0002 -0.0000 -1.0000
vn -0.9999 -0.0000 0.0137
vn -0.9997 -0.0000 -0.0229
vn -0.0004 -0.0000 -1.0000
vn -0.0000 -0.0689 0.9976
vn -0.0000 1.0000 0.0005
vn 0.0891 0.0040 -0.9960
vn -0.0891 0.0040 -0.9960
vn -0.0200 -0.0000 -0.9998
vn 0.0200 -0.0000 -0.9998
vn -0.0538 -0.0067 -0.9985
vn 0.0538 -0.0067 -0.9985
vn -0.2612 -0.9553 -0.1384
vn 0.2612 -0.9553 -0.1384
vn 0.1191 0.9929 -0.0000
vn -0.1191 0.9929 -0.0000
vn -0.0074 -0.0011 1.0000
vn 0.0117 0.0017 -0.9999
vn -0.0074 -0.0023 1.0000
vn 0.0074 0.0023 -1.0000
vn -0.0074 -0.0025 1.0000
vn 0.0074 0.0025 -1.0000
vn 0.0440 -0.9988 -0.0197
vn -0.0117 0.0017 -0.9999
vn 0.0074 -0.0011 1.0000
vn -0.0074 0.0023 -1.0000
vn 0.0074 -0.0023 1.0000
vn -0.0074 0.0025 -1.0000
vn 0.0074 -0.0025 1.0000
vn -0.0440 -0.9988 -0.0197
vn 0.0047 0.0009 1.0000
vn 0.0196 -0.0017 -0.9998
vn -0.0196 0.0017 0.9998
vn 1.0000 -0.0000 -0.0003
vn -1.0000 -0.0000 0.0003
vt 0.791666 0.178667
vt 1.000000 0.178667
vt 1.000000 0.904000
vt 0.791667 0.904000
vt 0.000000 0.000000
vt 1.000000 0.000000
vt 1.000000 0.093333
vt 0.000000 0.093333
vt 0.000000 0.178667
vt 0.000000 0.904000
vt 1.000000 1.000000
vt 0.000000 1.000000
vt 0.000000 0.027000
vt 1.000000 0.027000
vt 1.000000 0.171000
vt 0.000000 0.171000
vt 0.000000 0.203000
vt 1.000000 0.203000
vt 1.000000 0.347000
vt 0.000000 0.347000
vt 0.000000 0.379000
vt 1.000000 0.379000
vt 1.000000 0.523000
vt 0.000000 0.523000
vt 0.000000 0.555000
vt 1.000000 0.555000
vt 1.000000 0.699000
vt 0.000000 0.699000
vt 0.000000 0.952000
vt 1.000000 0.952000
s 0
f 12/5/7 10/6/7 9/7/7 11/8/7
f 12/5/8 11/8/8 13/8/8 14/5/8
f 14/5/7 13/8/7 15/8/7 16/5/7
f 16/5/8 15/8/8 17/8/8 18/5/8
f 18/5/7 17/8/7 19/8/7 20/5/7
f 20/5/8 19/8/8 21/8/8 22/5/8
f 22/5/7 21/8/7 23/8/7 24/5/7
f 24/5/7 23/8/7 25/8/7 26/5/7
f 26/5/9 25/8/9 27/8/9 28/5/9
f 28/5/7 27/8/7 29/8/7 30/5/7
f 11/8/7 12/5/7 32/5/7 31/8/7
f 13/8/10 11/8/10 33/8/10 34/8/10
f 17/8/10 15/8/10 35/8/10 36/8/10
f 21/8/10 19/8/10 37/8/10 38/8/10
f 29/8/10 27/8/10 39/8/10 40/8/10
f 12/5/11 14/5/11 42/5/11 41/5/11
f 16/5/11 18/5/11 44/5/11 43/5/11
f 20/5/11 22/5/11 46/5/11 45/5/11
f 28/5/11 30/5/11 48/5/11 47/5/11
f 49/9/7 50/10/7 53/11/7 52/12/7
f 54/6/11 65/5/11 55/13/11 63/13/11 62/6/11
f 52/12/10 53/11/10 61/11/10 60/12/10
f 55/13/7 65/5/7 64/8/7 51/14/7
f 66/9/7 67/10/7 69/15/7 68/16/7
f 70/9/12 71/10/12 73/15/12 72/16/12
f 74/9/10 75/10/10 77/15/10 76/16/10
f 78/9/11 79/10/11 81/15/11 80/16/11
f 82/17/12 83/18/12 84/19/12 85/20/12
f 87/21/12 86/22/12 92/23/12 93/24/12
f 95/25/12 94/26/12 100/27/12 101/28/12
f 103/29/12 102/30/12 108/31/12 109/32/12
f 102/30/10 103/29/10 125/29/10 124/30/10
f 101/28/11 100/27/11 122/27/11 123/28/11
f 94/26/10 95/25/10 121/25/10 120/26/10
f 93/24/11 92/23/11 118/23/11 119/24/11
f 86/22/10 87/21/10 117/21/10 116/22/10
f 85/20/11 84/19/11 114/19/11 115/20/11
f 124/30/7 125/29/7 131/29/7 130/30/7
f 120/26/7 121/25/7 129/25/7 128/26/7
f 116/22/7 117/21/7 127/21/7 126/22/7
f 132/33/10 133/34/10 135/34/10 134/33/10
f 133/34/10 132/33/10 136/33/10 137/34/10
f 138/33/10 139/34/10 141/34/10 140/33/10
f 143/18/10 142/17/10 144/17/10 145/18/10
f 145/18/7 144/17/7 146/17/7 147/18/7
f 149/32/11 148/31/11 150/31/11 151/32/11
f 152/31/10 153/32/10 155/32/10 154/31/10
f 154/31/7 155/32/7 157/32/7 156/31/7
f 156/31/11 157/32/11 159/32/11 158/31/11
f 158/31/12 159/32/12 161/32/12 160/31/12
f 171/32/10 173/32/10 172/31/10 170/31/10
f 174/31/10 176/31/10 177/32/10 175/32/10
f 177/32/10 176/31/10 186/31/10 187/32/10
f 187/32/12 186/31/12 188/31/12 189/32/12
f 189/32/11 188/31/11 190/31/11 191/32/11
f 191/32/7 190/31/7 192/31/7 193/32/7
f 70/9/7 72/16/7 195/16/7 194/9/7
f 194/9/7 195/16/7 197/16/7 196/9/7
f 196/9/7 197/16/7 199/16/7 198/9/7
f 198/9/7 199/16/7 201/16/7 200/9/7
f 200/9/8 201/16/8 203/16/8 202/9/8
f 207/5/13 206/8/13 204/7/13 205/6/13
f 207/5/14 209/5/14 208/8/14 206/8/14
f 209/5/12 211/5/12 210/8/12 208/8/12
f 211/5/9 213/5/9 212/8/9 210/8/9
f 213/5/12 215/5/12 214/8/12 212/8/12
f 215/5/9 217/5/9 216/8/9 214/8/9
f 217/5/15 219/5/15 218/8/15 216/8/15
f 219/5/16 221/5/16 220/8/16 218/8/16
f 221/5/17 223/5/17 222/8/17 220/8/17
f 223/5/18 225/5/18 224/8/18 222/8/18
f 206/8/19 226/8/19 227/5/19 207/5/19
f 208/8/20 229/8/20 228/8/20 206/8/20
f 212/8/21 231/8/21 230/8/21 210/8/21
f 216/8/22 233/8/22 232/8/22 214/8/22
f 224/8/23 235/8/23 234/8/23 222/8/23
f 207/5/24 236/5/24 237/5/24 209/5/24
f 211/5/25 238/5/25 239/5/25 213/5/25
f 215/5/26 240/5/26 241/5/26 217/5/26
f 223/5/27 242/5/27 243/5/27 225/5/27
f 244/9/28 247/12/28 248/11/28 245/10/28
f 249/6/29 257/6/29 258/13/29 250/13/29 260/5/29
f 247/12/30 255/12/30 256/11/30 248/11/30
f 250/13/31 246/14/31 259/8/31 260/5/31
f 261/9/12 263/16/12 264/15/12 262/10/12
f 265/9/32 267/16/32 268/15/32 266/10/32
f 269/9/11 271/16/11 272/15/11 270/10/11
f 273/9/10 275/16/10 276/15/10 274/10/10
f 277/17/33 280/20/33 279/19/33 278/18/33
f 282/21/7 288/24/7 287/23/7 281/22/7
f 290/25/7 296/28/7 295/27/7 289/26/7
f 298/29/34 304/32/34 303/31/34 297/30/34
f 297/30/11 319/30/11 320/29/11 298/29/11
f 296/28/35 318/28/35 317/27/35 295/27/35
f 289/26/11 315/26/11 316/25/11 290/25/11
f 288/24/35 314/24/35 313/23/35 287/23/35
f 281/22/11 311/22/11 312/21/11 282/21/11
f 280/20/35 310/20/35 309/19/35 279/19/35
f 319/30/36 325/30/36 326/29/36 320/29/36
f 315/26/36 323/26/36 324/25/36 316/25/36
f 311/22/36 321/22/36 322/21/36 312/21/36
f 327/33/11 329/33/11 330/34/11 328/34/11
f 328/34/11 332/34/11 331/33/11 327/33/11
f 333/33/11 335/33/11 336/34/11 334/34/11
f 338/18/37 340/18/37 339/17/37 337/17/37
f 340/18/36 342/18/36 341/17/36 339/17/36
f 344/32/10 346/32/10 345/31/10 343/31/10
f 347/31/37 349/31/37 350/32/37 348/32/37
f 349/31/12 351/31/12 352/32/12 350/32/12
f 351/31/10 353/31/10 354/32/10 352/32/10
f 353/31/33 355/31/33 356/32/33 354/32/33
f 366/32/11 365/31/11 367/31/11 368/32/11
f 369/31/11 370/32/11 372/32/11 371/31/11
f 372/32/38 382/32/38 381/31/38 371/31/38
f 382/32/7 384/32/7 383/31/7 381/31/7
f 384/32/10 386/32/10 385/31/10 383/31/10
f 386/32/39 388/32/39 387/31/39 385/31/39
f 265/9/9 389/9/9 390/16/9 267/16/9
f 389/9/7 391/9/7 392/16/7 390/16/7
f 391/9/7 393/9/7 394/16/7 392/16/7
f 393/9/40 395/9/40 396/16/40 394/16/40
f 395/9/41 397/9/41 398/16/41 396/16/41
f 9/7/8 10/6/8 205/6/8 204/7/8
f 11/8/42 9/7/42 204/7/42 206/8/42
f 10/6/43 12/5/43 207/5/43 205/6/43
f 14/5/44 16/5/44 211/5/44 209/5/44
f 15/8/45 13/8/45 208/8/45 210/8/45
f 18/5/44 20/5/44 215/5/44 213/5/44
f 19/8/45 17/8/45 212/8/45 214/8/45
f 22/5/46 24/5/46 219/5/46 217/5/46
f 23/8/47 21/8/47 216/8/47 218/8/47
f 24/5/10 26/5/10 221/5/10 219/5/10
f 25/8/11 23/8/11 218/8/11 220/8/11
f 26/5/48 28/5/48 223/5/48 221/5/48
f 27/8/49 25/8/49 220/8/49 222/8/49
f 30/5/9 29/8/9 224/8/9 225/5/9
f 31/8/8 32/5/8 227/5/8 226/8/8
f 11/8/50 31/8/50 226/8/50 206/8/50
f 32/5/51 12/5/51 207/5/51 227/5/51
f 34/8/9 33/8/9 228/8/9 229/8/9
f 13/8/52 34/8/52 229/8/52 208/8/52
f 33/8/53 11/8/53 206/8/53 228/8/53
f 36/8/9 35/8/9 230/8/9 231/8/9
f 17/8/54 36/8/54 231/8/54 212/8/54
f 35/8/55 15/8/55 210/8/55 230/8/55
f 38/8/9 37/8/9 232/8/9 233/8/9
f 21/8/56 38/8/56 233/8/56 216/8/56
f 37/8/57 19/8/57 214/8/57 232/8/57
f 40/8/12 39/8/12 234/8/12 235/8/12
f 29/8/9 40/8/9 235/8/9 224/8/9
f 39/8/58 27/8/58 222/8/58 234/8/58
f 41/5/9 42/5/9 237/5/9 236/5/9
f 12/5/59 41/5/59 236/5/59 207/5/59
f 42/5/60 14/5/60 209/5/60 237/5/60
f 43/5/9 44/5/9 239/5/9 238/5/9
f 16/5/61 43/5/61 238/5/61 211/5/61
f 44/5/62 18/5/62 213/5/62 239/5/62
f 45/5/9 46/5/9 241/5/9 240/5/9
f 20/5/63 45/5/63 240/5/63 215/5/63
f 46/5/64 22/5/64 217/5/64 241/5/64
f 47/5/12 48/5/12 243/5/12 242/5/12
f 28/5/65 47/5/65 242/5/65 223/5/65
f 48/5/9 30/5/9 225/5/9 243/5/9
f 49/9/9 52/12/9 247/12/9 244/9/9
f 50/10/11 49/9/11 244/9/11 245/10/11
f 51/14/10 64/8/10 259/8/10 246/14/10
f 53/11/8 50/10/8 245/10/8 248/11/8
f 55/13/9 51/14/9 246/14/9 250/13/9
f 60/12/12 61/11/12 256/11/12 255/12/12
f 62/6/12 63/13/12 258/13/12 257/6/12
f 54/6/8 62/6/8 257/6/8 249/6/8
f 63/13/9 55/13/9 250/13/9 258/13/9
f 52/12/9 60/12/9 255/12/9 247/12/9
f 61/11/8 53/11/8 248/11/8 256/11/8
f 65/5/66 54/6/66 249/6/66 260/5/66
f 64/8/8 65/5/8 260/5/8 259/8/8
f 66/9/9 68/16/9 263/16/9 261/9/9
f 67/10/11 66/9/11 261/9/11 262/10/11
f 69/15/8 67/10/8 262/10/8 264/15/8
f 68/16/10 69/15/10 264/15/10 263/16/10
f 71/10/67 70/9/67 265/9/67 266/10/67
f 73/15/8 71/10/8 266/10/8 268/15/8
f 72/16/68 73/15/68 268/15/68 267/16/68
f 74/9/9 76/16/9 271/16/9 269/9/9
f 75/10/7 74/9/7 269/9/7 270/10/7
f 77/15/8 75/10/8 270/10/8 272/15/8
f 76/16/12 77/15/12 272/15/12 271/16/12
f 78/9/8 80/16/8 275/16/8 273/9/8
f 79/10/7 78/9/7 273/9/7 274/10/7
f 81/15/9 79/10/9 274/10/9 276/15/9
f 80/16/12 81/15/12 276/15/12 275/16/12
f 82/17/9 85/20/9 280/20/9 277/17/9
f 83/18/69 82/17/69 277/17/69 278/18/69
f 84/19/8 83/18/8 278/18/8 279/19/8
f 87/21/9 93/24/9 288/24/9 282/21/9
f 92/23/8 86/22/8 281/22/8 287/23/8
f 95/25/9 101/28/9 296/28/9 290/25/9
f 100/27/8 94/26/8 289/26/8 295/27/8
f 103/29/9 109/32/9 304/32/9 298/29/9
f 108/31/8 102/30/8 297/30/8 303/31/8
f 109/32/70 108/31/70 303/31/70 304/32/70
f 115/20/7 114/19/7 309/19/7 310/20/7
f 119/24/7 118/23/7 313/23/7 314/24/7
f 123/28/7 122/27/7 317/27/7 318/28/7
f 102/30/8 124/30/8 319/30/8 297/30/8
f 125/29/9 103/29/9 298/29/9 320/29/9
f 101/28/9 123/28/9 318/28/9 296/28/9
f 122/27/8 100/27/8 295/27/8 317/27/8
f 94/26/8 120/26/8 315/26/8 289/26/8
f 121/25/9 95/25/9 290/25/9 316/25/9
f 93/24/9 119/24/9 314/24/9 288/24/9
f 118/23/8 92/23/8 287/23/8 313/23/8
f 86/22/8 116/22/8 311/22/8 281/22/8
f 117/21/9 87/21/9 282/21/9 312/21/9
f 85/20/9 115/20/9 310/20/9 280/20/9
f 114/19/8 84/19/8 279/19/8 309/19/8
f 126/22/70 127/21/70 322/21/70 321/22/70
f 128/26/11 129/25/11 324/25/11 323/26/11
f 130/30/70 131/29/70 326/29/70 325/30/70
f 124/30/8 130/30/8 325/30/8 319/30/8
f 131/29/9 125/29/9 320/29/9 326/29/9
f 120/26/8 128/26/8 323/26/8 315/26/8
f 129/25/9 121/25/9 316/25/9 324/25/9
f 116/22/8 126/22/8 321/22/8 311/22/8
f 127/21/9 117/21/9 312/21/9 322/21/9
f 134/33/12 135/34/12 330/34/12 329/33/12
f 132/33/9 134/33/9 329/33/9 327/33/9
f 135/34/8 133/34/8 328/34/8 330/34/8
f 137/34/7 136/33/7 331/33/7 332/34/7
f 133/34/8 137/34/8 332/34/8 328/34/8
f 136/33/9 132/33/9 327/33/9 331/33/9
f 139/34/7 138/33/7 333/33/7 334/34/7
f 140/33/12 141/34/12 336/34/12 335/33/12
f 138/33/9 140/33/9 335/33/9 333/33/9
f 141/34/8 139/34/8 334/34/8 336/34/8
f 142/17/12 143/18/12 338/18/12 337/17/12
f 143/18/8 145/18/8 340/18/8 338/18/8
f 144/17/9 142/17/9 337/17/9 339/17/9
f 147/18/11 146/17/11 341/17/11 342/18/11
f 145/18/8 147/18/8 342/18/8 340/18/8
f 146/17/9 144/17/9 339/17/9 341/17/9
f 148/31/12 149/32/12 344/32/12 343/31/12
f 151/32/7 150/31/7 345/31/7 346/32/7
f 149/32/9 151/32/9 346/32/9 344/32/9
f 150/31/8 148/31/8 343/31/8 345/31/8
f 153/32/12 152/31/12 347/31/12 348/32/12
f 152/31/8 154/31/8 349/31/8 347/31/8
f 155/32/9 153/32/9 348/32/9 350/32/9
f 154/31/8 156/31/8 351/31/8 349/31/8
f 157/32/9 155/32/9 350/32/9 352/32/9
f 156/31/8 158/31/8 353/31/8 351/31/8
f 159/32/9 157/32/9 352/32/9 354/32/9
f 160/31/10 161/32/10 356/32/10 355/31/10
f 158/31/8 160/31/8 355/31/8 353/31/8
f 161/32/9 159/32/9 354/32/9 356/32/9
f 171/32/12 170/31/12 365/31/12 366/32/12
f 172/31/7 173/32/7 368/32/7 367/31/7
f 173/32/9 171/32/9 366/32/9 368/32/9
f 170/31/8 172/31/8 367/31/8 365/31/8
f 174/31/7 175/32/7 370/32/7 369/31/7
f 176/31/8 174/31/8 369/31/8 371/31/8
f 175/32/9 177/32/9 372/32/9 370/32/9
f 177/32/9 187/32/9 382/32/9 372/32/9
f 186/31/8 176/31/8 371/31/8 381/31/8
f 187/32/9 189/32/9 384/32/9 382/32/9
f 188/31/8 186/31/8 381/31/8 383/31/8
f 189/32/9 191/32/9 386/32/9 384/32/9
f 190/31/8 188/31/8 383/31/8 385/31/8
f 193/32/10 192/31/10 387/31/10 388/32/10
f 191/32/9 193/32/9 388/32/9 386/32/9
f 192/31/8 190/31/8 385/31/8 387/31/8
f 70/9/8 194/9/8 389/9/8 265/9/8
f 195/16/9 72/16/9 267/16/9 390/16/9
f 194/9/7 196/9/7 391/9/7 389/9/7
f 197/16/7 195/16/7 390/16/7 392/16/7
f 196/9/7 198/9/7 393/9/7 391/9/7
f 199/16/7 197/16/7 392/16/7 394/16/7
f 198/9/11 200/9/11 395/9/11 393/9/11
f 201/16/10 199/16/10 394/16/10 396/16/10
f 202/9/12 203/16/12 398/16/12 397/9/12
f 200/9/10 202/9/10 397/9/10 395/9/10
f 203/16/11 201/16/11 396/16/11 398/16/11

BIN
assets/sounds/fart.wav Normal file

Binary file not shown.

BIN
assets/sounds/jazz.wav Normal file

Binary file not shown.

BIN
assets/sounds/step.wav Normal file

Binary file not shown.

View File

Before

Width:  |  Height:  |  Size: 298 KiB

After

Width:  |  Height:  |  Size: 298 KiB

View File

Before

Width:  |  Height:  |  Size: 6.1 KiB

After

Width:  |  Height:  |  Size: 6.1 KiB

View File

Before

Width:  |  Height:  |  Size: 218 KiB

After

Width:  |  Height:  |  Size: 218 KiB

View File

Before

Width:  |  Height:  |  Size: 78 KiB

After

Width:  |  Height:  |  Size: 78 KiB

View File

@@ -1,286 +1,9 @@
#pragma once #pragma once
/** #include <sp/common/DataBuffer.h>
* \file DataBuffer.h
* \brief File containing the blitz::DataBuffer class
*/
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
namespace blitz { namespace blitz {
/** using DataBuffer = sp::DataBuffer;
* \class DataBuffer
* \brief Class used to manipulate memory
*/
class DataBuffer {
private:
typedef std::vector<std::uint8_t> Data;
Data m_Buffer;
std::size_t m_ReadOffset;
public:
typedef Data::iterator iterator;
typedef Data::const_iterator const_iterator;
typedef Data::reference reference;
typedef Data::const_reference const_reference;
typedef Data::difference_type difference_type;
DataBuffer();
DataBuffer(const DataBuffer& other);
DataBuffer(const DataBuffer& other, difference_type offset);
DataBuffer(DataBuffer&& other);
DataBuffer(const std::string& str);
DataBuffer& operator=(const DataBuffer& other);
DataBuffer& operator=(DataBuffer&& other);
/**
* \brief Append data to the buffer
*/
template <typename T>
void Append(const T& data) {
std::size_t size = sizeof(data);
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + size);
std::memcpy(&m_Buffer[end_pos], &data, size);
}
/**
* \brief Append data to the buffer
*/
template <typename T>
DataBuffer& operator<<(const T& data) {
Append(data);
return *this;
}
/**
* \brief Append a string to the buffer
* \warning Don't use it for binary data !
* \param str The string to append
*/
DataBuffer& operator<<(const std::string& str) {
std::size_t strlen = str.length() + 1; // including null character
Resize(GetSize() + strlen);
std::memcpy(m_Buffer.data() + GetSize() - strlen, str.data(), strlen);
return *this;
}
/**
* \brief Append data to the buffer from another const buffer
* \param data The buffer to append
*/
DataBuffer& operator<<(const DataBuffer& data) {
m_Buffer.insert(m_Buffer.end(), data.begin(), data.end());
return *this;
}
/**
* \brief Read some data from the buffer and assign to desired variable
*/
template <typename T>
DataBuffer& operator>>(T& data) {
assert(m_ReadOffset + sizeof(T) <= GetSize());
data = *(reinterpret_cast<T*>(&m_Buffer[m_ReadOffset]));
m_ReadOffset += sizeof(T);
return *this;
}
/**
* \brief Read some data from the buffer and assign to the new buffer
* \param data The buffer to assign
*/
DataBuffer& operator>>(DataBuffer& data) {
data.Resize(GetSize() - m_ReadOffset);
std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), m_Buffer.end(), data.begin());
m_ReadOffset = m_Buffer.size();
return *this;
}
/**
* \brief Read a string from the buffer
* \param str The string to assign in the new buffer
* \warning Don't use it for binary data !
*/
DataBuffer& operator>>(std::string& str) {
std::size_t stringSize =
strlen(reinterpret_cast<const char*>(m_Buffer.data()) + m_ReadOffset) + 1; // including null character
str.resize(stringSize);
std::copy(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset),
m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset + stringSize), str.begin());
m_ReadOffset += stringSize;
return *this;
}
/**
* \brief Write some data to the buffer
* \param buffer The buffer to write
* \param amount The amount of data to write
*/
void WriteSome(const char* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
/**
* \brief Write some data to the buffer
* \param buffer The buffer to write
* \param amount The amount of data to write
*/
void WriteSome(const std::uint8_t* buffer, std::size_t amount) {
std::size_t end_pos = m_Buffer.size();
m_Buffer.resize(m_Buffer.size() + amount);
std::memcpy(m_Buffer.data() + end_pos, buffer, amount);
}
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(char* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount;
}
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(std::uint8_t* buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer);
m_ReadOffset += amount;
}
/**
* \brief Read some data from the buffer
* \param buffer The buffer to Read
* \param amount The amount of data from the buffer
*/
void ReadSome(DataBuffer& buffer, std::size_t amount) {
assert(m_ReadOffset + amount <= GetSize());
buffer.Resize(amount);
std::copy_n(m_Buffer.begin() + static_cast<difference_type>(m_ReadOffset), amount, buffer.begin());
m_ReadOffset += amount;
}
/**
* \brief Resize the buffer
* \param size The new size of the buffer
*/
void Resize(std::size_t size) {
m_Buffer.resize(size);
}
/**
* \brief Reserve some space in the buffer
* \param amount The amount of space to reserve
*/
void Reserve(std::size_t amount) {
m_Buffer.reserve(amount);
}
/**
* \brief Clear the buffer
*/
void Clear() {
m_Buffer.clear();
m_ReadOffset = 0;
}
/**
* \brief When the buffer has been read entirely
*/
bool IsFinished() const {
return m_ReadOffset >= m_Buffer.size();
}
/**
* \brief Get the buffer data
*/
std::uint8_t* data() {
return m_Buffer.data();
}
/**
* \brief Get the buffer data
*/
const std::uint8_t* data() const {
return m_Buffer.data();
}
/**
* \brief Get the read offset
*/
std::size_t GetReadOffset() const {
return m_ReadOffset;
}
/**
* \brief Set the read offset
* \param pos The new read offset
*/
void SetReadOffset(std::size_t pos);
/**
* \brief Get the size of the buffer
*/
std::size_t GetSize() const;
/**
* \brief Get the remaining size of the buffer
*/
std::size_t GetRemaining() const;
/**
* \brief Read a file into the buffer
* \param fileName The name of the file to read
*/
bool ReadFile(const std::string& fileName);
/**
* \brief Write a file into the buffer
* \param fileName The name of the file to write to
*/
bool WriteFile(const std::string& fileName) const;
/**
* \brief Allocate the buffer on the heap
* \warning Don't forget to free the data !
*/
std::uint8_t* HeapAllocatedData() const {
std::uint8_t* newBuffer = new std::uint8_t[GetSize()];
std::memcpy(newBuffer, data(), GetSize());
return newBuffer;
}
/**
* \brief Operator == to compare two DataBuffer
*/
bool operator==(const DataBuffer& other) const {
return m_Buffer == other.m_Buffer;
}
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
};
/**
* \brief Operator << to write a DataBuffer to an ostream
*/
std::ostream& operator<<(std::ostream& os, const DataBuffer& buffer);
} // namespace blitz } // namespace blitz

View File

@@ -6,6 +6,7 @@
*/ */
#include <cstdint> #include <cstdint>
#include <sp/protocol/MessagePrinter.h>
namespace blitz { namespace blitz {
namespace game { namespace game {
@@ -30,3 +31,10 @@ enum GameState : std::uint8_t {
} // namespace game } // namespace game
} // namespace blitz } // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::game::GameState& a_State) {
return PrintData(static_cast<unsigned>(a_State));
}
} // namespace sp

View File

@@ -1,25 +0,0 @@
#pragma once
/**
* \file NonCopyable.h
* \brief File containing the blitz::NonCopyable class
*/
namespace blitz {
/**
* \class NonCopyable
* \brief Class used to make a class non copyable
* \note Inherit from this class privately to make a class non copyable
*/
class NonCopyable {
public:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
protected:
NonCopyable() {}
~NonCopyable() {}
};
} // namespace blitz

View File

@@ -1,58 +0,0 @@
#pragma once
/**
* \file VarInt.h
* \brief File containing the blitz::VarInt class
*/
#include <cstddef>
#include <cstdint>
namespace blitz {
class DataBuffer;
/**
* \class VarInt
* \brief Variable-length format such that smaller numbers use fewer bytes.
*/
class VarInt {
private:
std::uint64_t m_Value;
public:
VarInt() : m_Value(0) {}
/**
* \brief Construct a variable integer from a value
* \param value The value of the variable integer
*/
VarInt(std::uint64_t value) : m_Value(value) {}
/**
* \brief Get the value of the variable integer
*/
std::uint64_t GetValue() const {
return m_Value;
}
/**
* \brief Get the length of the serialized variable integer
*/
std::size_t GetSerializedLength() const;
/**
* \brief Serialize the variable integer
* \param out The buffer to write the serialized variable integer to
* \param var The variable integer to serialize
*/
friend DataBuffer& operator<<(DataBuffer& out, const VarInt& var);
/**
* \brief Deserialize the variable integer
* \param in The buffer to read the serialized variable integer from
* \param var The variable integer to deserialize
*/
friend DataBuffer& operator>>(DataBuffer& in, VarInt& var);
};
} // namespace blitz

View File

@@ -10,6 +10,7 @@
#include "blitz/misc/ObjectNotifier.h" #include "blitz/misc/ObjectNotifier.h"
#include "blitz/misc/Time.h" #include "blitz/misc/Time.h"
#include <map> #include <map>
#include <sp/protocol/MessagePrinter.h>
namespace blitz { namespace blitz {
namespace game { namespace game {
@@ -48,7 +49,7 @@ class Game : public utils::ObjectNotifier<GameListener> {
public: public:
/** \brief Default constructor */ /** \brief Default constructor */
Game() : m_GameState(gsNone) {} Game() : m_GameState(gsNone), m_Config({}) {}
/** /**
* \brief Update the game with a delta time * \brief Update the game with a delta time
@@ -140,3 +141,10 @@ class Game : public utils::ObjectNotifier<GameListener> {
} // namespace game } // namespace game
} // namespace blitz } // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::game::GameConfig& a_Config) {
return "{Gravity=" + PrintData(a_Config.Gravity) + ", FiringRate=" + PrintData(a_Config.FiringRate) + "}";
}
} // namespace sp

View File

@@ -1,43 +1,18 @@
#pragma once #pragma once
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h"
#include <vector>
namespace blitz { namespace blitz {
namespace protocol {
struct ColoredPart;
typedef std::vector<ColoredPart> ColoredText;
} // namespace protocol
namespace game { namespace game {
class PlayerInputListener {
public:
virtual void OnLocalPlayerJump() {}
virtual void OnLocalPlayerShoot(const Vec3f& position, float yaw, float pitch) {}
};
class GameListener { class GameListener {
public: public:
virtual void OnPlayerJoin(game::PlayerID player) {} virtual void OnPlayerJoin(game::PlayerID player) {}
virtual void OnPlayerLeave(game::PlayerID player) {} virtual void OnPlayerLeave(game::PlayerID player) {}
virtual void OnPlayerDeath(game::PlayerID player) {}
virtual void OnGameStateUpdate(game::GameState newState) {} virtual void OnGameStateUpdate(game::GameState newState) {}
}; };
class ClientListener {
public:
virtual void OnTextChatReceived(const protocol::ColoredText& text) {}
virtual void OnSpectatorChange(game::PlayerID player) {}
virtual void OnPlayerShoot(PlayerID player, const Vec3f& position, float yaw, float pitch) {}
virtual void OnClientPlayerJoin() {}
virtual void OnGameConfigUpdate() {}
virtual void OnGameJoin() {}
virtual void OnGameLeave() {}
};
} // namespace game } // namespace game
} // namespace blitz } // namespace blitz

View File

@@ -8,6 +8,7 @@
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include <cstdint> #include <cstdint>
#include <sp/protocol/MessagePrinter.h>
#include <string> #include <string>
namespace blitz { namespace blitz {
@@ -222,3 +223,12 @@ class Player {
} // namespace game } // namespace game
} // namespace blitz } // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::game::PlayerStats& a_Stats) {
return "{m_Deaths=" + PrintData(a_Stats.m_Deaths) + ", m_Kills=" + PrintData(a_Stats.m_Kills) +
", m_ShootCount=" + PrintData(a_Stats.m_ShootCount) + ", m_ShootSuccessCount=" + PrintData(a_Stats.m_ShootSuccessCount) +
"}";
}
} // namespace sp

View File

@@ -1,6 +1,7 @@
#pragma once #pragma once
namespace blitz { namespace blitz {
namespace maths {
class EMASmoother { class EMASmoother {
private: private:
@@ -16,4 +17,5 @@ class EMASmoother {
void SetSmoothingTime(float t); void SetSmoothingTime(float t);
}; };
} // namespace maths
} // namespace blitz } // namespace blitz

View File

@@ -8,6 +8,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <cstddef> #include <cstddef>
#include <sp/protocol/MessagePrinter.h>
namespace blitz { namespace blitz {
@@ -325,3 +326,14 @@ bool operator==(const Mat4<T>& mat, const Mat4<T>& other) {
mat.w3 == other.w3; mat.w3 == other.w3;
} }
} // namespace blitz } // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::Vec3f& a_Vec) {
return "{" + PrintData(a_Vec.x) + ", " + PrintData(a_Vec.y) + ", " + PrintData(a_Vec.z) + "}";
}
template <>
inline std::string PrintData(const blitz::Vec4f& a_Vec) {
return "{" + PrintData(a_Vec.x) + ", " + PrintData(a_Vec.y) + ", " + PrintData(a_Vec.z) + ", " + PrintData(a_Vec.w) + "}";
}
} // namespace sp

View File

@@ -43,6 +43,8 @@ class ObjectNotifier {
/** /**
* \brief Notify listeners that were bound * \brief Notify listeners that were bound
* \param function the function to call
* \param args the parameters of the function to call
*/ */
template <typename Func, typename... Args> template <typename Func, typename... Args>
void NotifyListeners(Func function, Args... args) const { void NotifyListeners(Func function, Args... args) const {

View File

@@ -8,70 +8,59 @@
#include "TCPSocket.h" #include "TCPSocket.h"
#include "blitz/protocol/PacketDispatcher.h" #include "blitz/protocol/PacketDispatcher.h"
#include "blitz/protocol/PacketHandler.h" #include "blitz/protocol/PacketHandler.h"
#include "blitz/protocol/PacketFactory.h"
namespace blitz { namespace blitz {
namespace network { namespace network {
using TCPStream = sp::io::Stream<sp::io::TcpTag, protocol::PacketDispatcher, protocol::PacketFactory, sp::option::ZlibCompress>;
/** /**
* \class Connexion * \class Connexion
* \brief Represents a network connexion * \brief Represents a network connexion
*/ */
class Connexion : public protocol::PacketHandler, private NonCopyable { class Connexion : public protocol::PacketHandler, public TCPStream {
protected:
protocol::PacketDispatcher m_Dispatcher;
private:
TCPSocket m_Socket;
public: public:
/** /**
* \brief Constructs with an empty socket * \brief Constructs with an empty socket
*/ */
Connexion(protocol::PacketDispatcher* dispatcher); Connexion() {}
/** /**
* \brief Constructs with an already connected socket * \brief Constructs with an already connected socket
*/ */
Connexion(protocol::PacketDispatcher* dispatcher, TCPSocket& socket); Connexion(TCPSocket&& socket);
/** /**
* \brief Move constructor * \brief Move constructor
*/ */
Connexion(Connexion&& move); Connexion(Connexion&& move);
/**
* \brief Default destructor
*/
virtual ~Connexion();
/**
* \brief Reads socket and process a Packet, if any
*/
virtual bool UpdateSocket();
/** /**
* \brief Closes the connexion * \brief Closes the connexion
*/ */
void CloseConnection(); void CloseConnection();
/**
* \brief Returns the TCPSocket::Status of the internal socket
*/
TCPSocket::Status GetSocketStatus() const {
return m_Interface.GetStatus();
}
virtual bool UpdateSocket();
/** /**
* \brief Tries to connect the socket at the specified address and port * \brief Tries to connect the socket at the specified address and port
* \return Whether this action was succesfull * \return Whether this action was succesfull
*/ */
bool Connect(const std::string& address, std::uint16_t port); bool Connect(const std::string& address, std::uint16_t port);
/**
* \brief Returns the TCPSocket::Status of the internal socket
*/
TCPSocket::Status GetSocketStatus() const {
return m_Socket.GetStatus();
}
/** /**
* \brief Sends the protocol::Packet over the network to the remote * \brief Sends the protocol::Packet over the network to the remote
* \param packet The protocol::Packet to send * \param packet The protocol::Packet to send
*/ */
void SendPacket(const protocol::Packet* packet); void SendPacket(const protocol::Packet& packet);
}; };
} // namespace network } // namespace network

View File

@@ -21,7 +21,7 @@ namespace network {
* \note This class is meant to be created only once in your program. \n * \note This class is meant to be created only once in your program. \n
* The easiest thing to do is to create an instance of this class at the top of your **main.cpp**. * The easiest thing to do is to create an instance of this class at the top of your **main.cpp**.
*/ */
class NetworkInitializer : private NonCopyable { class NetworkInitializer : private sp::NonCopyable {
public: public:
/** /**
* \brief Creates the networking context * \brief Creates the networking context

View File

@@ -10,76 +10,7 @@
namespace blitz { namespace blitz {
namespace network { namespace network {
/** using TCPListener = sp::io::TcpListener;
* \class TCPListener
* \brief Cross platform abstraction of a TCP socket server
*/
class TCPListener : private NonCopyable {
private:
SocketHandle m_Handle;
std::uint16_t m_Port;
int m_MaxConnections;
public:
/**
* \brief Default constructor
*/
TCPListener();
/**
* \brief Default destructor
*/
~TCPListener();
/**
* \brief Starts listening for guests to connect
* \param port The port to listen to
* \param maxConnexions The maximum amount of connexion that can happen at the same time. \n
* Every other guests will be kicked if this amount is reached.
* \return Whether this action was succesfull
*/
bool Listen(std::uint16_t port, int maxConnexions);
/**
* \brief Tries to accept an incoming request to connect
* \param newSocket the empty socket to put the result to
* \return true if a new connexion was accepted
*/
bool Accept(TCPSocket& newSocket);
/**
* \brief Destroys the socket
*/
void Destroy();
/**
* \brief Closes transmissions
* \return true if this action was succesfull
*/
bool Close();
/**
* \brief Allows to set the socket in non blocking/blocking mode
* \param block If set to true, every call to Read will wait until the socket receives something
* \return true if the operation was successful
*/
bool SetBlocking(bool blocking);
/**
* \brief Getter of the m_Port member
* \return The port which the socket listen to
*/
std::uint16_t GetListeningPort() const {
return m_Port;
}
/**
* \brief Getter of the m_MaxConnections member
* \return The maximum amount of connexions that can happen at the same time.
*/
int GetMaximumConnections() const {
return m_MaxConnections;
}
};
} // namespace network } // namespace network
} // namespace blitz } // namespace blitz

View File

@@ -1,26 +1,6 @@
#pragma once #pragma once
#include "blitz/common/DataBuffer.h" #include <sp/extensions/Tcp.h>
#include "blitz/common/NonCopyable.h"
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#else
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define closesocket close
#endif
#ifndef INVALID_SOCKET
#define INVALID_SOCKET -1
#endif
/** /**
* \file TCPSocket.h * \file TCPSocket.h
@@ -30,138 +10,7 @@
namespace blitz { namespace blitz {
namespace network { namespace network {
/** using TCPSocket = sp::io::TcpSocket;
* \typedef SocketHandle
* \brief Represents a native socket
*/
typedef int SocketHandle;
/**
* \class TCPSocket
* \brief Cross platform abstraction of a TCP socket
*/
class TCPSocket : private NonCopyable {
public:
/**
* \enum Status
* \brief Describes the state of a socket
*/
enum class Status {
/** The socket is connected */
Connected,
/** The socket is not connected */
Disconnected,
/** Something bad happened */
Error,
};
private:
bool m_Blocking;
Status m_Status;
SocketHandle m_Handle;
std::uint16_t m_Port;
sockaddr m_RemoteAddr;
public:
/**
* \brief Default constructor
*/
TCPSocket();
/**
* \brief Default destructor
*/
virtual ~TCPSocket();
/**
* \brief Move constructor
*/
TCPSocket(TCPSocket&&);
/**
* \brief Sets the TCPSocket::Status of the socket
* \param status The TCPSocket::Status to apply
*/
void SetStatus(Status status);
/**
* \brief Allows to set the socket in non blocking/blocking mode
* \param block If set to true, every call to Read will wait until the socket receives something
* \return true if the operation was successful
*/
bool SetBlocking(bool block);
/**
* \brief Checks if the socket is in blocking mode
* \return Whether the socket is in blocking mode
*/
bool IsBlocking() const;
/**
* \brief Getter of the m_Status member
* \return The TCPSocket::Status of this socket
*/
Status GetStatus() const;
/**
* \brief Tries to connect to the host at the given port
* \param host The host to connect to. Can be a hostname or an ip address.
* \param port The port to connect to.
* \return Whether this action was successfull
*/
bool Connect(const std::string& host, std::uint16_t port);
/**
* \brief Disconnects the socket from the remote
* \note Does nothing if the socket is not connected. \n
* This function is also called by the destructor.
*/
void Disconnect();
/**
* \brief Sends some data
* \param buffer The data to send
* \note Simply returns 0 if the socket is not connected
* \return The amount of data sent. It should be the size of the buffer in theory.
*/
std::size_t Send(DataBuffer& buffer);
/**
* \brief Sends some data
* \param data The data to send
* \param size The amount of data to send
* \note Simply returns 0 if the socket is not connected
* \return The amount of data sent. It should be equal to the size param in theory
*/
std::size_t Send(const std::uint8_t* data, std::size_t size);
/**
* \brief Reads some data
* \param amount The amount of data to read
* \return The buffer containing the data that have been received
* \note If no data is available, an empty DataBuffer is returned
*/
DataBuffer Receive(std::size_t amount);
/**
* \brief Reads some data
* \param buffer The buffer to write into
* \param amount The amount of data to read
* \return The amount of data read
* \note If no data is available, 0 is returned
*/
std::size_t Receive(DataBuffer& buffer, std::size_t amount);
friend class TCPListener;
};
/**
* \brief Compress the data and send it to the socket
* \param data The data to send
* \param socket The socket to send to
*/
void SendPacket(const DataBuffer& data, network::TCPSocket& socket);
} // namespace network } // namespace network
} // namespace blitz } // namespace blitz

View File

@@ -0,0 +1,74 @@
#pragma once
#include "blitz/common/DataBuffer.h"
#include "blitz/maths/Vector.h"
#include <string>
#include <vector>
namespace blitz {
namespace protocol {
/**
* \struct ColoredPart
* \brief Represents a part of a chat message with a specific color.
*/
struct ColoredPart {
/**
* \brief The color of the part.
*/
Vec4f m_Color;
/**
* \brief The text of the part.
*/
std::string m_Text;
};
using ColoredText = std::vector<ColoredPart>;
const static Vec3uc AQUA = {0, 255, 255};
const static Vec3uc BLUE = {0, 0, 255};
const static Vec3uc GREEN = {0, 255, 0};
const static Vec3uc PURPLE = {255, 0, 255};
const static Vec3uc RED = {255, 0, 0};
const static Vec3uc WHITE = {255, 255, 255};
const static Vec3uc YELLOW = {255, 255, 0};
/**
* \brief Get the text color.
*/
std::string GetTextColor(Vec3uc color);
/**
* \brief Colorize a text.
*/
ColoredText ColorizeText(const std::string& text);
/**
* \brief Get the colored text string.
*/
std::string GetColoredTextString(const ColoredText& text);
/**
* \brief Serialize the colored part
* \param out The buffer to write the serialized colored part to
* \param var The colored part to serialize
*/
DataBuffer& operator<<(DataBuffer& out, const ColoredPart& var);
/**
* \brief Deserialize the colored part
* \param in The buffer to read the serialized colored part from
* \param var The colored part to deserialize
*/
DataBuffer& operator>>(DataBuffer& in, ColoredPart& var);
} // namespace protocol
} // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::protocol::ColoredPart& a_Part) {
return "{m_Color=" + PrintData(a_Part.m_Color) + ", m_Text=" + PrintData(a_Part.m_Text) + "}";
}
} // namespace sp

View File

@@ -5,54 +5,17 @@
* \brief File containing the blitz::protocol::PacketDispatcher class * \brief File containing the blitz::protocol::PacketDispatcher class
*/ */
#include "blitz/common/NonCopyable.h" #include "blitz/protocol/Packets.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacketDispatcher.h>
#include <map>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
class PacketHandler;
/** /**
* \class PacketDispatcher * \class PacketDispatcher
* \brief Class used to dispatch packets * \brief Class used to dispatch packets
*/ */
class PacketDispatcher : private NonCopyable { using PacketDispatcher = sp::PacketDispatcher;
private:
std::map<PacketType, std::vector<PacketHandler*>> m_Handlers;
public:
/**
* \brief Constructor
*/
PacketDispatcher() {}
/**
* \brief Dispatch a packet
* \param packet The packet to dispatch
*/
void Dispatch(const Packet* packet);
/**
* \brief Register a packet handler
* \param type The packet type
* \param handler The packet handler
*/
void RegisterHandler(PacketType type, PacketHandler* handler);
/**
* \brief Unregister a packet handler
* \param type The packet type
* \param handler The packet handler
*/
void UnregisterHandler(PacketType type, PacketHandler* handler);
/**
* \brief Unregister a packet handler
* \param handler The packet handler
*/
void UnregisterHandler(PacketHandler* handler);
};
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -4,19 +4,13 @@
* \file PacketFactory.h * \file PacketFactory.h
*/ */
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Packets.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
namespace PacketFactory {
/** using PacketPtr = std::unique_ptr<Packet>;
* \brief Creates a packet from a buffer. using PacketFactory = sp::PacketFactory;
* \param buffer The buffer containing the packet data.
* \return The created packet.
*/
const Packet* CreatePacket(PacketType type, DataBuffer& buffer);
} // namespace PacketFactory
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -5,54 +5,12 @@
* \brief File containing the blitz::protocol::PacketHandler class * \brief File containing the blitz::protocol::PacketHandler class
*/ */
#include "blitz/protocol/PacketsForward.h" #include "blitz/protocol/Packets.h"
#include "blitz/protocol/Protocol.h"
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
class PacketDispatcher; using PacketHandler = sp::PacketHandler;
/**
* \class PacketHandler
* \brief Class used to handle packets
*/
class PacketHandler {
private:
PacketDispatcher* m_Dispatcher;
public:
/**
* \brief Constructor
* \param dispatcher The packet dispatcher
*/
PacketHandler(PacketDispatcher* dispatcher) : m_Dispatcher(dispatcher) {}
virtual ~PacketHandler() {}
/**
* \brief Get the packet dispatcher
* \return The packet dispatcher
*/
PacketDispatcher* GetDispatcher() {
return m_Dispatcher;
}
virtual void HandlePacket(const ChatPacket* packet) {}
virtual void HandlePacket(const ConnexionInfoPacket* packet) {}
virtual void HandlePacket(const DisconnectPacket* packet) {}
virtual void HandlePacket(const KeepAlivePacket* packet) {}
virtual void HandlePacket(const PlayerJoinPacket* packet) {}
virtual void HandlePacket(const PlayerLeavePacket* packet) {}
virtual void HandlePacket(const PlayerListPacket* packet) {}
virtual void HandlePacket(const PlayerLoginPacket* packet) {}
virtual void HandlePacket(const PlayerPositionAndRotationPacket* packet) {}
virtual void HandlePacket(const PlayerShootPacket* packet) {}
virtual void HandlePacket(const PlayerStatsPacket* packet) {}
virtual void HandlePacket(const ServerConfigPacket* packet) {}
virtual void HandlePacket(const ServerTpsPacket* packet) {}
virtual void HandlePacket(const UpdateGameStatePacket* packet) {}
virtual void HandlePacket(const UpdateHealthPacket* packet) {}
};
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -1,7 +1,39 @@
#pragma once
namespace blitz {
namespace protocol {
/**
* \enum PacketType
* \brief Map the packets name to their ID
*/
enum PacketType {
Chat = 0, /**< Corresponds to ChatPacket */
ConnexionInfo, /**< Corresponds to ConnexionInfoPacket */
Disconnect, /**< Corresponds to DisconnectPacket */
KeepAlive, /**< Corresponds to KeepAlivePacket */
PlayerDeath, /**< Corresponds to PlayerDeathPacket */
PlayerJoin, /**< Corresponds to PlayerJoinPacket */
PlayerLeave, /**< Corresponds to PlayerLeavePacket */
PlayerList, /**< Corresponds to PlayerListPacket */
PlayerLogin, /**< Corresponds to PlayerLoginPacket */
PlayerPositionAndRotation, /**< Corresponds to PlayerPositionAndRotationPacket */
PlayerShoot, /**< Corresponds to PlayerShootPacket */
PlayerStats, /**< Corresponds to PlayerStatsPacket */
ServerConfig, /**< Corresponds to ServerConfigPacket*/
ServerTps, /**< Corresponds to ServerTpsPacket */
UpdateGameState, /**< Corresponds to UpdateGameStatePacket */
UpdateHealth, /**< Corresponds to UpdateHealthPacket */
};
} // namespace protocol
} // namespace blitz
#include "packets/ChatPacket.h" #include "packets/ChatPacket.h"
#include "packets/ConnexionInfoPacket.h" #include "packets/ConnexionInfoPacket.h"
#include "packets/DisconnectPacket.h" #include "packets/DisconnectPacket.h"
#include "packets/KeepAlivePacket.h" #include "packets/KeepAlivePacket.h"
#include "packets/PlayerDeathPacket.h"
#include "packets/PlayerJoinPacket.h" #include "packets/PlayerJoinPacket.h"
#include "packets/PlayerLeavePacket.h" #include "packets/PlayerLeavePacket.h"
#include "packets/PlayerListPacket.h" #include "packets/PlayerListPacket.h"
@@ -13,3 +45,34 @@
#include "packets/ServerTpsPacket.h" #include "packets/ServerTpsPacket.h"
#include "packets/UpdateGameStatePacket.h" #include "packets/UpdateGameStatePacket.h"
#include "packets/UpdateHealthPacket.h" #include "packets/UpdateHealthPacket.h"
// they must be in the same order as in the enum !
using AllPackets = std::tuple<
blitz::protocol::ChatPacket,
blitz::protocol::ConnexionInfoPacket,
blitz::protocol::DisconnectPacket,
blitz::protocol::KeepAlivePacket,
blitz::protocol::PlayerDeathPacket,
blitz::protocol::PlayerJoinPacket,
blitz::protocol::PlayerLeavePacket,
blitz::protocol::PlayerListPacket,
blitz::protocol::PlayerLoginPacket,
blitz::protocol::PlayerPositionAndRotationPacket,
blitz::protocol::PlayerShootPacket,
blitz::protocol::PlayerStatsPacket,
blitz::protocol::ServerConfigPacket,
blitz::protocol::ServerTpsPacket,
blitz::protocol::UpdateGameStatePacket,
blitz::protocol::UpdateHealthPacket
>;
#include <sp/default/DefaultPacketFactory.h>
#include <sp/default/DefaultPacketHandler.h>
namespace blitz {
namespace protocol {
using Packet = sp::PacketMessage;
} // namespace protocol
} // namespace blitz

View File

@@ -7,6 +7,7 @@ class ChatPacket;
class ConnexionInfoPacket; class ConnexionInfoPacket;
class DisconnectPacket; class DisconnectPacket;
class KeepAlivePacket; class KeepAlivePacket;
class PlayerDeathPacket;
class PlayerJoinPacket; class PlayerJoinPacket;
class PlayerLeavePacket; class PlayerLeavePacket;
class PlayerListPacket; class PlayerListPacket;

View File

@@ -1,103 +0,0 @@
#pragma once
/**
* \file Protocol.h
* \brief File containing the blitz::protocol::Protocol class
*/
#include "blitz/common/DataBuffer.h"
namespace blitz {
namespace protocol {
class PacketHandler;
/**
* \enum PacketType
* \brief Map the packets name to their ID
*/
enum class PacketType : std::uint8_t {
// client --> server
PlayerLogin = 0, /**< Corresponds to PlayerLoginPacket */
UpdateHealth, /**< Corresponds to UpdateHealthPacket */
// client <-- server
ConnexionInfo, /**< Corresponds to ConnexionInfoPacket */
PlayerJoin, /**< Corresponds to PlayerJoinPacket */
PlayerLeave, /**< Corresponds to PlayerLeavePacket */
PlayerList, /**< Corresponds to PlayerListPacket */
PlayerStats, /**< Corresponds to PlayerStatsPacket */
ServerConfig, /**< Corresponds to ServerConfigPacket*/
ServerTps, /**< Corresponds to ServerTpsPacket */
UpdateGameState, /**< Corresponds to UpdateGameStatePacket */
// client <--> server
KeepAlive, /**< Corresponds to KeepAlivePacket */
Disconnect, /**< Corresponds to DisconnectPacket */
Chat, /**< Corresponds to ChatPacket */
PlayerPositionAndRotation, /**< Corresponds to PlayerPositionAndRotationPacket */
PlayerShoot, /**< Corresponds to PlayerShootPacket */
PACKET_COUNT
};
/**
* \class Packet
* \brief Represents a network packet <br/>
* %Packet data structure :
*| Field Name | Field Type | Notes |
*|---------------------|---------------|-------------------------------|
*| Length | Long | Length of whole Packet |
*| Uncompressed Length | VarInt | Length of Packet ID + Data |
*| Packet ID | Byte | Represents the #PacketType |
*| Data | Byte Array | Depends on the packet ID |
*/
class Packet {
public:
Packet() {}
virtual ~Packet() {}
/**
* \brief Serialize the Packet into a DataBuffer to be sent over the network
* \param packetID Set to false if you don't want to write the Packet ID for some reason
* \returns A DataBuffer filled with the serialized Packet
*/
virtual DataBuffer Serialize(bool packetID = true) const = 0;
/**
* \brief Deserialize the DataBuffer into a Packet to be read by the client/server
* \param data The DataBuffer containing the data from the network
*/
virtual void Deserialize(DataBuffer& data) = 0;
/**
* \brief Dispatches the Packet
* \param handler The class to dispatch the Packet to
*/
virtual void Dispatch(PacketHandler* handler) const = 0;
/**
* \brief Writes the Packet ID into a buffer
* \param data The DataBuffer to write to
* \param packetID If set to false, this function does nothing
*/
void WritePacketID(DataBuffer& data, bool packetID) const;
/**
* \returns The type of the Packet
*/
virtual PacketType GetType() const = 0;
/**
* \returns The Packet ID corresponding to the PacketType of this Packet
*/
std::uint8_t GetID() const {
return static_cast<std::uint8_t>(GetType());
}
};
} // namespace protocol
} // namespace blitz

View File

@@ -5,29 +5,22 @@
* \brief File containing the blitz::protocol::ChatPacket class * \brief File containing the blitz::protocol::ChatPacket class
*/ */
#include "blitz/maths/Vector.h"
#include "blitz/protocol/Protocol.h" #include "blitz/protocol/Color.h"
#include <vector> #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
/** enum class ChatFieldsE {
* \struct ColoredPart m_Message = 0,
* \brief Represents a part of a chat message with a specific color.
*/
struct ColoredPart {
/**
* \brief The color of the part.
*/
Vec4f color;
/**
* \brief The text of the part.
*/
std::string text;
}; };
typedef std::vector<ColoredPart> ColoredText; using ChatFields = std::tuple<
ColoredText //<- m_Message
>;
/** /**
* \class ChatPacket * \class ChatPacket
@@ -41,64 +34,21 @@ typedef std::vector<ColoredPart> ColoredText;
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | m_Message | ColoredText | The message sent in the chat | * | m_Message | ColoredText | The message sent in the chat |
*/ */
class ChatPacket : public Packet { DeclarePacket(Chat){
private: public:
ColoredText m_Message; PacketConstructor(Chat)
public: ChatPacket(const std::string& msg) : ChatPacket(ColorizeText(msg)) {}
/**
* \brief Default constructor.
*/
ChatPacket() {}
/**
* \brief Constructor.
* \param msg The message to send.
*/
ChatPacket(const std::string& msg) : m_Message(ColorizeText(msg)) {}
/**
* \brief Constructor.
* \param msg The message to send.
*/
ChatPacket(const ColoredText& msg) : m_Message(msg) {}
virtual ~ChatPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the message. * \brief Get the message.
* \return The message. * \return The message.
*/ */
const ColoredText& GetMessage() const { const ColoredText& GetMessage() const {
return m_Message; return GetField<ChatFieldsE, ChatFieldsE::m_Message>();
} }
virtual PacketType GetType() const {
return PacketType::Chat;
}
/**
* \brief Get the text color.
*/
static std::string GetTextColor(Vec3uc color);
/**
* \brief Colorize a text.
*/
static ColoredText ColorizeText(const std::string& text);
/**
* \brief Get the colored text string.
*/
static std::string GetColoredTextString(const ColoredText& text);
}; };
const static Vec3uc AQUA = {0, 255, 255};
const static Vec3uc BLUE = {0, 0, 255};
const static Vec3uc GREEN = {0, 255, 0};
const static Vec3uc PURPLE = {255, 0, 255};
const static Vec3uc RED = {255, 0, 0};
const static Vec3uc WHITE = {255, 255, 255};
const static Vec3uc YELLOW = {255, 255, 0};
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -5,11 +5,21 @@
* \brief File containing the blitz::protocol::ConnexionInfoPacket class * \brief File containing the blitz::protocol::ConnexionInfoPacket class
*/ */
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class ConnexionInfoFieldsE {
m_ConnectionID = 0,
};
using ConnexionInfoFields = std::tuple<
std::uint8_t //<- m_ConnectionID
>;
/** /**
* \class ConnexionInfoPacket * \class ConnexionInfoPacket
* \brief Packet for sending connection information. * \brief Packet for sending connection information.
@@ -22,36 +32,16 @@ namespace protocol {
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | m_ConnectionID | std::uint8_t | The connection ID | * | m_ConnectionID | std::uint8_t | The connection ID |
*/ */
class ConnexionInfoPacket : public Packet { DeclarePacket(ConnexionInfo){
private: public:
std::uint8_t m_ConnectionID; PacketConstructor(ConnexionInfo)
public:
/**
* \brief Default constructor.
*/
ConnexionInfoPacket() {}
/**
* \brief Constructor.
* \param connectionID The ID of the connection.
*/
ConnexionInfoPacket(std::uint8_t connectionID) : m_ConnectionID(connectionID) {}
virtual ~ConnexionInfoPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the connection ID. * \brief Get the connection ID.
* \return The connection ID. * \return The connection ID.
*/ */
std::uint8_t GetConnectionID() const { std::uint8_t GetConnectionID() const {
return m_ConnectionID; return GetField<ConnexionInfoFieldsE, ConnexionInfoFieldsE::m_ConnectionID>();
}
virtual PacketType GetType() const {
return PacketType::ConnexionInfo;
} }
}; };

View File

@@ -5,11 +5,21 @@
* \brief File containing the blitz::protocol::DisconnectPacket class * \brief File containing the blitz::protocol::DisconnectPacket class
*/ */
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class DisconnectFieldsE {
m_Reason = 0,
};
using DisconnectFields = std::tuple<
std::string //<- m_Reason
>;
/** /**
* \class DisconnectPacket * \class DisconnectPacket
* \brief Packet for disconnecting from the server. * \brief Packet for disconnecting from the server.
@@ -22,35 +32,16 @@ namespace protocol {
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | m_Reason | std::string | The reason for disconnection | * | m_Reason | std::string | The reason for disconnection |
*/ */
class DisconnectPacket : public Packet { DeclarePacket(Disconnect){
private: public:
std::string m_Reason; // only when sent from server PacketConstructor(Disconnect)
public:
/**
* \brief Default constructor.
*/
DisconnectPacket() {}
/**
* \brief Constructor.
* \param reason The reason for disconnection.
*/
DisconnectPacket(std::string reason) : m_Reason(reason) {}
virtual ~DisconnectPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the reason for disconnection. * \brief Get the reason for disconnection.
* \return The reason for disconnection. * \return The reason for disconnection.
*/ */
const std::string& GetReason() const { const std::string& GetReason() const {
return m_Reason; return GetField<DisconnectFieldsE, DisconnectFieldsE::m_Reason>();
}
virtual PacketType GetType() const {
return PacketType::Disconnect;
} }
}; };

View File

@@ -5,12 +5,21 @@
* \brief File containing the blitz::protocol::KeepAlivePacket class * \brief File containing the blitz::protocol::KeepAlivePacket class
*/ */
#include "blitz/common/VarInt.h" #include <sp/default/DefaultPacket.h>
#include "blitz/protocol/Protocol.h" #include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class KeepAliveFieldsE {
KeepAliveId = 0,
};
using KeepAliveFields = std::tuple<
sp::VarInt //<- KeepAliveId
>;
/** /**
* \class KeepAlivePacket * \class KeepAlivePacket
* \brief Packet sent to measure the health of a connexion. \n * \brief Packet sent to measure the health of a connexion. \n
@@ -25,31 +34,18 @@ namespace protocol {
* | Keep Alive ID | VarInt | The server generates a random ID, the client must respond with the same | * | Keep Alive ID | VarInt | The server generates a random ID, the client must respond with the same |
* *
*/ */
class KeepAlivePacket : public Packet { DeclarePacket(KeepAlive){
private: public:
VarInt m_AliveID; PacketConstructor(KeepAlive)
public:
KeepAlivePacket() {}
KeepAlivePacket(std::uint64_t aliveID) : m_AliveID(aliveID) {}
virtual ~KeepAlivePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Getter of the alive ID * \brief Getter of the alive ID
* \return The alive ID * \return The alive ID
*/ */
std::uint64_t GetAliveID() const { std::uint64_t GetAliveId() const {
return m_AliveID.GetValue(); return GetField<KeepAliveFieldsE, KeepAliveFieldsE::KeepAliveId>().GetValue();
}
virtual PacketType GetType() const {
return PacketType::KeepAlive;
} }
}; };
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz

View File

@@ -0,0 +1,50 @@
#pragma once
/**
* \file PlayerDeathPacket.h
* \brief File containing the blitz::protocol::PlayerDeathPacket class
*/
#include "blitz/common/Defines.h"
#include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz {
namespace protocol {
enum class PlayerDeathFieldsE {
m_PlayerID = 0,
};
using PlayerDeathFields = std::tuple<
game::PlayerID //<- m_PlayerID
>;
/**
* \class PlayerDeathPacket
* \brief Packet for when a player leaves the game.
* %Packet structure :
* | PacketType |
* |------------------------|
* | PacketType::PlayerDeath|
*
* | Field Name | Field Type | Notes |
* |--------------------|-------------------|-------------------------------|
* | m_PlayerID | PlayerID |The ID of the player that died |
*/
DeclarePacket(PlayerDeath){
public:
PacketConstructor(PlayerDeath)
/**
* \brief Get the ID of the player that died.
* \return The ID of the player that died.
*/
game::PlayerID GetPlayerID() const {
return GetField<PlayerDeathFieldsE, PlayerDeathFieldsE::m_PlayerID>();
}
};
} // namespace protocol
} // namespace blitz

View File

@@ -6,11 +6,23 @@
*/ */
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerJoinFieldsE {
m_PlayerID = 0,
m_PlayerName,
};
using PlayerJoinFields = std::tuple<
game::PlayerID, //<- m_PlayerID
std::string //<- m_PlayerName
>;
/** /**
* \class PlayerJoinPacket * \class PlayerJoinPacket
* \brief Packet sent when a new player joins the game * \brief Packet sent when a new player joins the game
@@ -25,26 +37,16 @@ namespace protocol {
* | Player Name | std::string | Name of the player who joined | * | Player Name | std::string | Name of the player who joined |
* *
*/ */
class PlayerJoinPacket : public Packet { DeclarePacket(PlayerJoin){
private: public:
game::PlayerID m_PlayerID; PacketConstructor(PlayerJoin)
std::string m_PlayerName;
public:
PlayerJoinPacket() {}
PlayerJoinPacket(game::PlayerID playerID, const std::string& playerName) : m_PlayerID(playerID), m_PlayerName(playerName) {}
virtual ~PlayerJoinPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Getter of the player id * \brief Get the ID of the player that died.
* \return The ID of the player * \return The ID of the player that died.
*/ */
game::PlayerID GetPlayerID() const { game::PlayerID GetPlayerID() const {
return m_PlayerID; return GetField<PlayerJoinFieldsE, PlayerJoinFieldsE::m_PlayerID>();
} }
/** /**
@@ -52,11 +54,7 @@ class PlayerJoinPacket : public Packet {
* \return The name of the player * \return The name of the player
*/ */
const std::string& GetPlayerName() const { const std::string& GetPlayerName() const {
return m_PlayerName; return GetField<PlayerJoinFieldsE, PlayerJoinFieldsE::m_PlayerName>();
}
virtual PacketType GetType() const {
return PacketType::PlayerJoin;
} }
}; };

View File

@@ -6,11 +6,22 @@
*/ */
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerLeaveFieldsE {
m_PlayerID = 0,
};
using PlayerLeaveFields = std::tuple<
game::PlayerID //<- m_PlayerID
>;
/** /**
* \class PlayerLeavePacket * \class PlayerLeavePacket
* \brief Packet for when a player leaves the game. * \brief Packet for when a player leaves the game.
@@ -23,36 +34,16 @@ namespace protocol {
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | m_PlayerID | PlayerID |The ID of the player that left | * | m_PlayerID | PlayerID |The ID of the player that left |
*/ */
class PlayerLeavePacket : public Packet { DeclarePacket(PlayerLeave){
private: public:
game::PlayerID m_PlayerID; PacketConstructor(PlayerLeave)
public:
/** /**
* \brief Default constructor. * \brief Get the ID of the player that left.
*/ * \return The ID of the player that left.
PlayerLeavePacket() {} */
/**
* \brief Constructor.
* \param playerID The ID of the player that left.
*/
PlayerLeavePacket(game::PlayerID playerID) : m_PlayerID(playerID) {}
virtual ~PlayerLeavePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the ID of the player that left.
* \return The ID of the player that left.
*/
game::PlayerID GetPlayerID() const { game::PlayerID GetPlayerID() const {
return m_PlayerID; return GetField<PlayerLeaveFieldsE, PlayerLeaveFieldsE::m_PlayerID>();
}
virtual PacketType GetType() const {
return PacketType::PlayerLeave;
} }
}; };

View File

@@ -7,7 +7,10 @@
#include <map> #include <map>
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
#include <sp/protocol/MessagePrinter.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
@@ -17,49 +20,38 @@ namespace protocol {
* \brief Represents information about a player. * \brief Represents information about a player.
*/ */
struct PlayerInfo { struct PlayerInfo {
std::string name; std::string m_Name;
}; };
typedef std::map<std::uint8_t, PlayerInfo> PlayerList; using PlayerMap = std::map<std::uint8_t, PlayerInfo>;
/**
* \class PlayerListPacket
* \brief Packet for sending the list of players.
* \todo PACKET STRUCTURE
*/
class PlayerListPacket : public Packet {
private:
PlayerList m_Players;
public:
/**
* \brief Default constructor.
*/
PlayerListPacket() {}
/**
* \brief Constructor.
* \param players The list of players.
*/
PlayerListPacket(const PlayerList& players) : m_Players(players) {}
virtual ~PlayerListPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
enum class PlayerListFieldsE {
m_PlayerList = 0,
};
using PlayerListFields = std::tuple<
PlayerMap //<- m_PlayerList
>;
DeclarePacket(PlayerList){
public:
PacketConstructor(PlayerList)
/** /**
* \brief Get the list of players. * \brief Get the list of players.
* \return The list of players. * \return The list of players.
*/ */
const PlayerList& GetPlayers() const { const PlayerMap& GetPlayers() const {
return m_Players; return GetField<PlayerListFieldsE, PlayerListFieldsE::m_PlayerList>();
}
virtual PacketType GetType() const {
return PacketType::PlayerList;
} }
}; };
} // namespace protocol } // namespace protocol
} // namespace blitz } // namespace blitz
namespace sp {
template <>
inline std::string PrintData(const blitz::protocol::PlayerInfo& a_Config) {
return "{m_Name=" + PrintData(a_Config.m_Name) + "}";
}
} // namespace sp

View File

@@ -5,11 +5,21 @@
* \brief File containing the blitz::protocol::PlayerLoginPacket class * \brief File containing the blitz::protocol::PlayerLoginPacket class
*/ */
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerLoginFieldsE {
m_PlayerName = 0,
};
using PlayerLoginFields = std::tuple<
std::string //<- m_PlayerName
>;
/** /**
* \class PlayerLoginPacket * \class PlayerLoginPacket
* \brief Packet for when a player logs in. * \brief Packet for when a player logs in.
@@ -22,36 +32,16 @@ namespace protocol {
* |--------------------|-------------------|----------------------------------| * |--------------------|-------------------|----------------------------------|
* | Player Name | std::string | Name of the player that logged in| * | Player Name | std::string | Name of the player that logged in|
*/ */
class PlayerLoginPacket : public Packet { DeclarePacket(PlayerLogin){
private: public:
std::string m_PlayerName; PacketConstructor(PlayerLogin)
public:
/**
* \brief Default constructor.
*/
PlayerLoginPacket() {}
/**
* \brief Constructor.
* \param playerName The name of the player that logged in.
*/
PlayerLoginPacket(std::string playerName) : m_PlayerName(playerName) {}
virtual ~PlayerLoginPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the name of the player that logged in. * \brief Get the name of the player that logged in.
* \return The name of the player that logged in. * \return The name of the player that logged in.
*/ */
const std::string& GetPlayerName() const { const std::string& GetPlayerName() const {
return m_PlayerName; return GetField<PlayerLoginFieldsE, PlayerLoginFieldsE::m_PlayerName>();
}
virtual PacketType GetType() const {
return PacketType::PlayerLogin;
} }
}; };

View File

@@ -7,11 +7,27 @@
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerPositionAndRotationFieldsE {
m_PlayerID = 0,
m_Position,
m_Yaw,
m_Pitch,
};
using PlayerPositionAndRotationFields = std::tuple<
game::PlayerID, //<- m_PlayerID
Vec3f, //<- m_Position
float, //<- m_Yaw
float //<- m_Pitch
>;
/** /**
* \class PlayerPositionAndRotationPacket * \class PlayerPositionAndRotationPacket
* \brief Packet for sending a player's position and rotation. * \brief Packet for sending a player's position and rotation.
@@ -27,38 +43,16 @@ namespace protocol {
* | Yaw | float | Yaw of the player | * | Yaw | float | Yaw of the player |
* | Pitch | float | Pitch of the player | * | Pitch | float | Pitch of the player |
*/ */
class PlayerPositionAndRotationPacket : public Packet { DeclarePacket(PlayerPositionAndRotation){
private: public:
game::PlayerID m_Player; // only used when sent to client PacketConstructor(PlayerPositionAndRotation)
Vec3f m_Position;
float m_Yaw, m_Pitch;
public:
/**
* \brief Default constructor.
*/
PlayerPositionAndRotationPacket() {}
/**
* \brief Constructor.
* \param position The position of the player.
* \param yaw The yaw of the player.
* \param pitch The pitch of the player.
* \param player The ID of the player.
*/
PlayerPositionAndRotationPacket(const Vec3f& position, float yaw, float pitch, game::PlayerID player = 0) :
m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {}
virtual ~PlayerPositionAndRotationPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the position of the player. * \brief Get the position of the player.
* \return The position of the player. * \return The position of the player.
*/ */
const Vec3f& GetPosition() const { const Vec3f& GetPosition() const {
return m_Position; return GetField<PlayerPositionAndRotationFieldsE, PlayerPositionAndRotationFieldsE::m_Position>();
} }
/** /**
@@ -66,7 +60,7 @@ class PlayerPositionAndRotationPacket : public Packet {
* \return The yaw of the player. * \return The yaw of the player.
*/ */
float GetYaw() const { float GetYaw() const {
return m_Yaw; return GetField<PlayerPositionAndRotationFieldsE, PlayerPositionAndRotationFieldsE::m_Yaw>();
} }
/** /**
@@ -74,7 +68,7 @@ class PlayerPositionAndRotationPacket : public Packet {
* \return The pitch of the player. * \return The pitch of the player.
*/ */
float GetPitch() const { float GetPitch() const {
return m_Pitch; return GetField<PlayerPositionAndRotationFieldsE, PlayerPositionAndRotationFieldsE::m_Pitch>();
} }
/** /**
@@ -82,11 +76,7 @@ class PlayerPositionAndRotationPacket : public Packet {
* \return The ID of the player. * \return The ID of the player.
*/ */
game::PlayerID GetPlayer() const { game::PlayerID GetPlayer() const {
return m_Player; return GetField<PlayerPositionAndRotationFieldsE, PlayerPositionAndRotationFieldsE::m_PlayerID>();
}
virtual PacketType GetType() const {
return PacketType::PlayerPositionAndRotation;
} }
}; };

View File

@@ -6,11 +6,27 @@
*/ */
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerShootFieldsE {
m_PlayerID = 0,
m_Position,
m_Yaw,
m_Pitch,
};
using PlayerShootFields = std::tuple<
game::PlayerID, //<- m_PlayerID
Vec3f, //<- m_Position
float, //<- m_Yaw
float //<- m_Pitch
>;
/** /**
* \class PlayerShootPacket * \class PlayerShootPacket
* \brief Packet for when a player shoots. * \brief Packet for when a player shoots.
@@ -26,38 +42,16 @@ namespace protocol {
* | Yaw | float | Yaw of the player | * | Yaw | float | Yaw of the player |
* | Pitch | float | Pitch of the player | * | Pitch | float | Pitch of the player |
*/ */
class PlayerShootPacket : public Packet { DeclarePacket(PlayerShoot){
private: public:
game::PlayerID m_Player; // only used when sent to client PacketConstructor(PlayerShoot)
Vec3f m_Position;
float m_Yaw, m_Pitch;
public:
/**
* \brief Default constructor.
*/
PlayerShootPacket() {}
/**
* \brief Constructor.
* \param position The position of the player.
* \param yaw The yaw of the player.
* \param pitch The pitch of the player.
* \param player The ID of the player.
*/
PlayerShootPacket(Vec3f position, float yaw, float pitch, game::PlayerID player = 0) :
m_Player(player), m_Position(position), m_Yaw(yaw), m_Pitch(pitch) {}
virtual ~PlayerShootPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the position of the player. * \brief Get the position of the player.
* \return The position of the player. * \return The position of the player.
*/ */
const Vec3f& GetPosition() const { const Vec3f& GetPosition() const {
return m_Position; return GetField<PlayerShootFieldsE, PlayerShootFieldsE::m_Position>();
} }
/** /**
@@ -65,7 +59,7 @@ class PlayerShootPacket : public Packet {
* \return The yaw of the player. * \return The yaw of the player.
*/ */
float GetYaw() const { float GetYaw() const {
return m_Yaw; return GetField<PlayerShootFieldsE, PlayerShootFieldsE::m_Yaw>();
} }
/** /**
@@ -73,7 +67,7 @@ class PlayerShootPacket : public Packet {
* \return The pitch of the player. * \return The pitch of the player.
*/ */
float GetPitch() const { float GetPitch() const {
return m_Pitch; return GetField<PlayerShootFieldsE, PlayerShootFieldsE::m_Pitch>();
} }
/** /**
@@ -81,11 +75,7 @@ class PlayerShootPacket : public Packet {
* \return The ID of the player. * \return The ID of the player.
*/ */
game::PlayerID GetPlayer() const { game::PlayerID GetPlayer() const {
return m_Player; return GetField<PlayerShootFieldsE, PlayerShootFieldsE::m_PlayerID>();
}
virtual PacketType GetType() const {
return PacketType::PlayerShoot;
} }
}; };

View File

@@ -7,11 +7,23 @@
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/game/Player.h" #include "blitz/game/Player.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class PlayerStatsFieldsE {
m_PlayerID = 0,
m_PlayerStats,
};
using PlayerStatsFields = std::tuple<
game::PlayerID, //<- m_PlayerID
game::PlayerStats //<- m_PlayerStats
>;
/** /**
* \class PlayerStatsPacket * \class PlayerStatsPacket
* \brief Packet for sending player stats. * \brief Packet for sending player stats.
@@ -25,34 +37,16 @@ namespace protocol {
* | Player ID | PlayerID | Id of the player | * | Player ID | PlayerID | Id of the player |
* | Player Stats | PlayerStats | Stats of the player | * | Player Stats | PlayerStats | Stats of the player |
*/ */
class PlayerStatsPacket : public Packet { DeclarePacket(PlayerStats){
private: public:
game::PlayerID m_PlayerID; PacketConstructor(PlayerStats)
game::PlayerStats m_PlayerStats;
public:
/**
* \brief Default constructor.
*/
PlayerStatsPacket() {}
/**
* \brief Constructor.
* \param playerID The ID of the player.
* \param stats The stats of the player.
*/
PlayerStatsPacket(game::PlayerID playerID, const game::PlayerStats& stats) : m_PlayerID(playerID), m_PlayerStats(stats) {}
virtual ~PlayerStatsPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Getter of the player id * \brief Getter of the player id
* \return The ID of the player * \return The ID of the player
*/ */
game::PlayerID GetPlayerID() const { game::PlayerID GetPlayerID() const {
return m_PlayerID; return GetField<PlayerStatsFieldsE, PlayerStatsFieldsE::m_PlayerID>();
} }
/** /**
@@ -60,11 +54,7 @@ class PlayerStatsPacket : public Packet {
* \return The stats of the player * \return The stats of the player
*/ */
const game::PlayerStats& GetPlayerStats() const { const game::PlayerStats& GetPlayerStats() const {
return m_PlayerStats; return GetField<PlayerStatsFieldsE, PlayerStatsFieldsE::m_PlayerStats>();
}
virtual PacketType GetType() const {
return PacketType::PlayerStats;
} }
}; };

View File

@@ -6,11 +6,21 @@
*/ */
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class ServerConfigFieldsE {
m_GameConfig = 0,
};
using ServerConfigFields = std::tuple<
game::GameConfig //<- m_GameConfig
>;
/** /**
* \class ServerConfigPacket * \class ServerConfigPacket
* \brief Packet for sending the server configuration. * \brief Packet for sending the server configuration.
@@ -23,36 +33,16 @@ namespace protocol {
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | Game Config | GameConfig | The game configuration | * | Game Config | GameConfig | The game configuration |
*/ */
class ServerConfigPacket : public Packet { DeclarePacket(ServerConfig){
private: public:
game::GameConfig m_GameConfig; PacketConstructor(ServerConfig)
public:
/**
* \brief Default constructor.
*/
ServerConfigPacket() {}
/**
* \brief Constructor.
* \param GameConfig The game configuration.
*/
ServerConfigPacket(const game::GameConfig& GameConfig) : m_GameConfig(GameConfig) {}
virtual ~ServerConfigPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Getter of the game configuration * \brief Getter of the game configuration
* \return The game configuration * \return The game configuration
*/ */
game::GameConfig GetGameConfig() const { game::GameConfig GetGameConfig() const {
return m_GameConfig; return GetField<ServerConfigFieldsE, ServerConfigFieldsE::m_GameConfig>();
}
virtual PacketType GetType() const {
return PacketType::ServerConfig;
} }
}; };

View File

@@ -5,11 +5,25 @@
* \brief File containing the blitz::protocol::ServerTpsPacket class * \brief File containing the blitz::protocol::ServerTpsPacket class
*/ */
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class ServerTpsFieldsE {
m_TPS = 0,
m_MSPT,
m_PacketSendTime,
};
using ServerTpsFields = std::tuple<
float, //<- m_TPS
float, //<- m_MSPT
std::uint64_t //<- m_PacketSendTime
>;
/** /**
* \class ServerTpsPacket * \class ServerTpsPacket
* \brief Packet for sending server TPS (Tick per second) and MSPT (Milliseconds per tick). * \brief Packet for sending server TPS (Tick per second) and MSPT (Milliseconds per tick).
@@ -24,35 +38,16 @@ namespace protocol {
* | Mspt | float | Server MSPT | * | Mspt | float | Server MSPT |
* | PacketSendTime | uint64_t | Time the packet was sent | * | PacketSendTime | uint64_t | Time the packet was sent |
*/ */
class ServerTpsPacket : public Packet { DeclarePacket(ServerTps){
private: public:
float m_TPS; PacketConstructor(ServerTps)
float m_MSPT;
std::uint64_t m_PacketSendTime; // used to calculate ping
public:
/**
* \brief Default constructor.
*/
ServerTpsPacket() {}
/**
* \brief Constructor.
* \param tps The server TPS.
* \param mspt The server MSPT.
* \param sendTime The time the packet was sent.
*/
ServerTpsPacket(float tps, float mspt, std::uint64_t sendTime) : m_TPS(tps), m_MSPT(mspt), m_PacketSendTime(sendTime) {}
virtual ~ServerTpsPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the server TPS. * \brief Get the server TPS.
* \return The server TPS. * \return The server TPS.
*/ */
float GetTPS() const { float GetTPS() const {
return m_TPS; return GetField<ServerTpsFieldsE, ServerTpsFieldsE::m_TPS>();
} }
/** /**
@@ -60,7 +55,7 @@ class ServerTpsPacket : public Packet {
* \return The server MSPT. * \return The server MSPT.
*/ */
float GetMSPT() const { float GetMSPT() const {
return m_MSPT; return GetField<ServerTpsFieldsE, ServerTpsFieldsE::m_MSPT>();
} }
/** /**
@@ -69,11 +64,7 @@ class ServerTpsPacket : public Packet {
* \todo Calculate ping. * \todo Calculate ping.
*/ */
std::uint64_t GetPacketSendTime() const { std::uint64_t GetPacketSendTime() const {
return m_PacketSendTime; return GetField<ServerTpsFieldsE, ServerTpsFieldsE::m_PacketSendTime>();
}
virtual PacketType GetType() const {
return PacketType::ServerTps;
} }
}; };

View File

@@ -6,11 +6,23 @@
*/ */
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class UpdateGameStateFieldsE {
m_GameState = 0,
m_TimeRemaining,
};
using UpdateGameStateFields = std::tuple<
game::GameState, //<- m_GameState
std::uint64_t //<- m_TimeRemaining
>;
/** /**
* \class UpdateGameStatePacket * \class UpdateGameStatePacket
* \brief Packet for updating the game state. * \brief Packet for updating the game state.
@@ -24,35 +36,16 @@ namespace protocol {
* | Game State | GameState | The new game state | * | Game State | GameState | The new game state |
* | Time Remaining | std::uint64_t | The time remaining in the current game state | * | Time Remaining | std::uint64_t | The time remaining in the current game state |
*/ */
class UpdateGameStatePacket : public Packet { DeclarePacket(UpdateGameState){
private: public:
game::GameState m_GameState; PacketConstructor(UpdateGameState)
std::uint64_t m_TimeRemaining;
public:
/**
* \brief Default constructor.
*/
UpdateGameStatePacket() {}
/**
* \brief Constructor.
* \param a_GameState The new game state.
* \param a_TimeRemaining The time remaining in the current game state.
*/
UpdateGameStatePacket(game::GameState a_GameState, std::uint64_t a_TimeRemaining = 0) :
m_GameState(a_GameState), m_TimeRemaining(a_TimeRemaining) {}
virtual ~UpdateGameStatePacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/** /**
* \brief Get the new game state. * \brief Get the new game state.
* \return The new game state. * \return The new game state.
*/ */
game::GameState GetGameState() const { game::GameState GetGameState() const {
return m_GameState; return GetField<UpdateGameStateFieldsE, UpdateGameStateFieldsE::m_GameState>();
} }
/** /**
@@ -60,11 +53,7 @@ class UpdateGameStatePacket : public Packet {
* \return The time remaining in the current game state. * \return The time remaining in the current game state.
*/ */
std::uint64_t GetTimeRemaining() const { std::uint64_t GetTimeRemaining() const {
return m_TimeRemaining; return GetField<UpdateGameStateFieldsE, UpdateGameStateFieldsE::m_TimeRemaining>();
}
virtual PacketType GetType() const {
return PacketType::UpdateGameState;
} }
}; };

View File

@@ -5,11 +5,21 @@
* \brief File containing the blitz::protocol::UpdateHealthPacket class * \brief File containing the blitz::protocol::UpdateHealthPacket class
*/ */
#include "blitz/protocol/Protocol.h" #include <sp/default/DefaultPacket.h>
#include <sp/protocol/Field.h>
#include <sp/protocol/MessageBase.h>
namespace blitz { namespace blitz {
namespace protocol { namespace protocol {
enum class UpdateHealthFieldsE {
m_NewHealth = 0,
};
using UpdateHealthFields = std::tuple<
float //<- m_NewHealth
>;
/** /**
* \class UpdateHealthPacket * \class UpdateHealthPacket
* \brief Packet for updating the health of a player. * \brief Packet for updating the health of a player.
@@ -22,36 +32,16 @@ namespace protocol {
* |--------------------|-------------------|-------------------------------| * |--------------------|-------------------|-------------------------------|
* | m_NewHealth | float | The new health value | * | m_NewHealth | float | The new health value |
*/ */
class UpdateHealthPacket : public Packet { DeclarePacket(UpdateHealth){
private: public:
float m_NewHealth; PacketConstructor(UpdateHealth)
public:
/** /**
* \brief Default constructor. * \brief Get the ID of the player that left.
* \return The ID of the player that left.
*/ */
UpdateHealthPacket() {} game::PlayerID GetNewHealth() const {
/** return GetField<UpdateHealthFieldsE, UpdateHealthFieldsE::m_NewHealth>();
* \brief Constructor.
* \param newHealth The new health value.
*/
UpdateHealthPacket(float newHealth) : m_NewHealth(newHealth) {}
virtual ~UpdateHealthPacket() {}
virtual DataBuffer Serialize(bool packetID = true) const;
virtual void Deserialize(DataBuffer& data);
virtual void Dispatch(PacketHandler* handler) const;
/**
* \brief Get the new health value.
* \return The new health value.
*/
float GetNewHealth() const {
return m_NewHealth;
}
virtual PacketType GetType() const {
return PacketType::UpdateHealth;
} }
}; };

View File

@@ -1,10 +1,9 @@
#pragma once #pragma once
#include "blitz/common/Defines.h" #include "blitz/common/Defines.h"
#include "blitz/game/Listeners.h"
#include "blitz/misc/ObjectNotifier.h" #include "blitz/misc/ObjectNotifier.h"
#include "blitz/misc/Time.h" #include "blitz/misc/Time.h"
#include "blitz/protocol/packets/ChatPacket.h" #include "client/Listeners.h"
#include "client/config/BlitzConfig.h" #include "client/config/BlitzConfig.h"
#include <cstdint> #include <cstdint>
#include <memory> #include <memory>
@@ -14,19 +13,17 @@ namespace blitz {
static const int PlayerUpdatePosRate = 50; static const int PlayerUpdatePosRate = 50;
namespace client {
class ClientConnexion;
class ClientGame;
} // namespace client
namespace server { namespace server {
class Server; class Server;
} // namespace server } // namespace server
namespace client {
class ClientConnexion;
class ClientGame;
// Singleton // Singleton
class Client : public utils::ObjectNotifier<game::ClientListener>, public game::PlayerInputListener { class Client : public utils::ObjectNotifier<client::ClientListener>, public client::PlayerInputListener {
private: private:
std::unique_ptr<server::Server> m_Server; std::unique_ptr<server::Server> m_Server;
std::unique_ptr<client::ClientConnexion> m_Connexion; std::unique_ptr<client::ClientConnexion> m_Connexion;
@@ -78,4 +75,5 @@ class Client : public utils::ObjectNotifier<game::ClientListener>, public game::
void UpdatePosition(std::uint64_t delta); void UpdatePosition(std::uint64_t delta);
}; };
} // namespace client
} // namespace blitz } // namespace blitz

View File

@@ -4,11 +4,10 @@
#include "blitz/network/Connexion.h" #include "blitz/network/Connexion.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
namespace client {
class ClientConnexion : public network::Connexion { class ClientConnexion : public network::Connexion {
private: private:
Client* m_Client; Client* m_Client;
@@ -19,10 +18,10 @@ class ClientConnexion : public network::Connexion {
ClientConnexion(Client* client); ClientConnexion(Client* client);
virtual ~ClientConnexion(); virtual ~ClientConnexion();
virtual void HandlePacket(const protocol::DisconnectPacket* packet) override; virtual void Handle(const protocol::DisconnectPacket& packet) override;
virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override; virtual void Handle(const protocol::KeepAlivePacket& packet) override;
virtual void HandlePacket(const protocol::ChatPacket* packet) override; virtual void Handle(const protocol::ChatPacket& packet) override;
virtual void HandlePacket(const protocol::ConnexionInfoPacket* packet) override; virtual void Handle(const protocol::ConnexionInfoPacket& packet) override;
bool Connect(const std::string& pseudo, const std::string& address, std::uint16_t port); bool Connect(const std::string& pseudo, const std::string& address, std::uint16_t port);

View File

@@ -0,0 +1,37 @@
#pragma once
#include "blitz/common/Defines.h"
#include "blitz/maths/Vector.h"
#include <vector>
namespace blitz {
namespace protocol {
struct ColoredPart;
typedef std::vector<ColoredPart> ColoredText;
} // namespace protocol
namespace client {
class PlayerInputListener {
public:
virtual void OnLocalPlayerJump() {}
virtual void OnLocalPlayerShoot(const Vec3f& position, float yaw, float pitch) {}
};
class ClientListener {
public:
virtual void OnTextChatReceived(const protocol::ColoredText& text) {}
virtual void OnSpectatorChange(game::PlayerID player) {}
virtual void OnPlayerShoot(game::PlayerID player, const Vec3f& position, float yaw, float pitch) {}
virtual void OnClientPlayerJoin() {}
virtual void OnGameConfigUpdate() {}
virtual void OnGameJoin() {}
virtual void OnGameLeave() {}
};
} // namespace game
} // namespace blitz

View File

@@ -1,14 +1,14 @@
#pragma once #pragma once
#include "blitz/common/DataBuffer.h" #include "blitz/common/DataBuffer.h"
#include "blitz/common/NonCopyable.h" #include <sp/common/NonCopyable.h>
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include "client/audio/AudioLoader.h" #include "client/audio/AudioLoader.h"
namespace blitz { namespace blitz {
namespace audio { namespace audio {
class AudioBuffer : private NonCopyable { class AudioBuffer : private sp::NonCopyable {
private: private:
unsigned int m_ID; unsigned int m_ID;

View File

@@ -1,12 +1,12 @@
#pragma once #pragma once
#include "blitz/common/NonCopyable.h" #include <sp/common/NonCopyable.h>
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
namespace blitz { namespace blitz {
namespace audio { namespace audio {
class AudioListener : private NonCopyable { class AudioListener : private sp::NonCopyable {
public: public:
AudioListener(); AudioListener();
~AudioListener(); ~AudioListener();

View File

@@ -1,13 +1,16 @@
#pragma once #pragma once
#include "blitz/game/Listeners.h" #include "blitz/game/Listeners.h"
#include "client/Listeners.h"
#include "client/audio/AudioListener.h" #include "client/audio/AudioListener.h"
#include "client/audio/AudioSource.h" #include "client/audio/AudioSource.h"
#include <map> #include <map>
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace game { namespace game {
class Player; class Player;
@@ -18,24 +21,31 @@ namespace audio {
struct PlayerSound { struct PlayerSound {
AudioSourcePtr m_Laser; AudioSourcePtr m_Laser;
AudioSourcePtr m_FootStep;
AudioSourcePtr m_Death;
}; };
class AudioManager : public game::ClientListener, public game::GameListener { class AudioManager : public client::ClientListener, public game::GameListener {
private: private:
Client* m_Client; client::Client* m_Client;
game::Player* m_Player; game::Player* m_Player;
AudioListener m_Listener; AudioListener m_Listener;
AudioSourcePtr m_MenuMusic; AudioSourcePtr m_MenuMusic;
AudioSourcePtr m_EndMusic;
AudioBufferPtr m_DeathSound;
AudioBufferPtr m_LaserSound; AudioBufferPtr m_LaserSound;
AudioBufferPtr m_FootStepSound;
std::map<game::PlayerID, PlayerSound> m_PlayerSources; std::map<game::PlayerID, PlayerSound> m_PlayerSources;
public: public:
AudioManager(Client* client); AudioManager(client::Client* client);
~AudioManager(); ~AudioManager();
virtual void OnGameJoin() override; virtual void OnGameJoin() override;
virtual void OnGameLeave() override; virtual void OnGameLeave() override;
virtual void OnGameStateUpdate(game::GameState gameState) override;
virtual void OnClientPlayerJoin() override; virtual void OnClientPlayerJoin() override;
virtual void OnPlayerDeath(game::PlayerID player) override;
virtual void OnPlayerShoot(game::PlayerID player, const Vec3f& position, float yaw, float pitch) override; virtual void OnPlayerShoot(game::PlayerID player, const Vec3f& position, float yaw, float pitch) override;
virtual void OnPlayerJoin(game::PlayerID player) override; virtual void OnPlayerJoin(game::PlayerID player) override;
virtual void OnPlayerLeave(game::PlayerID player) override; virtual void OnPlayerLeave(game::PlayerID player) override;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include "blitz/common/NonCopyable.h" #include <sp/common/NonCopyable.h>
#include "blitz/maths/Vector.h" #include "blitz/maths/Vector.h"
#include "client/audio/AudioBuffer.h" #include "client/audio/AudioBuffer.h"
#include <memory> #include <memory>
@@ -10,7 +10,7 @@ namespace audio {
typedef std::shared_ptr<AudioBuffer> AudioBufferPtr; typedef std::shared_ptr<AudioBuffer> AudioBufferPtr;
class AudioSource : NonCopyable { class AudioSource : sp::NonCopyable {
private: private:
unsigned int m_ID; unsigned int m_ID;
AudioBufferPtr m_Buffer; AudioBufferPtr m_Buffer;

View File

@@ -11,6 +11,8 @@
namespace blitz { namespace blitz {
namespace input {
/** /**
* \enum KeyAction * \enum KeyAction
* \brief Enum containing the key actions * \brief Enum containing the key actions
@@ -24,7 +26,9 @@ enum KeyAction {
kaMax, kaMax,
}; };
typedef std::array<int, kaMax> Keybinds; } // namespace input
typedef std::array<int, input::kaMax> Keybinds;
/** /**
* \class BlitzConfig * \class BlitzConfig

View File

@@ -3,34 +3,36 @@
#include "blitz/game/Game.h" #include "blitz/game/Game.h"
#include "blitz/game/LeaderBoard.h" #include "blitz/game/LeaderBoard.h"
#include "blitz/protocol/PacketHandler.h" #include "blitz/protocol/PacketHandler.h"
#include "blitz/protocol/PacketDispatcher.h"
#include <vector> #include <vector>
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
namespace client {
class ClientGame : public game::Game, public protocol::PacketHandler { class ClientGame : public game::Game, public protocol::PacketHandler {
private: private:
Client* m_Client; Client* m_Client;
game::LeaderBoard m_LeaderBoard; game::LeaderBoard m_LeaderBoard;
protocol::PacketDispatcher& m_Dispatcher;
public: public:
ClientGame(Client* client, protocol::PacketDispatcher* dispatcher); ClientGame(Client* client, protocol::PacketDispatcher& dispatcher);
virtual ~ClientGame(); virtual ~ClientGame();
void Tick(std::uint64_t delta) override; void Tick(std::uint64_t delta) override;
virtual void HandlePacket(const protocol::PlayerJoinPacket* packet) override; virtual void Handle(const protocol::PlayerDeathPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerLeavePacket* packet) override; virtual void Handle(const protocol::PlayerJoinPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerListPacket* packet) override; virtual void Handle(const protocol::PlayerLeavePacket& packet) override;
virtual void HandlePacket(const protocol::PlayerPositionAndRotationPacket* packet) override; virtual void Handle(const protocol::PlayerListPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerShootPacket* packet) override; virtual void Handle(const protocol::PlayerPositionAndRotationPacket& packet) override;
virtual void HandlePacket(const protocol::UpdateHealthPacket* packet) override; virtual void Handle(const protocol::PlayerShootPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerStatsPacket* packet) override; virtual void Handle(const protocol::UpdateHealthPacket& packet) override;
virtual void HandlePacket(const protocol::UpdateGameStatePacket* packet) override; virtual void Handle(const protocol::PlayerStatsPacket& packet) override;
virtual void HandlePacket(const protocol::ServerConfigPacket* packet) override; virtual void Handle(const protocol::UpdateGameStatePacket& packet) override;
virtual void Handle(const protocol::ServerConfigPacket& packet) override;
virtual void AddPlayer(game::PlayerID player, const std::string& name) override; virtual void AddPlayer(game::PlayerID player, const std::string& name) override;
virtual void RemovePlayer(game::PlayerID player) override; virtual void RemovePlayer(game::PlayerID player) override;
@@ -41,6 +43,10 @@ class ClientGame : public game::Game, public protocol::PacketHandler {
private: private:
void RegisterHandlers(); void RegisterHandlers();
protocol::PacketDispatcher& GetDispatcher() {
return m_Dispatcher;
}
}; };
} // namespace client } // namespace client

View File

@@ -1,11 +1,13 @@
#pragma once #pragma once
#include "GuiWidget.h" #include "GuiWidget.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
@@ -14,7 +16,7 @@ class BlitzGui : public GuiWidget {
enum SubMenu { Main = 0 }; enum SubMenu { Main = 0 };
public: public:
BlitzGui(Client* client, input::InputManager& inputManager); BlitzGui(client::Client* client, input::InputManager& inputManager);
virtual void Render() override; virtual void Render() override;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include "blitz/protocol/packets/ChatPacket.h" #include "blitz/protocol/Color.h"
#include <string> #include <string>
namespace blitz { namespace blitz {

View File

@@ -1,11 +1,13 @@
#pragma once #pragma once
#include "GuiWidget.h" #include "GuiWidget.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
@@ -14,7 +16,7 @@ class CreateGameMenu : public GuiWidget {
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
public: public:
CreateGameMenu(GuiWidget* parent, Client* client, input::InputManager& inputManager); CreateGameMenu(GuiWidget* parent, client::Client* client, input::InputManager& inputManager);
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -3,6 +3,11 @@
#include "GuiWidget.h" #include "GuiWidget.h"
namespace blitz { namespace blitz {
namespace client {
class Client;
} // namespace client
namespace gui { namespace gui {
class CrossHair : public GuiWidget { class CrossHair : public GuiWidget {
@@ -10,7 +15,7 @@ class CrossHair : public GuiWidget {
std::uint64_t m_CrossHairTexture; std::uint64_t m_CrossHairTexture;
public: public:
CrossHair(Client* client); CrossHair(client::Client* client);
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -4,13 +4,15 @@
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
class FPSMenu : public GuiWidget { class FPSMenu : public GuiWidget {
public: public:
FPSMenu(GuiWidget* parent, Client* client) : GuiWidget(parent, client) {} FPSMenu(GuiWidget* parent, client::Client* client) : GuiWidget(parent, client) {}
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -2,15 +2,19 @@
#include "GuiWidget.h" #include "GuiWidget.h"
#include "client/Client.h" #include "client/Client.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
#include <string> #include <string>
#include <vector> #include <vector>
namespace blitz { namespace blitz {
namespace client {
class Client;
} // namespace client
namespace gui { namespace gui {
class GameChatGui : public GuiWidget, game::ClientListener { class GameChatGui : public GuiWidget, client::ClientListener {
private: private:
char InputBuf[256]; char InputBuf[256];
std::vector<protocol::ColoredText> m_Lines; std::vector<protocol::ColoredText> m_Lines;
@@ -27,7 +31,7 @@ class GameChatGui : public GuiWidget, game::ClientListener {
void DrawMini(const char* title, bool* p_open); void DrawMini(const char* title, bool* p_open);
public: public:
GameChatGui(GuiWidget* parent, Client* client, input::InputManager& inputManager); GameChatGui(GuiWidget* parent, client::Client* client, input::InputManager& inputManager);
virtual ~GameChatGui(); virtual ~GameChatGui();
virtual void OnTextChatReceived(const protocol::ColoredText& text) override; virtual void OnTextChatReceived(const protocol::ColoredText& text) override;

View File

@@ -7,19 +7,21 @@
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
class GuiWidget { class GuiWidget {
protected: protected:
bool m_Enabled; bool m_Enabled;
Client* m_Client; client::Client* m_Client;
GuiWidget* m_Parent; GuiWidget* m_Parent;
std::vector<std::unique_ptr<GuiWidget>> m_SubWidgets; std::vector<std::unique_ptr<GuiWidget>> m_SubWidgets;
public: public:
GuiWidget(GuiWidget* parent, Client* client) : m_Enabled(false), m_Client(client), m_Parent(parent) {} GuiWidget(GuiWidget* parent, client::Client* client) : m_Enabled(false), m_Client(client), m_Parent(parent) {}
virtual ~GuiWidget() {} virtual ~GuiWidget() {}
void Enable() { void Enable() {

View File

@@ -5,23 +5,30 @@
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace game { namespace game {
class Player; class Player;
} // namespace game } // namespace game
namespace gui { namespace gui {
class Hud : public GuiWidget { class Hud : public GuiWidget, public game::GameListener, public client::ClientListener {
private: private:
std::uint64_t m_GunTexture; std::uint64_t m_GunTexture;
std::uint64_t m_JPTexture; std::uint64_t m_JPTexture;
utils::DelayTimer<float> m_Timer{5.0f}; utils::DelayTimer<float> m_Timer{5.0f};
public: public:
Hud(GuiWidget* parent, Client* client); Hud(GuiWidget* parent, client::Client* client);
virtual ~Hud();
virtual void Render() override; virtual void Render() override;
virtual void OnGameStateUpdate(game::GameState gameState) override;
virtual void OnGameJoin() override;
virtual void OnGameLeave() override;
private: private:
std::string FormatString(); std::string FormatString();
void Draw(const char* title, bool* p_open); void Draw(const char* title, bool* p_open);

View File

@@ -1,11 +1,13 @@
#pragma once #pragma once
#include "GuiWidget.h" #include "GuiWidget.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
@@ -14,7 +16,7 @@ class JoinGameMenu : public GuiWidget {
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
public: public:
JoinGameMenu(GuiWidget* parent, Client* client, input::InputManager& inputManager); JoinGameMenu(GuiWidget* parent, client::Client* client, input::InputManager& inputManager);
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -5,16 +5,24 @@
namespace blitz { namespace blitz {
namespace client {
class Client;
} // namespace client
namespace gui { namespace gui {
class LeaderBoardGui : public GuiWidget { class LeaderBoardGui : public GuiWidget, public game::GameListener, public client::ClientListener {
private: private:
void Draw(const char* title, bool* p_open); void Draw(const char* title, bool* p_open);
utils::DelayTimer<float> m_Timer{5.0f}; utils::DelayTimer<float> m_Timer{5.0f};
public: public:
LeaderBoardGui(GuiWidget* parent, Client* client); LeaderBoardGui(GuiWidget* parent, client::Client* client);
~LeaderBoardGui(); ~LeaderBoardGui();
virtual void OnGameStateUpdate(game::GameState gameState) override;
virtual void OnGameJoin() override;
virtual void OnGameLeave() override;
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -1,11 +1,13 @@
#pragma once #pragma once
#include "GuiWidget.h" #include "GuiWidget.h"
#include "blitz/game/Listeners.h" #include "client/Listeners.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace input { namespace input {
class InputManager; class InputManager;
@@ -13,14 +15,14 @@ class InputManager;
namespace gui { namespace gui {
class MainMenu : public GuiWidget, public game::ClientListener { class MainMenu : public GuiWidget, public client::ClientListener {
private: private:
enum SubMenu { CREATE_MENU = 0, JOIN_MENU, OPTION_MENU }; enum SubMenu { CREATE_MENU = 0, JOIN_MENU, OPTION_MENU };
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
public: public:
MainMenu(Client* client, input::InputManager& inputManager); MainMenu(client::Client* client, input::InputManager& inputManager);
virtual ~MainMenu(); virtual ~MainMenu();
virtual void OnGameLeave() override; virtual void OnGameLeave() override;

View File

@@ -3,13 +3,15 @@
#include "GuiWidget.h" #include "GuiWidget.h"
#include "blitz/misc/Time.h" #include "blitz/misc/Time.h"
#include "client/config/BlitzConfig.h" #include "client/config/BlitzConfig.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
#include <array> #include <array>
#include <string> #include <string>
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
@@ -20,11 +22,11 @@ class OptionsMenu : public GuiWidget, public input::InputListener {
bool m_IsKeyPopupOpen; bool m_IsKeyPopupOpen;
bool m_KeyPopupShouldClose; bool m_KeyPopupShouldClose;
utils::Timer m_Timer{100}; utils::Timer m_Timer{100};
KeyAction m_CurrentAction; input::KeyAction m_CurrentAction;
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
public: public:
OptionsMenu(GuiWidget* parent, Client* client, input::InputManager& inputManager); OptionsMenu(GuiWidget* parent, client::Client* client, input::InputManager& inputManager);
virtual ~OptionsMenu(); virtual ~OptionsMenu();
virtual void Render() override; virtual void Render() override;
@@ -32,7 +34,7 @@ class OptionsMenu : public GuiWidget, public input::InputListener {
virtual void OnKeyDown(int key) override; virtual void OnKeyDown(int key) override;
private: private:
std::string GetKeyActionCodeName(KeyAction); std::string GetKeyActionCodeName(input::KeyAction);
void HotkeyBindingButton(); void HotkeyBindingButton();
void HotkeyBindingPopUp(); void HotkeyBindingPopUp();
}; };

View File

@@ -1,9 +1,14 @@
#pragma once #pragma once
#include "GuiWidget.h" #include "GuiWidget.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
namespace blitz { namespace blitz {
namespace client {
class Client;
} // namespace client
namespace gui { namespace gui {
class ServerGui : public GuiWidget { class ServerGui : public GuiWidget {
@@ -11,7 +16,7 @@ class ServerGui : public GuiWidget {
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
public: public:
ServerGui(GuiWidget* parent, Client* client, input::InputManager& inputManager); ServerGui(GuiWidget* parent, client::Client* client, input::InputManager& inputManager);
virtual void Render() override; virtual void Render() override;
}; };

View File

@@ -5,8 +5,8 @@
* \brief File containing the blitz::Display class * \brief File containing the blitz::Display class
*/ */
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
#include "client/display/PlayerController.h" #include "client/input/PlayerController.h"
#include <memory> #include <memory>
#include <string> #include <string>
@@ -14,12 +14,16 @@ class SDL_Window;
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace gui { namespace gui {
class BlitzGui; class BlitzGui;
} // namespace gui } // namespace gui
namespace input {
/** /**
* \class Display * \class Display
* \brief Class used to manage the display * \brief Class used to manage the display
@@ -37,7 +41,7 @@ class Display {
bool m_ShouldClose; bool m_ShouldClose;
bool m_FullScreen; bool m_FullScreen;
Client* m_Client; client::Client* m_Client;
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
std::unique_ptr<gui::BlitzGui> m_BlitzGui; std::unique_ptr<gui::BlitzGui> m_BlitzGui;
input::PlayerController m_PlayerController; input::PlayerController m_PlayerController;
@@ -51,7 +55,7 @@ class Display {
* \param client The client * \param client The client
* \param inputManager The InputManager * \param inputManager The InputManager
*/ */
Display(int width, int height, const std::string& windowName, Client* client, input::InputManager& inputManager); Display(int width, int height, const std::string& windowName, client::Client* client, input::InputManager& inputManager);
~Display(); ~Display();
/** /**
@@ -112,4 +116,5 @@ class Display {
void InitImGui(); void InitImGui();
}; };
} // namespace input
} // namespace blitz } // namespace blitz

View File

@@ -5,15 +5,17 @@
* \brief File containing the blitz::input::PlayerController class. * \brief File containing the blitz::input::PlayerController class.
*/ */
#include "blitz/common/Smoothing.h" #include "blitz/maths/Smoothing.h"
#include "blitz/game/Listeners.h"
#include "blitz/misc/ObjectNotifier.h" #include "blitz/misc/ObjectNotifier.h"
#include "blitz/misc/Time.h" #include "blitz/misc/Time.h"
#include "client/display/InputManager.h" #include "client/input/InputManager.h"
#include "client/Listeners.h"
namespace blitz { namespace blitz {
namespace client {
class Client; class Client;
} // namespace client
namespace game { namespace game {
@@ -28,14 +30,14 @@ namespace input {
* \details This class is responsible for handling player input and sending it to the server. * \details This class is responsible for handling player input and sending it to the server.
* It also handles the player's velocity and position. * It also handles the player's velocity and position.
*/ */
class PlayerController : public utils::ObjectNotifier<game::PlayerInputListener>, game::ClientListener, InputListener { class PlayerController : public utils::ObjectNotifier<client::PlayerInputListener>, client::ClientListener, InputListener {
private: private:
game::Player* m_Player; game::Player* m_Player;
Client* m_Client; client::Client* m_Client;
input::InputManager& m_InputManager; input::InputManager& m_InputManager;
utils::CooldownTimer<float> m_ShootTimer{1.0f}; utils::CooldownTimer<float> m_ShootTimer{1.0f};
EMASmoother m_DxSmoother; maths::EMASmoother m_DxSmoother;
EMASmoother m_DySmoother; maths::EMASmoother m_DySmoother;
// current (target) velocity // current (target) velocity
Vec3f m_Velocity; Vec3f m_Velocity;
/// maximum x-axis velocity /// maximum x-axis velocity
@@ -47,7 +49,7 @@ class PlayerController : public utils::ObjectNotifier<game::PlayerInputListener>
/** /**
* \brief Default constructor * \brief Default constructor
*/ */
PlayerController(Client* client, input::InputManager& inputManager); PlayerController(client::Client* client, input::InputManager& inputManager);
virtual ~PlayerController(); virtual ~PlayerController();
/** /**

View File

@@ -1,7 +1,6 @@
#pragma once #pragma once
#include "client/Client.h" #include "client/input/PlayerController.h"
#include "client/display/PlayerController.h"
#include "client/render/BulletRenderer.h" #include "client/render/BulletRenderer.h"
#include "client/render/Camera.h" #include "client/render/Camera.h"
#include "client/render/loader/GLLoader.h" #include "client/render/loader/GLLoader.h"
@@ -9,6 +8,10 @@
namespace blitz { namespace blitz {
namespace client {
class Client;
} // namespace client
namespace shader { namespace shader {
class EntityShader; class EntityShader;
@@ -20,9 +23,9 @@ class GunShader;
namespace render { namespace render {
class MainRenderer : public game::ClientListener, public game::PlayerInputListener { class MainRenderer : public client::ClientListener, public client::PlayerInputListener {
private: private:
Client* m_Client; client::Client* m_Client;
ModelLoader::Model m_PlayerModel; ModelLoader::Model m_PlayerModel;
ModelLoader::Model m_WorldModel; ModelLoader::Model m_WorldModel;
ModelLoader::Model m_GunModel; ModelLoader::Model m_GunModel;
@@ -36,7 +39,7 @@ class MainRenderer : public game::ClientListener, public game::PlayerInputListen
input::PlayerController& m_PlayerController; input::PlayerController& m_PlayerController;
public: public:
MainRenderer(Client* client, input::PlayerController& playerController); MainRenderer(client::Client* client, input::PlayerController& playerController);
~MainRenderer(); ~MainRenderer();
virtual void OnSpectatorChange(game::PlayerID player) override; virtual void OnSpectatorChange(game::PlayerID player) override;

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include "blitz/common/NonCopyable.h" #include <sp/common/NonCopyable.h>
#include <vector> #include <vector>
@@ -13,7 +13,7 @@ struct VertexAttribPointer {
unsigned int m_Offset; unsigned int m_Offset;
}; };
class ElementBuffer : private NonCopyable { class ElementBuffer : private sp::NonCopyable {
private: private:
unsigned int m_ID = 0; unsigned int m_ID = 0;
std::size_t m_TriangleCount; std::size_t m_TriangleCount;
@@ -35,7 +35,7 @@ class ElementBuffer : private NonCopyable {
} }
}; };
class VertexBuffer : private NonCopyable { class VertexBuffer : private sp::NonCopyable {
private: private:
unsigned int m_ID = 0, m_DataStride; unsigned int m_ID = 0, m_DataStride;
std::vector<VertexAttribPointer> m_VertexAttribs; std::vector<VertexAttribPointer> m_VertexAttribs;
@@ -56,7 +56,7 @@ class VertexBuffer : private NonCopyable {
void BindVertexAttribs() const; void BindVertexAttribs() const;
}; };
class VertexArray : private NonCopyable { class VertexArray : private sp::NonCopyable {
private: private:
unsigned int m_ID = 0; unsigned int m_ID = 0;
ElementBuffer m_ElementBuffer; ElementBuffer m_ElementBuffer;

View File

@@ -35,7 +35,7 @@ typedef std::map<std::uint8_t, std::unique_ptr<ServerConnexion>> ConnexionMap;
*/ */
class Server { class Server {
private: private:
network::TCPListener m_Listener; std::unique_ptr<network::TCPListener> m_Listener;
ConnexionMap m_Connections; ConnexionMap m_Connections;
utils::TickCounter m_TickCounter; utils::TickCounter m_TickCounter;
@@ -91,7 +91,7 @@ class Server {
* \brief Broadcast a packet to all connexions * \brief Broadcast a packet to all connexions
* \param packet The packet * \param packet The packet
*/ */
void BroadcastPacket(const protocol::Packet* packet); void BroadcastPacket(const protocol::Packet& packet);
/** /**
* \brief Broadcast a chat message * \brief Broadcast a chat message
* \param msg The message * \param msg The message

View File

@@ -52,7 +52,7 @@ class ServerConnexion : public network::Connexion {
* \param socket The socket * \param socket The socket
* \param id The ID of the connexion * \param id The ID of the connexion
*/ */
ServerConnexion(Server* server, network::TCPSocket& socket, std::uint8_t id); ServerConnexion(Server* server, std::unique_ptr<network::TCPSocket>&& socket, std::uint8_t id);
/** /**
* \brief Move constructor * \brief Move constructor
*/ */
@@ -72,14 +72,14 @@ class ServerConnexion : public network::Connexion {
return m_ID; return m_ID;
} }
virtual void HandlePacket(const protocol::PlayerLoginPacket* packet) override; virtual void Handle(const protocol::PlayerLoginPacket& packet) override;
virtual void HandlePacket(const protocol::KeepAlivePacket* packet) override; virtual void Handle(const protocol::KeepAlivePacket& packet) override;
virtual void HandlePacket(const protocol::DisconnectPacket* packet) override; virtual void Handle(const protocol::DisconnectPacket& packet) override;
virtual void HandlePacket(const protocol::ChatPacket* packet) override; virtual void Handle(const protocol::ChatPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerPositionAndRotationPacket* packet) override; virtual void Handle(const protocol::PlayerPositionAndRotationPacket& packet) override;
virtual void HandlePacket(const protocol::PlayerShootPacket* packet) override; virtual void Handle(const protocol::PlayerShootPacket& packet) override;
virtual bool UpdateSocket() override; virtual bool UpdateSocket() override;
private: private:
void RegisterHandlers(); void RegisterHandlers();

View File

@@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014-2023 Omar Cornut
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -1,942 +0,0 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
// About WebGL/ES:
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
// - This is done automatically on iOS, Android and Emscripten targets.
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2023-06-20: OpenGL: Fixed erroneous use glGetIntegerv(GL_CONTEXT_PROFILE_MASK) on contexts lower than 3.2. (#6539, #6333)
// 2023-05-09: OpenGL: Support for glBindSampler() backup/restore on ES3. (#6375)
// 2023-04-18: OpenGL: Restore front and back polygon mode separately when supported by context. (#6333)
// 2023-03-23: OpenGL: Properly restoring "no shader program bound" if it was the case prior to running the rendering function. (#6267, #6220, #6224)
// 2023-03-15: OpenGL: Fixed GL loader crash when GL_VERSION returns NULL. (#6154, #4445, #3530)
// 2023-03-06: OpenGL: Fixed restoration of a potentially deleted OpenGL program, by calling glIsProgram(). (#6220, #6224)
// 2022-11-09: OpenGL: Reverted use of glBufferSubData(), too many corruptions issues + old issues seemingly can't be reproed with Intel drivers nowadays (revert 2021-12-15 and 2022-05-23 changes).
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-09-27: OpenGL: Added ability to '#define IMGUI_IMPL_OPENGL_DEBUG'.
// 2022-05-23: OpenGL: Reworking 2021-12-15 "Using buffer orphaning" so it only happens on Intel GPU, seems to cause problems otherwise. (#4468, #4825, #4832, #5127).
// 2022-05-13: OpenGL: Fixed state corruption on OpenGL ES 2.0 due to not preserving GL_ELEMENT_ARRAY_BUFFER_BINDING and vertex attribute states.
// 2021-12-15: OpenGL: Using buffer orphaning + glBufferSubData(), seems to fix leaks with multi-viewports with some Intel HD drivers.
// 2021-08-23: OpenGL: Fixed ES 3.0 shader ("#version 300 es") use normal precision floats to avoid wobbly rendering at HD resolutions.
// 2021-08-19: OpenGL: Embed and use our own minimal GL loader (imgui_impl_opengl3_loader.h), removing requirement and support for third-party loader.
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2021-06-25: OpenGL: Use OES_vertex_array extension on Emscripten + backup/restore current state.
// 2021-06-21: OpenGL: Destroy individual vertex/fragment shader objects right after they are linked into the main shader.
// 2021-05-24: OpenGL: Access GL_CLIP_ORIGIN when "GL_ARB_clip_control" extension is detected, inside of just OpenGL 4.5 version.
// 2021-05-19: OpenGL: Replaced direct access to ImDrawCmd::TextureId with a call to ImDrawCmd::GetTexID(). (will become a requirement)
// 2021-04-06: OpenGL: Don't try to read GL_CLIP_ORIGIN unless we're OpenGL 4.5 or greater.
// 2021-02-18: OpenGL: Change blending equation to preserve alpha in output buffer.
// 2021-01-03: OpenGL: Backup, setup and restore GL_STENCIL_TEST state.
// 2020-10-23: OpenGL: Backup, setup and restore GL_PRIMITIVE_RESTART state.
// 2020-10-15: OpenGL: Use glGetString(GL_VERSION) instead of glGetIntegerv(GL_MAJOR_VERSION, ...) when the later returns zero (e.g. Desktop GL 2.x)
// 2020-09-17: OpenGL: Fix to avoid compiling/calling glBindSampler() on ES or pre 3.3 context which have the defines set by a loader.
// 2020-07-10: OpenGL: Added support for glad2 OpenGL loader.
// 2020-05-08: OpenGL: Made default GLSL version 150 (instead of 130) on OSX.
// 2020-04-21: OpenGL: Fixed handling of glClipControl(GL_UPPER_LEFT) by inverting projection matrix.
// 2020-04-12: OpenGL: Fixed context version check mistakenly testing for 4.0+ instead of 3.2+ to enable ImGuiBackendFlags_RendererHasVtxOffset.
// 2020-03-24: OpenGL: Added support for glbinding 2.x OpenGL loader.
// 2020-01-07: OpenGL: Added support for glbinding 3.x OpenGL loader.
// 2019-10-25: OpenGL: Using a combination of GL define and runtime GL version to decide whether to use glDrawElementsBaseVertex(). Fix building with pre-3.2 GL loaders.
// 2019-09-22: OpenGL: Detect default GL loader using __has_include compiler facility.
// 2019-09-16: OpenGL: Tweak initialization code to allow application calling ImGui_ImplOpenGL3_CreateFontsTexture() before the first NewFrame() call.
// 2019-05-29: OpenGL: Desktop GL only: Added support for large mesh (64K+ vertices), enable ImGuiBackendFlags_RendererHasVtxOffset flag.
// 2019-04-30: OpenGL: Added support for special ImDrawCallback_ResetRenderState callback to reset render state.
// 2019-03-29: OpenGL: Not calling glBindBuffer more than necessary in the render loop.
// 2019-03-15: OpenGL: Added a GL call + comments in ImGui_ImplOpenGL3_Init() to detect uninitialized GL function loaders early.
// 2019-03-03: OpenGL: Fix support for ES 2.0 (WebGL 1.0).
// 2019-02-20: OpenGL: Fix for OSX not supporting OpenGL 4.5, we don't try to read GL_CLIP_ORIGIN even if defined by the headers/loader.
// 2019-02-11: OpenGL: Projecting clipping rectangles correctly using draw_data->FramebufferScale to allow multi-viewports for retina display.
// 2019-02-01: OpenGL: Using GLSL 410 shaders for any version over 410 (e.g. 430, 450).
// 2018-11-30: Misc: Setting up io.BackendRendererName so it can be displayed in the About Window.
// 2018-11-13: OpenGL: Support for GL 4.5's glClipControl(GL_UPPER_LEFT) / GL_CLIP_ORIGIN.
// 2018-08-29: OpenGL: Added support for more OpenGL loaders: glew and glad, with comments indicative that any loader can be used.
// 2018-08-09: OpenGL: Default to OpenGL ES 3 on iOS and Android. GLSL version default to "#version 300 ES".
// 2018-07-30: OpenGL: Support for GLSL 300 ES and 410 core. Fixes for Emscripten compilation.
// 2018-07-10: OpenGL: Support for more GLSL versions (based on the GLSL version string). Added error output when shaders fail to compile/link.
// 2018-06-08: Misc: Extracted imgui_impl_opengl3.cpp/.h away from the old combined GLFW/SDL+OpenGL3 examples.
// 2018-06-08: OpenGL: Use draw_data->DisplayPos and draw_data->DisplaySize to setup projection matrix and clipping rectangle.
// 2018-05-25: OpenGL: Removed unnecessary backup/restore of GL_ELEMENT_ARRAY_BUFFER_BINDING since this is part of the VAO state.
// 2018-05-14: OpenGL: Making the call to glBindSampler() optional so 3.2 context won't fail if the function is a nullptr pointer.
// 2018-03-06: OpenGL: Added const char* glsl_version parameter to ImGui_ImplOpenGL3_Init() so user can override the GLSL version e.g. "#version 150".
// 2018-02-23: OpenGL: Create the VAO in the render function so the setup can more easily be used with multiple shared GL context.
// 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplSdlGL3_RenderDrawData() in the .h file so you can call it yourself.
// 2018-01-07: OpenGL: Changed GLSL shader version from 330 to 150.
// 2017-09-01: OpenGL: Save and restore current bound sampler. Save and restore current polygon mode.
// 2017-05-01: OpenGL: Fixed save and restore of current blend func state.
// 2017-05-01: OpenGL: Fixed save and restore of current GL_ACTIVE_TEXTURE.
// 2016-09-05: OpenGL: Fixed save and restore of current scissor rectangle.
// 2016-07-29: OpenGL: Explicitly setting GL_UNPACK_ROW_LENGTH to reduce issues because SDL changes it. (#752)
//----------------------------------------
// OpenGL GLSL GLSL
// version version string
//----------------------------------------
// 2.0 110 "#version 110"
// 2.1 120 "#version 120"
// 3.0 130 "#version 130"
// 3.1 140 "#version 140"
// 3.2 150 "#version 150"
// 3.3 330 "#version 330 core"
// 4.0 400 "#version 400 core"
// 4.1 410 "#version 410 core"
// 4.2 420 "#version 410 core"
// 4.3 430 "#version 430 core"
// ES 2.0 100 "#version 100" = WebGL 1.0
// ES 3.0 300 "#version 300 es" = WebGL 2.0
//----------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_opengl3.h"
#include <stdio.h>
#include <stdint.h> // intptr_t
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#pragma clang diagnostic ignored "-Wunused-macros" // warning: macro is not used
#pragma clang diagnostic ignored "-Wnonportable-system-include-path"
#pragma clang diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx'
#pragma GCC diagnostic ignored "-Wcast-function-type" // warning: cast between incompatible function types (for loader)
#endif
// GL includes
#if defined(IMGUI_IMPL_OPENGL_ES2)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES2/gl.h> // Use GL ES 2
#else
#include <GLES2/gl2.h> // Use GL ES 2
#endif
#if defined(__EMSCRIPTEN__)
#ifndef GL_GLEXT_PROTOTYPES
#define GL_GLEXT_PROTOTYPES
#endif
#include <GLES2/gl2ext.h>
#endif
#elif defined(IMGUI_IMPL_OPENGL_ES3)
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV))
#include <OpenGLES/ES3/gl.h> // Use GL ES 3
#else
#include <GLES3/gl3.h> // Use GL ES 3
#endif
#elif !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
// Modern desktop OpenGL doesn't have a standard portable header file to load OpenGL function pointers.
// Helper libraries are often used for this purpose! Here we are using our own minimal custom loader based on gl3w.
// In the rest of your app/engine, you can use another loader of your choice (gl3w, glew, glad, glbinding, glext, glLoadGen, etc.).
// If you happen to be developing a new feature for this backend (imgui_impl_opengl3.cpp):
// - You may need to regenerate imgui_impl_opengl3_loader.h to add new symbols. See https://github.com/dearimgui/gl3w_stripped
// - You can temporarily use an unstripped version. See https://github.com/dearimgui/gl3w_stripped/releases
// Changes to this backend using new APIs should be accompanied by a regenerated stripped loader version.
#define IMGL3W_IMPL
#include "imgui_impl_opengl3_loader.h"
#endif
// Vertex arrays are not supported on ES2/WebGL1 unless Emscripten which uses an extension
#ifndef IMGUI_IMPL_OPENGL_ES2
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#elif defined(__EMSCRIPTEN__)
#define IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
#define glBindVertexArray glBindVertexArrayOES
#define glGenVertexArrays glGenVertexArraysOES
#define glDeleteVertexArrays glDeleteVertexArraysOES
#define GL_VERTEX_ARRAY_BINDING GL_VERTEX_ARRAY_BINDING_OES
#endif
// Desktop GL 2.0+ has glPolygonMode() which GL ES and WebGL don't have.
#ifdef GL_POLYGON_MODE
#define IMGUI_IMPL_HAS_POLYGON_MODE
#endif
// Desktop GL 3.2+ has glDrawElementsBaseVertex() which GL ES and WebGL don't have.
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_2)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
#endif
// Desktop GL 3.3+ and GL ES 3.0+ have glBindSampler()
#if !defined(IMGUI_IMPL_OPENGL_ES2) && (defined(IMGUI_IMPL_OPENGL_ES3) || defined(GL_VERSION_3_3))
#define IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
#endif
// Desktop GL 3.1+ has GL_PRIMITIVE_RESTART state
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && defined(GL_VERSION_3_1)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
#endif
// Desktop GL use extension detection
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3)
#define IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
#endif
// [Debugging]
//#define IMGUI_IMPL_OPENGL_DEBUG
#ifdef IMGUI_IMPL_OPENGL_DEBUG
#include <stdio.h>
#define GL_CALL(_CALL) do { _CALL; GLenum gl_err = glGetError(); if (gl_err != 0) fprintf(stderr, "GL error 0x%x returned from '%s'.\n", gl_err, #_CALL); } while (0) // Call with error check
#else
#define GL_CALL(_CALL) _CALL // Call without error check
#endif
// OpenGL Data
struct ImGui_ImplOpenGL3_Data
{
GLuint GlVersion; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries (e.g. 320 for GL 3.2)
char GlslVersionString[32]; // Specified by user or detected based on compile time GL settings.
bool GlProfileIsES2;
bool GlProfileIsES3;
bool GlProfileIsCompat;
GLint GlProfileMask;
GLuint FontTexture;
GLuint ShaderHandle;
GLint AttribLocationTex; // Uniforms location
GLint AttribLocationProjMtx;
GLuint AttribLocationVtxPos; // Vertex attributes location
GLuint AttribLocationVtxUV;
GLuint AttribLocationVtxColor;
unsigned int VboHandle, ElementsHandle;
GLsizeiptr VertexBufferSize;
GLsizeiptr IndexBufferSize;
bool HasClipOrigin;
bool UseBufferSubData;
ImGui_ImplOpenGL3_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendRendererUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
static ImGui_ImplOpenGL3_Data* ImGui_ImplOpenGL3_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplOpenGL3_Data*)ImGui::GetIO().BackendRendererUserData : nullptr;
}
// OpenGL vertex attribute state (for ES 1.0 and ES 2.0 only)
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
struct ImGui_ImplOpenGL3_VtxAttribState
{
GLint Enabled, Size, Type, Normalized, Stride;
GLvoid* Ptr;
void GetState(GLint index)
{
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_ENABLED, &Enabled);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_SIZE, &Size);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_TYPE, &Type);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_NORMALIZED, &Normalized);
glGetVertexAttribiv(index, GL_VERTEX_ATTRIB_ARRAY_STRIDE, &Stride);
glGetVertexAttribPointerv(index, GL_VERTEX_ATTRIB_ARRAY_POINTER, &Ptr);
}
void SetState(GLint index)
{
glVertexAttribPointer(index, Size, Type, (GLboolean)Normalized, Stride, Ptr);
if (Enabled) glEnableVertexAttribArray(index); else glDisableVertexAttribArray(index);
}
};
#endif
// Functions
bool ImGui_ImplOpenGL3_Init(const char* glsl_version)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendRendererUserData == nullptr && "Already initialized a renderer backend!");
// Initialize our loader
#if !defined(IMGUI_IMPL_OPENGL_ES2) && !defined(IMGUI_IMPL_OPENGL_ES3) && !defined(IMGUI_IMPL_OPENGL_LOADER_CUSTOM)
if (imgl3wInit() != 0)
{
fprintf(stderr, "Failed to initialize OpenGL loader!\n");
return false;
}
#endif
// Setup backend capabilities flags
ImGui_ImplOpenGL3_Data* bd = IM_NEW(ImGui_ImplOpenGL3_Data)();
io.BackendRendererUserData = (void*)bd;
io.BackendRendererName = "imgui_impl_opengl3";
// Query for GL version (e.g. 320 for GL 3.2)
#if defined(IMGUI_IMPL_OPENGL_ES2)
// GLES 2
bd->GlVersion = 200;
bd->GlProfileIsES2 = true;
#else
// Desktop or GLES 3
GLint major = 0;
GLint minor = 0;
glGetIntegerv(GL_MAJOR_VERSION, &major);
glGetIntegerv(GL_MINOR_VERSION, &minor);
if (major == 0 && minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
const char* gl_version = (const char*)glGetString(GL_VERSION);
sscanf(gl_version, "%d.%d", &major, &minor);
}
bd->GlVersion = (GLuint)(major * 100 + minor * 10);
#if defined(GL_CONTEXT_PROFILE_MASK)
if (bd->GlVersion >= 320)
glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &bd->GlProfileMask);
bd->GlProfileIsCompat = (bd->GlProfileMask & GL_CONTEXT_COMPATIBILITY_PROFILE_BIT) != 0;
#endif
#if defined(IMGUI_IMPL_OPENGL_ES3)
bd->GlProfileIsES3 = true;
#endif
bd->UseBufferSubData = false;
/*
// Query vendor to enable glBufferSubData kludge
#ifdef _WIN32
if (const char* vendor = (const char*)glGetString(GL_VENDOR))
if (strncmp(vendor, "Intel", 5) == 0)
bd->UseBufferSubData = true;
#endif
*/
#endif
#ifdef IMGUI_IMPL_OPENGL_DEBUG
printf("GlVersion = %d\nGlProfileIsCompat = %d\nGlProfileMask = 0x%X\nGlProfileIsES2 = %d, GlProfileIsES3 = %d\nGL_VENDOR = '%s'\nGL_RENDERER = '%s'\n", bd->GlVersion, bd->GlProfileIsCompat, bd->GlProfileMask, bd->GlProfileIsES2, bd->GlProfileIsES3, (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER)); // [DEBUG]
#endif
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
#endif
// Store GLSL version string so we can refer to it later in case we recreate shaders.
// Note: GLSL version is NOT the same as GL version. Leave this to nullptr if unsure.
if (glsl_version == nullptr)
{
#if defined(IMGUI_IMPL_OPENGL_ES2)
glsl_version = "#version 100";
#elif defined(IMGUI_IMPL_OPENGL_ES3)
glsl_version = "#version 300 es";
#elif defined(__APPLE__)
glsl_version = "#version 150";
#else
glsl_version = "#version 130";
#endif
}
IM_ASSERT((int)strlen(glsl_version) + 2 < IM_ARRAYSIZE(bd->GlslVersionString));
strcpy(bd->GlslVersionString, glsl_version);
strcat(bd->GlslVersionString, "\n");
// Make an arbitrary GL call (we don't actually need the result)
// IF YOU GET A CRASH HERE: it probably means the OpenGL function loader didn't do its job. Let us know!
GLint current_texture;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture);
// Detect extensions we support
bd->HasClipOrigin = (bd->GlVersion >= 450);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_EXTENSIONS
GLint num_extensions = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions);
for (GLint i = 0; i < num_extensions; i++)
{
const char* extension = (const char*)glGetStringi(GL_EXTENSIONS, i);
if (extension != nullptr && strcmp(extension, "GL_ARB_clip_control") == 0)
bd->HasClipOrigin = true;
}
#endif
return true;
}
void ImGui_ImplOpenGL3_Shutdown()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != nullptr && "No renderer backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_DestroyDeviceObjects();
io.BackendRendererName = nullptr;
io.BackendRendererUserData = nullptr;
io.BackendFlags &= ~ImGuiBackendFlags_RendererHasVtxOffset;
IM_DELETE(bd);
}
void ImGui_ImplOpenGL3_NewFrame()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplOpenGL3_Init()?");
if (!bd->ShaderHandle)
ImGui_ImplOpenGL3_CreateDeviceObjects();
}
static void ImGui_ImplOpenGL3_SetupRenderState(ImDrawData* draw_data, int fb_width, int fb_height, GLuint vertex_array_object)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill
glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glDisable(GL_DEPTH_TEST);
glDisable(GL_STENCIL_TEST);
glEnable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310)
glDisable(GL_PRIMITIVE_RESTART);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
#endif
// Support for GL 4.5 rarely used glClipControl(GL_UPPER_LEFT)
#if defined(GL_CLIP_ORIGIN)
bool clip_origin_lower_left = true;
if (bd->HasClipOrigin)
{
GLenum current_clip_origin = 0; glGetIntegerv(GL_CLIP_ORIGIN, (GLint*)&current_clip_origin);
if (current_clip_origin == GL_UPPER_LEFT)
clip_origin_lower_left = false;
}
#endif
// Setup viewport, orthographic projection matrix
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps.
GL_CALL(glViewport(0, 0, (GLsizei)fb_width, (GLsizei)fb_height));
float L = draw_data->DisplayPos.x;
float R = draw_data->DisplayPos.x + draw_data->DisplaySize.x;
float T = draw_data->DisplayPos.y;
float B = draw_data->DisplayPos.y + draw_data->DisplaySize.y;
#if defined(GL_CLIP_ORIGIN)
if (!clip_origin_lower_left) { float tmp = T; T = B; B = tmp; } // Swap top and bottom if origin is upper left
#endif
const float ortho_projection[4][4] =
{
{ 2.0f/(R-L), 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/(T-B), 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{ (R+L)/(L-R), (T+B)/(B-T), 0.0f, 1.0f },
};
glUseProgram(bd->ShaderHandle);
glUniform1i(bd->AttribLocationTex, 0);
glUniformMatrix4fv(bd->AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
glBindSampler(0, 0); // We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise.
#endif
(void)vertex_array_object;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(vertex_array_object);
#endif
// Bind vertex/index buffers and setup attributes for ImDrawVert
GL_CALL(glBindBuffer(GL_ARRAY_BUFFER, bd->VboHandle));
GL_CALL(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bd->ElementsHandle));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxPos));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxUV));
GL_CALL(glEnableVertexAttribArray(bd->AttribLocationVtxColor));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxPos, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, pos)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxUV, 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, uv)));
GL_CALL(glVertexAttribPointer(bd->AttribLocationVtxColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)IM_OFFSETOF(ImDrawVert, col)));
}
// OpenGL3 Render function.
// Note that this implementation is little overcomplicated because we are saving/setting up/restoring every OpenGL state explicitly.
// This is in order to be able to run within an OpenGL engine that doesn't do so.
void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data)
{
// Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates)
int fb_width = (int)(draw_data->DisplaySize.x * draw_data->FramebufferScale.x);
int fb_height = (int)(draw_data->DisplaySize.y * draw_data->FramebufferScale.y);
if (fb_width <= 0 || fb_height <= 0)
return;
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLenum last_active_texture; glGetIntegerv(GL_ACTIVE_TEXTURE, (GLint*)&last_active_texture);
glActiveTexture(GL_TEXTURE0);
GLuint last_program; glGetIntegerv(GL_CURRENT_PROGRAM, (GLint*)&last_program);
GLuint last_texture; glGetIntegerv(GL_TEXTURE_BINDING_2D, (GLint*)&last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
GLuint last_sampler; if (bd->GlVersion >= 330 || bd->GlProfileIsES3) { glGetIntegerv(GL_SAMPLER_BINDING, (GLint*)&last_sampler); } else { last_sampler = 0; }
#endif
GLuint last_array_buffer; glGetIntegerv(GL_ARRAY_BUFFER_BINDING, (GLint*)&last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
// This is part of VAO on OpenGL 3.0+ and OpenGL ES 3.0+.
GLint last_element_array_buffer; glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &last_element_array_buffer);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_pos; last_vtx_attrib_state_pos.GetState(bd->AttribLocationVtxPos);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_uv; last_vtx_attrib_state_uv.GetState(bd->AttribLocationVtxUV);
ImGui_ImplOpenGL3_VtxAttribState last_vtx_attrib_state_color; last_vtx_attrib_state_color.GetState(bd->AttribLocationVtxColor);
#endif
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLuint last_vertex_array_object; glGetIntegerv(GL_VERTEX_ARRAY_BINDING, (GLint*)&last_vertex_array_object);
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
GLint last_polygon_mode[2]; glGetIntegerv(GL_POLYGON_MODE, last_polygon_mode);
#endif
GLint last_viewport[4]; glGetIntegerv(GL_VIEWPORT, last_viewport);
GLint last_scissor_box[4]; glGetIntegerv(GL_SCISSOR_BOX, last_scissor_box);
GLenum last_blend_src_rgb; glGetIntegerv(GL_BLEND_SRC_RGB, (GLint*)&last_blend_src_rgb);
GLenum last_blend_dst_rgb; glGetIntegerv(GL_BLEND_DST_RGB, (GLint*)&last_blend_dst_rgb);
GLenum last_blend_src_alpha; glGetIntegerv(GL_BLEND_SRC_ALPHA, (GLint*)&last_blend_src_alpha);
GLenum last_blend_dst_alpha; glGetIntegerv(GL_BLEND_DST_ALPHA, (GLint*)&last_blend_dst_alpha);
GLenum last_blend_equation_rgb; glGetIntegerv(GL_BLEND_EQUATION_RGB, (GLint*)&last_blend_equation_rgb);
GLenum last_blend_equation_alpha; glGetIntegerv(GL_BLEND_EQUATION_ALPHA, (GLint*)&last_blend_equation_alpha);
GLboolean last_enable_blend = glIsEnabled(GL_BLEND);
GLboolean last_enable_cull_face = glIsEnabled(GL_CULL_FACE);
GLboolean last_enable_depth_test = glIsEnabled(GL_DEPTH_TEST);
GLboolean last_enable_stencil_test = glIsEnabled(GL_STENCIL_TEST);
GLboolean last_enable_scissor_test = glIsEnabled(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
GLboolean last_enable_primitive_restart = (bd->GlVersion >= 310) ? glIsEnabled(GL_PRIMITIVE_RESTART) : GL_FALSE;
#endif
// Setup desired GL state
// Recreate the VAO every time (this is to easily allow multiple GL contexts to be rendered to. VAO are not shared among GL contexts)
// The renderer would actually work without any VAO bound, but then our VertexAttrib calls would overwrite the default one currently bound.
GLuint vertex_array_object = 0;
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GL_CALL(glGenVertexArrays(1, &vertex_array_object));
#endif
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
// Will project scissor/clipping rectangles into framebuffer space
ImVec2 clip_off = draw_data->DisplayPos; // (0,0) unless using multi-viewports
ImVec2 clip_scale = draw_data->FramebufferScale; // (1,1) unless using retina display which are often (2,2)
// Render command lists
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
// Upload vertex/index buffers
// - OpenGL drivers are in a very sorry state nowadays....
// During 2021 we attempted to switch from glBufferData() to orphaning+glBufferSubData() following reports
// of leaks on Intel GPU when using multi-viewports on Windows.
// - After this we kept hearing of various display corruptions issues. We started disabling on non-Intel GPU, but issues still got reported on Intel.
// - We are now back to using exclusively glBufferData(). So bd->UseBufferSubData IS ALWAYS FALSE in this code.
// We are keeping the old code path for a while in case people finding new issues may want to test the bd->UseBufferSubData path.
// - See https://github.com/ocornut/imgui/issues/4468 and please report any corruption issues.
const GLsizeiptr vtx_buffer_size = (GLsizeiptr)cmd_list->VtxBuffer.Size * (int)sizeof(ImDrawVert);
const GLsizeiptr idx_buffer_size = (GLsizeiptr)cmd_list->IdxBuffer.Size * (int)sizeof(ImDrawIdx);
if (bd->UseBufferSubData)
{
if (bd->VertexBufferSize < vtx_buffer_size)
{
bd->VertexBufferSize = vtx_buffer_size;
GL_CALL(glBufferData(GL_ARRAY_BUFFER, bd->VertexBufferSize, nullptr, GL_STREAM_DRAW));
}
if (bd->IndexBufferSize < idx_buffer_size)
{
bd->IndexBufferSize = idx_buffer_size;
GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, bd->IndexBufferSize, nullptr, GL_STREAM_DRAW));
}
GL_CALL(glBufferSubData(GL_ARRAY_BUFFER, 0, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data));
GL_CALL(glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, 0, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data));
}
else
{
GL_CALL(glBufferData(GL_ARRAY_BUFFER, vtx_buffer_size, (const GLvoid*)cmd_list->VtxBuffer.Data, GL_STREAM_DRAW));
GL_CALL(glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx_buffer_size, (const GLvoid*)cmd_list->IdxBuffer.Data, GL_STREAM_DRAW));
}
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback != nullptr)
{
// User callback, registered via ImDrawList::AddCallback()
// (ImDrawCallback_ResetRenderState is a special callback value used by the user to request the renderer to reset render state.)
if (pcmd->UserCallback == ImDrawCallback_ResetRenderState)
ImGui_ImplOpenGL3_SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object);
else
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// Project scissor/clipping rectangles into framebuffer space
ImVec2 clip_min((pcmd->ClipRect.x - clip_off.x) * clip_scale.x, (pcmd->ClipRect.y - clip_off.y) * clip_scale.y);
ImVec2 clip_max((pcmd->ClipRect.z - clip_off.x) * clip_scale.x, (pcmd->ClipRect.w - clip_off.y) * clip_scale.y);
if (clip_max.x <= clip_min.x || clip_max.y <= clip_min.y)
continue;
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
GL_CALL(glScissor((int)clip_min.x, (int)((float)fb_height - clip_max.y), (int)(clip_max.x - clip_min.x), (int)(clip_max.y - clip_min.y)));
// Bind texture, Draw
GL_CALL(glBindTexture(GL_TEXTURE_2D, (GLuint)(intptr_t)pcmd->GetTexID()));
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_VTX_OFFSET
if (bd->GlVersion >= 320)
GL_CALL(glDrawElementsBaseVertex(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx)), (GLint)pcmd->VtxOffset));
else
#endif
GL_CALL(glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, (void*)(intptr_t)(pcmd->IdxOffset * sizeof(ImDrawIdx))));
}
}
}
// Destroy the temporary VAO
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GL_CALL(glDeleteVertexArrays(1, &vertex_array_object));
#endif
// Restore modified GL state
// This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220.
if (last_program == 0 || glIsProgram(last_program)) glUseProgram(last_program);
glBindTexture(GL_TEXTURE_2D, last_texture);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_BIND_SAMPLER
if (bd->GlVersion >= 330 || bd->GlProfileIsES3)
glBindSampler(0, last_sampler);
#endif
glActiveTexture(last_active_texture);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array_object);
#endif
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifndef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, last_element_array_buffer);
last_vtx_attrib_state_pos.SetState(bd->AttribLocationVtxPos);
last_vtx_attrib_state_uv.SetState(bd->AttribLocationVtxUV);
last_vtx_attrib_state_color.SetState(bd->AttribLocationVtxColor);
#endif
glBlendEquationSeparate(last_blend_equation_rgb, last_blend_equation_alpha);
glBlendFuncSeparate(last_blend_src_rgb, last_blend_dst_rgb, last_blend_src_alpha, last_blend_dst_alpha);
if (last_enable_blend) glEnable(GL_BLEND); else glDisable(GL_BLEND);
if (last_enable_cull_face) glEnable(GL_CULL_FACE); else glDisable(GL_CULL_FACE);
if (last_enable_depth_test) glEnable(GL_DEPTH_TEST); else glDisable(GL_DEPTH_TEST);
if (last_enable_stencil_test) glEnable(GL_STENCIL_TEST); else glDisable(GL_STENCIL_TEST);
if (last_enable_scissor_test) glEnable(GL_SCISSOR_TEST); else glDisable(GL_SCISSOR_TEST);
#ifdef IMGUI_IMPL_OPENGL_MAY_HAVE_PRIMITIVE_RESTART
if (bd->GlVersion >= 310) { if (last_enable_primitive_restart) glEnable(GL_PRIMITIVE_RESTART); else glDisable(GL_PRIMITIVE_RESTART); }
#endif
#ifdef IMGUI_IMPL_HAS_POLYGON_MODE
// Desktop OpenGL 3.0 and OpenGL 3.1 had separate polygon draw modes for front-facing and back-facing faces of polygons
if (bd->GlVersion <= 310 || bd->GlProfileIsCompat)
{
glPolygonMode(GL_FRONT, (GLenum)last_polygon_mode[0]);
glPolygonMode(GL_BACK, (GLenum)last_polygon_mode[1]);
}
else
{
glPolygonMode(GL_FRONT_AND_BACK, (GLenum)last_polygon_mode[0]);
}
#endif // IMGUI_IMPL_HAS_POLYGON_MODE
glViewport(last_viewport[0], last_viewport[1], (GLsizei)last_viewport[2], (GLsizei)last_viewport[3]);
glScissor(last_scissor_box[0], last_scissor_box[1], (GLsizei)last_scissor_box[2], (GLsizei)last_scissor_box[3]);
(void)bd; // Not all compilation paths use this
}
bool ImGui_ImplOpenGL3_CreateFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Build texture atlas
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory.
// Upload texture to graphics system
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
GLint last_texture;
GL_CALL(glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture));
GL_CALL(glGenTextures(1, &bd->FontTexture));
GL_CALL(glBindTexture(GL_TEXTURE_2D, bd->FontTexture));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GL_CALL(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
#ifdef GL_UNPACK_ROW_LENGTH // Not on WebGL/ES
GL_CALL(glPixelStorei(GL_UNPACK_ROW_LENGTH, 0));
#endif
GL_CALL(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels));
// Store our identifier
io.Fonts->SetTexID((ImTextureID)(intptr_t)bd->FontTexture);
// Restore state
GL_CALL(glBindTexture(GL_TEXTURE_2D, last_texture));
return true;
}
void ImGui_ImplOpenGL3_DestroyFontsTexture()
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->FontTexture)
{
glDeleteTextures(1, &bd->FontTexture);
io.Fonts->SetTexID(0);
bd->FontTexture = 0;
}
}
// If you get an error please report on github. You may try different GL context version or GLSL version. See GL<>GLSL version table at the top of this file.
static bool CheckShader(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetShaderiv(handle, GL_COMPILE_STATUS, &status);
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to compile %s! With GLSL: %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetShaderInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
// If you get an error please report on GitHub. You may try different GL context version or GLSL version.
static bool CheckProgram(GLuint handle, const char* desc)
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
GLint status = 0, log_length = 0;
glGetProgramiv(handle, GL_LINK_STATUS, &status);
glGetProgramiv(handle, GL_INFO_LOG_LENGTH, &log_length);
if ((GLboolean)status == GL_FALSE)
fprintf(stderr, "ERROR: ImGui_ImplOpenGL3_CreateDeviceObjects: failed to link %s! With GLSL %s\n", desc, bd->GlslVersionString);
if (log_length > 1)
{
ImVector<char> buf;
buf.resize((int)(log_length + 1));
glGetProgramInfoLog(handle, log_length, nullptr, (GLchar*)buf.begin());
fprintf(stderr, "%s\n", buf.begin());
}
return (GLboolean)status == GL_TRUE;
}
bool ImGui_ImplOpenGL3_CreateDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
// Backup GL state
GLint last_texture, last_array_buffer;
glGetIntegerv(GL_TEXTURE_BINDING_2D, &last_texture);
glGetIntegerv(GL_ARRAY_BUFFER_BINDING, &last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
GLint last_vertex_array;
glGetIntegerv(GL_VERTEX_ARRAY_BINDING, &last_vertex_array);
#endif
// Parse GLSL version string
int glsl_version = 130;
sscanf(bd->GlslVersionString, "#version %d", &glsl_version);
const GLchar* vertex_shader_glsl_120 =
"uniform mat4 ProjMtx;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Color;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_130 =
"uniform mat4 ProjMtx;\n"
"in vec2 Position;\n"
"in vec2 UV;\n"
"in vec4 Color;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_300_es =
"precision highp float;\n"
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* vertex_shader_glsl_410_core =
"layout (location = 0) in vec2 Position;\n"
"layout (location = 1) in vec2 UV;\n"
"layout (location = 2) in vec4 Color;\n"
"uniform mat4 ProjMtx;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Color = Color;\n"
" gl_Position = ProjMtx * vec4(Position.xy,0,1);\n"
"}\n";
const GLchar* fragment_shader_glsl_120 =
"#ifdef GL_ES\n"
" precision mediump float;\n"
"#endif\n"
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Color;\n"
"void main()\n"
"{\n"
" gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_130 =
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_300_es =
"precision mediump float;\n"
"uniform sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
const GLchar* fragment_shader_glsl_410_core =
"in vec2 Frag_UV;\n"
"in vec4 Frag_Color;\n"
"uniform sampler2D Texture;\n"
"layout (location = 0) out vec4 Out_Color;\n"
"void main()\n"
"{\n"
" Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n"
"}\n";
// Select shaders matching our GLSL versions
const GLchar* vertex_shader = nullptr;
const GLchar* fragment_shader = nullptr;
if (glsl_version < 130)
{
vertex_shader = vertex_shader_glsl_120;
fragment_shader = fragment_shader_glsl_120;
}
else if (glsl_version >= 410)
{
vertex_shader = vertex_shader_glsl_410_core;
fragment_shader = fragment_shader_glsl_410_core;
}
else if (glsl_version == 300)
{
vertex_shader = vertex_shader_glsl_300_es;
fragment_shader = fragment_shader_glsl_300_es;
}
else
{
vertex_shader = vertex_shader_glsl_130;
fragment_shader = fragment_shader_glsl_130;
}
// Create shaders
const GLchar* vertex_shader_with_version[2] = { bd->GlslVersionString, vertex_shader };
GLuint vert_handle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vert_handle, 2, vertex_shader_with_version, nullptr);
glCompileShader(vert_handle);
CheckShader(vert_handle, "vertex shader");
const GLchar* fragment_shader_with_version[2] = { bd->GlslVersionString, fragment_shader };
GLuint frag_handle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(frag_handle, 2, fragment_shader_with_version, nullptr);
glCompileShader(frag_handle);
CheckShader(frag_handle, "fragment shader");
// Link
bd->ShaderHandle = glCreateProgram();
glAttachShader(bd->ShaderHandle, vert_handle);
glAttachShader(bd->ShaderHandle, frag_handle);
glLinkProgram(bd->ShaderHandle);
CheckProgram(bd->ShaderHandle, "shader program");
glDetachShader(bd->ShaderHandle, vert_handle);
glDetachShader(bd->ShaderHandle, frag_handle);
glDeleteShader(vert_handle);
glDeleteShader(frag_handle);
bd->AttribLocationTex = glGetUniformLocation(bd->ShaderHandle, "Texture");
bd->AttribLocationProjMtx = glGetUniformLocation(bd->ShaderHandle, "ProjMtx");
bd->AttribLocationVtxPos = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Position");
bd->AttribLocationVtxUV = (GLuint)glGetAttribLocation(bd->ShaderHandle, "UV");
bd->AttribLocationVtxColor = (GLuint)glGetAttribLocation(bd->ShaderHandle, "Color");
// Create buffers
glGenBuffers(1, &bd->VboHandle);
glGenBuffers(1, &bd->ElementsHandle);
ImGui_ImplOpenGL3_CreateFontsTexture();
// Restore modified GL state
glBindTexture(GL_TEXTURE_2D, last_texture);
glBindBuffer(GL_ARRAY_BUFFER, last_array_buffer);
#ifdef IMGUI_IMPL_OPENGL_USE_VERTEX_ARRAY
glBindVertexArray(last_vertex_array);
#endif
return true;
}
void ImGui_ImplOpenGL3_DestroyDeviceObjects()
{
ImGui_ImplOpenGL3_Data* bd = ImGui_ImplOpenGL3_GetBackendData();
if (bd->VboHandle) { glDeleteBuffers(1, &bd->VboHandle); bd->VboHandle = 0; }
if (bd->ElementsHandle) { glDeleteBuffers(1, &bd->ElementsHandle); bd->ElementsHandle = 0; }
if (bd->ShaderHandle) { glDeleteProgram(bd->ShaderHandle); bd->ShaderHandle = 0; }
ImGui_ImplOpenGL3_DestroyFontsTexture();
}
//-----------------------------------------------------------------------------
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE

View File

@@ -1,63 +0,0 @@
// dear imgui: Renderer Backend for modern OpenGL with shaders / programmatic pipeline
// - Desktop GL: 2.x 3.x 4.x
// - Embedded GL: ES 2.0 (WebGL 1.0), ES 3.0 (WebGL 2.0)
// This needs to be used along with a Platform Backend (e.g. GLFW, SDL, Win32, custom..)
// Implemented features:
// [X] Renderer: User texture binding. Use 'GLuint' OpenGL texture identifier as void*/ImTextureID. Read the FAQ about ImTextureID!
// [x] Renderer: Large meshes support (64k+ vertices) with 16-bit indices (Desktop OpenGL only).
// About WebGL/ES:
// - You need to '#define IMGUI_IMPL_OPENGL_ES2' or '#define IMGUI_IMPL_OPENGL_ES3' to use WebGL or OpenGL ES.
// - This is done automatically on iOS, Android and Emscripten targets.
// - For other targets, the define needs to be visible from the imgui_impl_opengl3.cpp compilation unit. If unsure, define globally or in imconfig.h.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// About GLSL version:
// The 'glsl_version' initialization parameter should be nullptr (default) or a "#version XXX" string.
// On computer platform the GLSL version default to "#version 130". On OpenGL ES 3 platform it defaults to "#version 300 es"
// Only override if your GL version doesn't handle this GLSL version. See GLSL version table at the top of imgui_impl_opengl3.cpp.
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
// Backend API
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_Init(const char* glsl_version = nullptr);
IMGUI_IMPL_API void ImGui_ImplOpenGL3_Shutdown();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_NewFrame();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_RenderDrawData(ImDrawData* draw_data);
// (Optional) Called by Init/NewFrame/Shutdown
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateFontsTexture();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyFontsTexture();
IMGUI_IMPL_API bool ImGui_ImplOpenGL3_CreateDeviceObjects();
IMGUI_IMPL_API void ImGui_ImplOpenGL3_DestroyDeviceObjects();
// Specific OpenGL ES versions
//#define IMGUI_IMPL_OPENGL_ES2 // Auto-detected on Emscripten
//#define IMGUI_IMPL_OPENGL_ES3 // Auto-detected on iOS/Android
// You can explicitly select GLES2 or GLES3 API by using one of the '#define IMGUI_IMPL_OPENGL_LOADER_XXX' in imconfig.h or compiler command-line.
#if !defined(IMGUI_IMPL_OPENGL_ES2) \
&& !defined(IMGUI_IMPL_OPENGL_ES3)
// Try to detect GLES on matching platforms
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if (defined(__APPLE__) && (TARGET_OS_IOS || TARGET_OS_TV)) || (defined(__ANDROID__))
#define IMGUI_IMPL_OPENGL_ES3 // iOS, Android -> GL ES 3, "#version 300 es"
#elif defined(__EMSCRIPTEN__) || defined(__amigaos4__)
#define IMGUI_IMPL_OPENGL_ES2 // Emscripten -> GL ES 2, "#version 100"
#else
// Otherwise imgui_impl_opengl3_loader.h will be used.
#endif
#endif
#endif // #ifndef IMGUI_DISABLE

View File

@@ -1,809 +0,0 @@
//-----------------------------------------------------------------------------
// About imgui_impl_opengl3_loader.h:
//
// We embed our own OpenGL loader to not require user to provide their own or to have to use ours,
// which proved to be endless problems for users.
// Our loader is custom-generated, based on gl3w but automatically filtered to only include
// enums/functions that we use in our imgui_impl_opengl3.cpp source file in order to be small.
//
// YOU SHOULD NOT NEED TO INCLUDE/USE THIS DIRECTLY. THIS IS USED BY imgui_impl_opengl3.cpp ONLY.
// THE REST OF YOUR APP SHOULD USE A DIFFERENT GL LOADER: ANY GL LOADER OF YOUR CHOICE.
//
// IF YOU GET BUILD ERRORS IN THIS FILE (commonly macro redefinitions or function redefinitions):
// IT LIKELY MEANS THAT YOU ARE BUILDING 'imgui_impl_opengl3.cpp' OR INCUDING 'imgui_impl_opengl3_loader.h'
// IN THE SAME COMPILATION UNIT AS ONE OF YOUR FILE WHICH IS USING A THIRD-PARTY OPENGL LOADER.
// (e.g. COULD HAPPEN IF YOU ARE DOING A UNITY/JUMBO BUILD, OR INCLUDING .CPP FILES FROM OTHERS)
// YOU SHOULD NOT BUILD BOTH IN THE SAME COMPILATION UNIT.
// BUT IF YOU REALLY WANT TO, you can '#define IMGUI_IMPL_OPENGL_LOADER_CUSTOM' and imgui_impl_opengl3.cpp
// WILL NOT BE USING OUR LOADER, AND INSTEAD EXPECT ANOTHER/YOUR LOADER TO BE AVAILABLE IN THE COMPILATION UNIT.
//
// Regenerate with:
// python gl3w_gen.py --output ../imgui/backends/imgui_impl_opengl3_loader.h --ref ../imgui/backends/imgui_impl_opengl3.cpp ./extra_symbols.txt
//
// More info:
// https://github.com/dearimgui/gl3w_stripped
// https://github.com/ocornut/imgui/issues/4445
//-----------------------------------------------------------------------------
/*
* This file was generated with gl3w_gen.py, part of imgl3w
* (hosted at https://github.com/dearimgui/gl3w_stripped)
*
* This is free and unencumbered software released into the public domain.
*
* Anyone is free to copy, modify, publish, use, compile, sell, or
* distribute this software, either in source code form or as a compiled
* binary, for any purpose, commercial or non-commercial, and by any
* means.
*
* In jurisdictions that recognize copyright laws, the author or authors
* of this software dedicate any and all copyright interest in the
* software to the public domain. We make this dedication for the benefit
* of the public at large and to the detriment of our heirs and
* successors. We intend this dedication to be an overt act of
* relinquishment in perpetuity of all present and future rights to this
* software under copyright law.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef __gl3w_h_
#define __gl3w_h_
// Adapted from KHR/khrplatform.h to avoid including entire file.
#ifndef __khrplatform_h_
typedef float khronos_float_t;
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
#ifdef _WIN64
typedef signed long long int khronos_intptr_t;
typedef signed long long int khronos_ssize_t;
#else
typedef signed long int khronos_intptr_t;
typedef signed long int khronos_ssize_t;
#endif
#if defined(_MSC_VER) && !defined(__clang__)
typedef signed __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#elif (defined(__clang__) || defined(__GNUC__)) && (__cplusplus < 201100)
#include <stdint.h>
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#else
typedef signed long long khronos_int64_t;
typedef unsigned long long khronos_uint64_t;
#endif
#endif // __khrplatform_h_
#ifndef __gl_glcorearb_h_
#define __gl_glcorearb_h_ 1
#ifdef __cplusplus
extern "C" {
#endif
/*
** Copyright 2013-2020 The Khronos Group Inc.
** SPDX-License-Identifier: MIT
**
** This header is generated from the Khronos OpenGL / OpenGL ES XML
** API Registry. The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** https://github.com/KhronosGroup/OpenGL-Registry
*/
#if defined(_WIN32) && !defined(APIENTRY) && !defined(__CYGWIN__) && !defined(__SCITECH_SNAP__)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
#endif
#ifndef APIENTRY
#define APIENTRY
#endif
#ifndef APIENTRYP
#define APIENTRYP APIENTRY *
#endif
#ifndef GLAPI
#define GLAPI extern
#endif
/* glcorearb.h is for use with OpenGL core profile implementations.
** It should should be placed in the same directory as gl.h and
** included as <GL/glcorearb.h>.
**
** glcorearb.h includes only APIs in the latest OpenGL core profile
** implementation together with APIs in newer ARB extensions which
** can be supported by the core profile. It does not, and never will
** include functionality removed from the core profile, such as
** fixed-function vertex and fragment processing.
**
** Do not #include both <GL/glcorearb.h> and either of <GL/gl.h> or
** <GL/glext.h> in the same source file.
*/
/* Generated C header for:
* API: gl
* Profile: core
* Versions considered: .*
* Versions emitted: .*
* Default extensions included: glcore
* Additional extensions included: _nomatch_^
* Extensions removed: _nomatch_^
*/
#ifndef GL_VERSION_1_0
typedef void GLvoid;
typedef unsigned int GLenum;
typedef khronos_float_t GLfloat;
typedef int GLint;
typedef int GLsizei;
typedef unsigned int GLbitfield;
typedef double GLdouble;
typedef unsigned int GLuint;
typedef unsigned char GLboolean;
typedef khronos_uint8_t GLubyte;
#define GL_COLOR_BUFFER_BIT 0x00004000
#define GL_FALSE 0
#define GL_TRUE 1
#define GL_TRIANGLES 0x0004
#define GL_ONE 1
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_FRONT 0x0404
#define GL_BACK 0x0405
#define GL_FRONT_AND_BACK 0x0408
#define GL_POLYGON_MODE 0x0B40
#define GL_CULL_FACE 0x0B44
#define GL_DEPTH_TEST 0x0B71
#define GL_STENCIL_TEST 0x0B90
#define GL_VIEWPORT 0x0BA2
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_BOX 0x0C10
#define GL_SCISSOR_TEST 0x0C11
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_TEXTURE_2D 0x0DE1
#define GL_UNSIGNED_BYTE 0x1401
#define GL_UNSIGNED_SHORT 0x1403
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_RGBA 0x1908
#define GL_FILL 0x1B02
#define GL_VENDOR 0x1F00
#define GL_RENDERER 0x1F01
#define GL_VERSION 0x1F02
#define GL_EXTENSIONS 0x1F03
#define GL_LINEAR 0x2601
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
typedef void (APIENTRYP PFNGLPOLYGONMODEPROC) (GLenum face, GLenum mode);
typedef void (APIENTRYP PFNGLSCISSORPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
typedef void (APIENTRYP PFNGLTEXPARAMETERIPROC) (GLenum target, GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLTEXIMAGE2DPROC) (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
typedef void (APIENTRYP PFNGLCLEARPROC) (GLbitfield mask);
typedef void (APIENTRYP PFNGLCLEARCOLORPROC) (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
typedef void (APIENTRYP PFNGLDISABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLENABLEPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLFLUSHPROC) (void);
typedef void (APIENTRYP PFNGLPIXELSTOREIPROC) (GLenum pname, GLint param);
typedef void (APIENTRYP PFNGLREADPIXELSPROC) (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
typedef GLenum (APIENTRYP PFNGLGETERRORPROC) (void);
typedef void (APIENTRYP PFNGLGETINTEGERVPROC) (GLenum pname, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGPROC) (GLenum name);
typedef GLboolean (APIENTRYP PFNGLISENABLEDPROC) (GLenum cap);
typedef void (APIENTRYP PFNGLVIEWPORTPROC) (GLint x, GLint y, GLsizei width, GLsizei height);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glPolygonMode (GLenum face, GLenum mode);
GLAPI void APIENTRY glScissor (GLint x, GLint y, GLsizei width, GLsizei height);
GLAPI void APIENTRY glTexParameteri (GLenum target, GLenum pname, GLint param);
GLAPI void APIENTRY glTexImage2D (GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels);
GLAPI void APIENTRY glClear (GLbitfield mask);
GLAPI void APIENTRY glClearColor (GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
GLAPI void APIENTRY glDisable (GLenum cap);
GLAPI void APIENTRY glEnable (GLenum cap);
GLAPI void APIENTRY glFlush (void);
GLAPI void APIENTRY glPixelStorei (GLenum pname, GLint param);
GLAPI void APIENTRY glReadPixels (GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels);
GLAPI GLenum APIENTRY glGetError (void);
GLAPI void APIENTRY glGetIntegerv (GLenum pname, GLint *data);
GLAPI const GLubyte *APIENTRY glGetString (GLenum name);
GLAPI GLboolean APIENTRY glIsEnabled (GLenum cap);
GLAPI void APIENTRY glViewport (GLint x, GLint y, GLsizei width, GLsizei height);
#endif
#endif /* GL_VERSION_1_0 */
#ifndef GL_VERSION_1_1
typedef khronos_float_t GLclampf;
typedef double GLclampd;
#define GL_TEXTURE_BINDING_2D 0x8069
typedef void (APIENTRYP PFNGLDRAWELEMENTSPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices);
typedef void (APIENTRYP PFNGLBINDTEXTUREPROC) (GLenum target, GLuint texture);
typedef void (APIENTRYP PFNGLDELETETEXTURESPROC) (GLsizei n, const GLuint *textures);
typedef void (APIENTRYP PFNGLGENTEXTURESPROC) (GLsizei n, GLuint *textures);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElements (GLenum mode, GLsizei count, GLenum type, const void *indices);
GLAPI void APIENTRY glBindTexture (GLenum target, GLuint texture);
GLAPI void APIENTRY glDeleteTextures (GLsizei n, const GLuint *textures);
GLAPI void APIENTRY glGenTextures (GLsizei n, GLuint *textures);
#endif
#endif /* GL_VERSION_1_1 */
#ifndef GL_VERSION_1_3
#define GL_TEXTURE0 0x84C0
#define GL_ACTIVE_TEXTURE 0x84E0
typedef void (APIENTRYP PFNGLACTIVETEXTUREPROC) (GLenum texture);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glActiveTexture (GLenum texture);
#endif
#endif /* GL_VERSION_1_3 */
#ifndef GL_VERSION_1_4
#define GL_BLEND_DST_RGB 0x80C8
#define GL_BLEND_SRC_RGB 0x80C9
#define GL_BLEND_DST_ALPHA 0x80CA
#define GL_BLEND_SRC_ALPHA 0x80CB
#define GL_FUNC_ADD 0x8006
typedef void (APIENTRYP PFNGLBLENDFUNCSEPARATEPROC) (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
typedef void (APIENTRYP PFNGLBLENDEQUATIONPROC) (GLenum mode);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendFuncSeparate (GLenum sfactorRGB, GLenum dfactorRGB, GLenum sfactorAlpha, GLenum dfactorAlpha);
GLAPI void APIENTRY glBlendEquation (GLenum mode);
#endif
#endif /* GL_VERSION_1_4 */
#ifndef GL_VERSION_1_5
typedef khronos_ssize_t GLsizeiptr;
typedef khronos_intptr_t GLintptr;
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_ARRAY_BUFFER_BINDING 0x8894
#define GL_ELEMENT_ARRAY_BUFFER_BINDING 0x8895
#define GL_STREAM_DRAW 0x88E0
typedef void (APIENTRYP PFNGLBINDBUFFERPROC) (GLenum target, GLuint buffer);
typedef void (APIENTRYP PFNGLDELETEBUFFERSPROC) (GLsizei n, const GLuint *buffers);
typedef void (APIENTRYP PFNGLGENBUFFERSPROC) (GLsizei n, GLuint *buffers);
typedef void (APIENTRYP PFNGLBUFFERDATAPROC) (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
typedef void (APIENTRYP PFNGLBUFFERSUBDATAPROC) (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindBuffer (GLenum target, GLuint buffer);
GLAPI void APIENTRY glDeleteBuffers (GLsizei n, const GLuint *buffers);
GLAPI void APIENTRY glGenBuffers (GLsizei n, GLuint *buffers);
GLAPI void APIENTRY glBufferData (GLenum target, GLsizeiptr size, const void *data, GLenum usage);
GLAPI void APIENTRY glBufferSubData (GLenum target, GLintptr offset, GLsizeiptr size, const void *data);
#endif
#endif /* GL_VERSION_1_5 */
#ifndef GL_VERSION_2_0
typedef char GLchar;
typedef khronos_int16_t GLshort;
typedef khronos_int8_t GLbyte;
typedef khronos_uint16_t GLushort;
#define GL_BLEND_EQUATION_RGB 0x8009
#define GL_VERTEX_ATTRIB_ARRAY_ENABLED 0x8622
#define GL_VERTEX_ATTRIB_ARRAY_SIZE 0x8623
#define GL_VERTEX_ATTRIB_ARRAY_STRIDE 0x8624
#define GL_VERTEX_ATTRIB_ARRAY_TYPE 0x8625
#define GL_VERTEX_ATTRIB_ARRAY_POINTER 0x8645
#define GL_BLEND_EQUATION_ALPHA 0x883D
#define GL_VERTEX_ATTRIB_ARRAY_NORMALIZED 0x886A
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_INFO_LOG_LENGTH 0x8B84
#define GL_CURRENT_PROGRAM 0x8B8D
#define GL_UPPER_LEFT 0x8CA2
typedef void (APIENTRYP PFNGLBLENDEQUATIONSEPARATEPROC) (GLenum modeRGB, GLenum modeAlpha);
typedef void (APIENTRYP PFNGLATTACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLCOMPILESHADERPROC) (GLuint shader);
typedef GLuint (APIENTRYP PFNGLCREATEPROGRAMPROC) (void);
typedef GLuint (APIENTRYP PFNGLCREATESHADERPROC) (GLenum type);
typedef void (APIENTRYP PFNGLDELETEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLDELETESHADERPROC) (GLuint shader);
typedef void (APIENTRYP PFNGLDETACHSHADERPROC) (GLuint program, GLuint shader);
typedef void (APIENTRYP PFNGLDISABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef void (APIENTRYP PFNGLENABLEVERTEXATTRIBARRAYPROC) (GLuint index);
typedef GLint (APIENTRYP PFNGLGETATTRIBLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETPROGRAMIVPROC) (GLuint program, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETPROGRAMINFOLOGPROC) (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef void (APIENTRYP PFNGLGETSHADERIVPROC) (GLuint shader, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETSHADERINFOLOGPROC) (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
typedef GLint (APIENTRYP PFNGLGETUNIFORMLOCATIONPROC) (GLuint program, const GLchar *name);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBIVPROC) (GLuint index, GLenum pname, GLint *params);
typedef void (APIENTRYP PFNGLGETVERTEXATTRIBPOINTERVPROC) (GLuint index, GLenum pname, void **pointer);
typedef GLboolean (APIENTRYP PFNGLISPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLLINKPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLSHADERSOURCEPROC) (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
typedef void (APIENTRYP PFNGLUSEPROGRAMPROC) (GLuint program);
typedef void (APIENTRYP PFNGLUNIFORM1IPROC) (GLint location, GLint v0);
typedef void (APIENTRYP PFNGLUNIFORMMATRIX4FVPROC) (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
typedef void (APIENTRYP PFNGLVERTEXATTRIBPOINTERPROC) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBlendEquationSeparate (GLenum modeRGB, GLenum modeAlpha);
GLAPI void APIENTRY glAttachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glCompileShader (GLuint shader);
GLAPI GLuint APIENTRY glCreateProgram (void);
GLAPI GLuint APIENTRY glCreateShader (GLenum type);
GLAPI void APIENTRY glDeleteProgram (GLuint program);
GLAPI void APIENTRY glDeleteShader (GLuint shader);
GLAPI void APIENTRY glDetachShader (GLuint program, GLuint shader);
GLAPI void APIENTRY glDisableVertexAttribArray (GLuint index);
GLAPI void APIENTRY glEnableVertexAttribArray (GLuint index);
GLAPI GLint APIENTRY glGetAttribLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetProgramiv (GLuint program, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetProgramInfoLog (GLuint program, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI void APIENTRY glGetShaderiv (GLuint shader, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetShaderInfoLog (GLuint shader, GLsizei bufSize, GLsizei *length, GLchar *infoLog);
GLAPI GLint APIENTRY glGetUniformLocation (GLuint program, const GLchar *name);
GLAPI void APIENTRY glGetVertexAttribiv (GLuint index, GLenum pname, GLint *params);
GLAPI void APIENTRY glGetVertexAttribPointerv (GLuint index, GLenum pname, void **pointer);
GLAPI GLboolean APIENTRY glIsProgram (GLuint program);
GLAPI void APIENTRY glLinkProgram (GLuint program);
GLAPI void APIENTRY glShaderSource (GLuint shader, GLsizei count, const GLchar *const*string, const GLint *length);
GLAPI void APIENTRY glUseProgram (GLuint program);
GLAPI void APIENTRY glUniform1i (GLint location, GLint v0);
GLAPI void APIENTRY glUniformMatrix4fv (GLint location, GLsizei count, GLboolean transpose, const GLfloat *value);
GLAPI void APIENTRY glVertexAttribPointer (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *pointer);
#endif
#endif /* GL_VERSION_2_0 */
#ifndef GL_VERSION_3_0
typedef khronos_uint16_t GLhalf;
#define GL_MAJOR_VERSION 0x821B
#define GL_MINOR_VERSION 0x821C
#define GL_NUM_EXTENSIONS 0x821D
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#define GL_VERTEX_ARRAY_BINDING 0x85B5
typedef void (APIENTRYP PFNGLGETBOOLEANI_VPROC) (GLenum target, GLuint index, GLboolean *data);
typedef void (APIENTRYP PFNGLGETINTEGERI_VPROC) (GLenum target, GLuint index, GLint *data);
typedef const GLubyte *(APIENTRYP PFNGLGETSTRINGIPROC) (GLenum name, GLuint index);
typedef void (APIENTRYP PFNGLBINDVERTEXARRAYPROC) (GLuint array);
typedef void (APIENTRYP PFNGLDELETEVERTEXARRAYSPROC) (GLsizei n, const GLuint *arrays);
typedef void (APIENTRYP PFNGLGENVERTEXARRAYSPROC) (GLsizei n, GLuint *arrays);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI const GLubyte *APIENTRY glGetStringi (GLenum name, GLuint index);
GLAPI void APIENTRY glBindVertexArray (GLuint array);
GLAPI void APIENTRY glDeleteVertexArrays (GLsizei n, const GLuint *arrays);
GLAPI void APIENTRY glGenVertexArrays (GLsizei n, GLuint *arrays);
#endif
#endif /* GL_VERSION_3_0 */
#ifndef GL_VERSION_3_1
#define GL_VERSION_3_1 1
#define GL_PRIMITIVE_RESTART 0x8F9D
#endif /* GL_VERSION_3_1 */
#ifndef GL_VERSION_3_2
#define GL_VERSION_3_2 1
typedef struct __GLsync *GLsync;
typedef khronos_uint64_t GLuint64;
typedef khronos_int64_t GLint64;
#define GL_CONTEXT_COMPATIBILITY_PROFILE_BIT 0x00000002
#define GL_CONTEXT_PROFILE_MASK 0x9126
typedef void (APIENTRYP PFNGLDRAWELEMENTSBASEVERTEXPROC) (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
typedef void (APIENTRYP PFNGLGETINTEGER64I_VPROC) (GLenum target, GLuint index, GLint64 *data);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glDrawElementsBaseVertex (GLenum mode, GLsizei count, GLenum type, const void *indices, GLint basevertex);
#endif
#endif /* GL_VERSION_3_2 */
#ifndef GL_VERSION_3_3
#define GL_VERSION_3_3 1
#define GL_SAMPLER_BINDING 0x8919
typedef void (APIENTRYP PFNGLBINDSAMPLERPROC) (GLuint unit, GLuint sampler);
#ifdef GL_GLEXT_PROTOTYPES
GLAPI void APIENTRY glBindSampler (GLuint unit, GLuint sampler);
#endif
#endif /* GL_VERSION_3_3 */
#ifndef GL_VERSION_4_1
typedef void (APIENTRYP PFNGLGETFLOATI_VPROC) (GLenum target, GLuint index, GLfloat *data);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VPROC) (GLenum target, GLuint index, GLdouble *data);
#endif /* GL_VERSION_4_1 */
#ifndef GL_VERSION_4_3
typedef void (APIENTRY *GLDEBUGPROC)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_VERSION_4_3 */
#ifndef GL_VERSION_4_5
#define GL_CLIP_ORIGIN 0x935C
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint *param);
typedef void (APIENTRYP PFNGLGETTRANSFORMFEEDBACKI64_VPROC) (GLuint xfb, GLenum pname, GLuint index, GLint64 *param);
#endif /* GL_VERSION_4_5 */
#ifndef GL_ARB_bindless_texture
typedef khronos_uint64_t GLuint64EXT;
#endif /* GL_ARB_bindless_texture */
#ifndef GL_ARB_cl_event
struct _cl_context;
struct _cl_event;
#endif /* GL_ARB_cl_event */
#ifndef GL_ARB_clip_control
#define GL_ARB_clip_control 1
#endif /* GL_ARB_clip_control */
#ifndef GL_ARB_debug_output
typedef void (APIENTRY *GLDEBUGPROCARB)(GLenum source,GLenum type,GLuint id,GLenum severity,GLsizei length,const GLchar *message,const void *userParam);
#endif /* GL_ARB_debug_output */
#ifndef GL_EXT_EGL_image_storage
typedef void *GLeglImageOES;
#endif /* GL_EXT_EGL_image_storage */
#ifndef GL_EXT_direct_state_access
typedef void (APIENTRYP PFNGLGETFLOATI_VEXTPROC) (GLenum pname, GLuint index, GLfloat *params);
typedef void (APIENTRYP PFNGLGETDOUBLEI_VEXTPROC) (GLenum pname, GLuint index, GLdouble *params);
typedef void (APIENTRYP PFNGLGETPOINTERI_VEXTPROC) (GLenum pname, GLuint index, void **params);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYINTEGERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, GLint *param);
typedef void (APIENTRYP PFNGLGETVERTEXARRAYPOINTERI_VEXTPROC) (GLuint vaobj, GLuint index, GLenum pname, void **param);
#endif /* GL_EXT_direct_state_access */
#ifndef GL_NV_draw_vulkan_image
typedef void (APIENTRY *GLVULKANPROCNV)(void);
#endif /* GL_NV_draw_vulkan_image */
#ifndef GL_NV_gpu_shader5
typedef khronos_int64_t GLint64EXT;
#endif /* GL_NV_gpu_shader5 */
#ifndef GL_NV_vertex_buffer_unified_memory
typedef void (APIENTRYP PFNGLGETINTEGERUI64I_VNVPROC) (GLenum value, GLuint index, GLuint64EXT *result);
#endif /* GL_NV_vertex_buffer_unified_memory */
#ifdef __cplusplus
}
#endif
#endif
#ifndef GL3W_API
#define GL3W_API
#endif
#ifndef __gl_h_
#define __gl_h_
#endif
#ifdef __cplusplus
extern "C" {
#endif
#define GL3W_OK 0
#define GL3W_ERROR_INIT -1
#define GL3W_ERROR_LIBRARY_OPEN -2
#define GL3W_ERROR_OPENGL_VERSION -3
typedef void (*GL3WglProc)(void);
typedef GL3WglProc (*GL3WGetProcAddressProc)(const char *proc);
/* gl3w api */
GL3W_API int imgl3wInit(void);
GL3W_API int imgl3wInit2(GL3WGetProcAddressProc proc);
GL3W_API int imgl3wIsSupported(int major, int minor);
GL3W_API GL3WglProc imgl3wGetProcAddress(const char *proc);
/* gl3w internal state */
union GL3WProcs {
GL3WglProc ptr[59];
struct {
PFNGLACTIVETEXTUREPROC ActiveTexture;
PFNGLATTACHSHADERPROC AttachShader;
PFNGLBINDBUFFERPROC BindBuffer;
PFNGLBINDSAMPLERPROC BindSampler;
PFNGLBINDTEXTUREPROC BindTexture;
PFNGLBINDVERTEXARRAYPROC BindVertexArray;
PFNGLBLENDEQUATIONPROC BlendEquation;
PFNGLBLENDEQUATIONSEPARATEPROC BlendEquationSeparate;
PFNGLBLENDFUNCSEPARATEPROC BlendFuncSeparate;
PFNGLBUFFERDATAPROC BufferData;
PFNGLBUFFERSUBDATAPROC BufferSubData;
PFNGLCLEARPROC Clear;
PFNGLCLEARCOLORPROC ClearColor;
PFNGLCOMPILESHADERPROC CompileShader;
PFNGLCREATEPROGRAMPROC CreateProgram;
PFNGLCREATESHADERPROC CreateShader;
PFNGLDELETEBUFFERSPROC DeleteBuffers;
PFNGLDELETEPROGRAMPROC DeleteProgram;
PFNGLDELETESHADERPROC DeleteShader;
PFNGLDELETETEXTURESPROC DeleteTextures;
PFNGLDELETEVERTEXARRAYSPROC DeleteVertexArrays;
PFNGLDETACHSHADERPROC DetachShader;
PFNGLDISABLEPROC Disable;
PFNGLDISABLEVERTEXATTRIBARRAYPROC DisableVertexAttribArray;
PFNGLDRAWELEMENTSPROC DrawElements;
PFNGLDRAWELEMENTSBASEVERTEXPROC DrawElementsBaseVertex;
PFNGLENABLEPROC Enable;
PFNGLENABLEVERTEXATTRIBARRAYPROC EnableVertexAttribArray;
PFNGLFLUSHPROC Flush;
PFNGLGENBUFFERSPROC GenBuffers;
PFNGLGENTEXTURESPROC GenTextures;
PFNGLGENVERTEXARRAYSPROC GenVertexArrays;
PFNGLGETATTRIBLOCATIONPROC GetAttribLocation;
PFNGLGETERRORPROC GetError;
PFNGLGETINTEGERVPROC GetIntegerv;
PFNGLGETPROGRAMINFOLOGPROC GetProgramInfoLog;
PFNGLGETPROGRAMIVPROC GetProgramiv;
PFNGLGETSHADERINFOLOGPROC GetShaderInfoLog;
PFNGLGETSHADERIVPROC GetShaderiv;
PFNGLGETSTRINGPROC GetString;
PFNGLGETSTRINGIPROC GetStringi;
PFNGLGETUNIFORMLOCATIONPROC GetUniformLocation;
PFNGLGETVERTEXATTRIBPOINTERVPROC GetVertexAttribPointerv;
PFNGLGETVERTEXATTRIBIVPROC GetVertexAttribiv;
PFNGLISENABLEDPROC IsEnabled;
PFNGLISPROGRAMPROC IsProgram;
PFNGLLINKPROGRAMPROC LinkProgram;
PFNGLPIXELSTOREIPROC PixelStorei;
PFNGLPOLYGONMODEPROC PolygonMode;
PFNGLREADPIXELSPROC ReadPixels;
PFNGLSCISSORPROC Scissor;
PFNGLSHADERSOURCEPROC ShaderSource;
PFNGLTEXIMAGE2DPROC TexImage2D;
PFNGLTEXPARAMETERIPROC TexParameteri;
PFNGLUNIFORM1IPROC Uniform1i;
PFNGLUNIFORMMATRIX4FVPROC UniformMatrix4fv;
PFNGLUSEPROGRAMPROC UseProgram;
PFNGLVERTEXATTRIBPOINTERPROC VertexAttribPointer;
PFNGLVIEWPORTPROC Viewport;
} gl;
};
GL3W_API extern union GL3WProcs imgl3wProcs;
/* OpenGL functions */
#define glActiveTexture imgl3wProcs.gl.ActiveTexture
#define glAttachShader imgl3wProcs.gl.AttachShader
#define glBindBuffer imgl3wProcs.gl.BindBuffer
#define glBindSampler imgl3wProcs.gl.BindSampler
#define glBindTexture imgl3wProcs.gl.BindTexture
#define glBindVertexArray imgl3wProcs.gl.BindVertexArray
#define glBlendEquation imgl3wProcs.gl.BlendEquation
#define glBlendEquationSeparate imgl3wProcs.gl.BlendEquationSeparate
#define glBlendFuncSeparate imgl3wProcs.gl.BlendFuncSeparate
#define glBufferData imgl3wProcs.gl.BufferData
#define glBufferSubData imgl3wProcs.gl.BufferSubData
#define glClear imgl3wProcs.gl.Clear
#define glClearColor imgl3wProcs.gl.ClearColor
#define glCompileShader imgl3wProcs.gl.CompileShader
#define glCreateProgram imgl3wProcs.gl.CreateProgram
#define glCreateShader imgl3wProcs.gl.CreateShader
#define glDeleteBuffers imgl3wProcs.gl.DeleteBuffers
#define glDeleteProgram imgl3wProcs.gl.DeleteProgram
#define glDeleteShader imgl3wProcs.gl.DeleteShader
#define glDeleteTextures imgl3wProcs.gl.DeleteTextures
#define glDeleteVertexArrays imgl3wProcs.gl.DeleteVertexArrays
#define glDetachShader imgl3wProcs.gl.DetachShader
#define glDisable imgl3wProcs.gl.Disable
#define glDisableVertexAttribArray imgl3wProcs.gl.DisableVertexAttribArray
#define glDrawElements imgl3wProcs.gl.DrawElements
#define glDrawElementsBaseVertex imgl3wProcs.gl.DrawElementsBaseVertex
#define glEnable imgl3wProcs.gl.Enable
#define glEnableVertexAttribArray imgl3wProcs.gl.EnableVertexAttribArray
#define glFlush imgl3wProcs.gl.Flush
#define glGenBuffers imgl3wProcs.gl.GenBuffers
#define glGenTextures imgl3wProcs.gl.GenTextures
#define glGenVertexArrays imgl3wProcs.gl.GenVertexArrays
#define glGetAttribLocation imgl3wProcs.gl.GetAttribLocation
#define glGetError imgl3wProcs.gl.GetError
#define glGetIntegerv imgl3wProcs.gl.GetIntegerv
#define glGetProgramInfoLog imgl3wProcs.gl.GetProgramInfoLog
#define glGetProgramiv imgl3wProcs.gl.GetProgramiv
#define glGetShaderInfoLog imgl3wProcs.gl.GetShaderInfoLog
#define glGetShaderiv imgl3wProcs.gl.GetShaderiv
#define glGetString imgl3wProcs.gl.GetString
#define glGetStringi imgl3wProcs.gl.GetStringi
#define glGetUniformLocation imgl3wProcs.gl.GetUniformLocation
#define glGetVertexAttribPointerv imgl3wProcs.gl.GetVertexAttribPointerv
#define glGetVertexAttribiv imgl3wProcs.gl.GetVertexAttribiv
#define glIsEnabled imgl3wProcs.gl.IsEnabled
#define glIsProgram imgl3wProcs.gl.IsProgram
#define glLinkProgram imgl3wProcs.gl.LinkProgram
#define glPixelStorei imgl3wProcs.gl.PixelStorei
#define glPolygonMode imgl3wProcs.gl.PolygonMode
#define glReadPixels imgl3wProcs.gl.ReadPixels
#define glScissor imgl3wProcs.gl.Scissor
#define glShaderSource imgl3wProcs.gl.ShaderSource
#define glTexImage2D imgl3wProcs.gl.TexImage2D
#define glTexParameteri imgl3wProcs.gl.TexParameteri
#define glUniform1i imgl3wProcs.gl.Uniform1i
#define glUniformMatrix4fv imgl3wProcs.gl.UniformMatrix4fv
#define glUseProgram imgl3wProcs.gl.UseProgram
#define glVertexAttribPointer imgl3wProcs.gl.VertexAttribPointer
#define glViewport imgl3wProcs.gl.Viewport
#ifdef __cplusplus
}
#endif
#endif
#ifdef IMGL3W_IMPL
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#if defined(_WIN32)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
#endif
#include <windows.h>
static HMODULE libgl;
typedef PROC(__stdcall* GL3WglGetProcAddr)(LPCSTR);
static GL3WglGetProcAddr wgl_get_proc_address;
static int open_libgl(void)
{
libgl = LoadLibraryA("opengl32.dll");
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
wgl_get_proc_address = (GL3WglGetProcAddr)GetProcAddress(libgl, "wglGetProcAddress");
return GL3W_OK;
}
static void close_libgl(void) { FreeLibrary(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = (GL3WglProc)wgl_get_proc_address(proc);
if (!res)
res = (GL3WglProc)GetProcAddress(libgl, proc);
return res;
}
#elif defined(__APPLE__)
#include <dlfcn.h>
static void *libgl;
static int open_libgl(void)
{
libgl = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#else
#include <dlfcn.h>
static void *libgl;
static GL3WglProc (*glx_get_proc_address)(const GLubyte *);
static int open_libgl(void)
{
libgl = dlopen("libGL.so.1", RTLD_LAZY | RTLD_LOCAL);
if (!libgl)
return GL3W_ERROR_LIBRARY_OPEN;
*(void **)(&glx_get_proc_address) = dlsym(libgl, "glXGetProcAddressARB");
return GL3W_OK;
}
static void close_libgl(void) { dlclose(libgl); }
static GL3WglProc get_proc(const char *proc)
{
GL3WglProc res;
res = glx_get_proc_address((const GLubyte *)proc);
if (!res)
*(void **)(&res) = dlsym(libgl, proc);
return res;
}
#endif
static struct { int major, minor; } version;
static int parse_version(void)
{
if (!glGetIntegerv)
return GL3W_ERROR_INIT;
glGetIntegerv(GL_MAJOR_VERSION, &version.major);
glGetIntegerv(GL_MINOR_VERSION, &version.minor);
if (version.major == 0 && version.minor == 0)
{
// Query GL_VERSION in desktop GL 2.x, the string will start with "<major>.<minor>"
if (const char* gl_version = (const char*)glGetString(GL_VERSION))
sscanf(gl_version, "%d.%d", &version.major, &version.minor);
}
if (version.major < 2)
return GL3W_ERROR_OPENGL_VERSION;
return GL3W_OK;
}
static void load_procs(GL3WGetProcAddressProc proc);
int imgl3wInit(void)
{
int res = open_libgl();
if (res)
return res;
atexit(close_libgl);
return imgl3wInit2(get_proc);
}
int imgl3wInit2(GL3WGetProcAddressProc proc)
{
load_procs(proc);
return parse_version();
}
int imgl3wIsSupported(int major, int minor)
{
if (major < 2)
return 0;
if (version.major == major)
return version.minor >= minor;
return version.major >= major;
}
GL3WglProc imgl3wGetProcAddress(const char *proc) { return get_proc(proc); }
static const char *proc_names[] = {
"glActiveTexture",
"glAttachShader",
"glBindBuffer",
"glBindSampler",
"glBindTexture",
"glBindVertexArray",
"glBlendEquation",
"glBlendEquationSeparate",
"glBlendFuncSeparate",
"glBufferData",
"glBufferSubData",
"glClear",
"glClearColor",
"glCompileShader",
"glCreateProgram",
"glCreateShader",
"glDeleteBuffers",
"glDeleteProgram",
"glDeleteShader",
"glDeleteTextures",
"glDeleteVertexArrays",
"glDetachShader",
"glDisable",
"glDisableVertexAttribArray",
"glDrawElements",
"glDrawElementsBaseVertex",
"glEnable",
"glEnableVertexAttribArray",
"glFlush",
"glGenBuffers",
"glGenTextures",
"glGenVertexArrays",
"glGetAttribLocation",
"glGetError",
"glGetIntegerv",
"glGetProgramInfoLog",
"glGetProgramiv",
"glGetShaderInfoLog",
"glGetShaderiv",
"glGetString",
"glGetStringi",
"glGetUniformLocation",
"glGetVertexAttribPointerv",
"glGetVertexAttribiv",
"glIsEnabled",
"glIsProgram",
"glLinkProgram",
"glPixelStorei",
"glPolygonMode",
"glReadPixels",
"glScissor",
"glShaderSource",
"glTexImage2D",
"glTexParameteri",
"glUniform1i",
"glUniformMatrix4fv",
"glUseProgram",
"glVertexAttribPointer",
"glViewport",
};
GL3W_API union GL3WProcs imgl3wProcs;
static void load_procs(GL3WGetProcAddressProc proc)
{
size_t i;
for (i = 0; i < ARRAY_SIZE(proc_names); i++)
imgl3wProcs.ptr[i] = proc(proc_names[i]);
}
#ifdef __cplusplus
}
#endif
#endif

View File

@@ -1,656 +0,0 @@
// dear imgui: Platform Backend for SDL2
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// (Prefer SDL 2.0.5+ for full feature support.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
// CHANGELOG
// (minor and older changes stripped away, please see git history for details)
// 2023-04-06: Inputs: Avoid calling SDL_StartTextInput()/SDL_StopTextInput() as they don't only pertain to IME. It's unclear exactly what their relation is to IME. (#6306)
// 2023-04-04: Inputs: Added support for io.AddMouseSourceEvent() to discriminate ImGuiMouseSource_Mouse/ImGuiMouseSource_TouchScreen. (#2702)
// 2023-02-23: Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. (#6189, #6114, #3644)
// 2023-02-07: Implement IME handler (io.SetPlatformImeDataFn will call SDL_SetTextInputRect()/SDL_StartTextInput()).
// 2023-02-07: *BREAKING CHANGE* Renamed this backend file from imgui_impl_sdl.cpp/.h to imgui_impl_sdl2.cpp/.h in prevision for the future release of SDL3.
// 2023-02-02: Avoid calling SDL_SetCursor() when cursor has not changed, as the function is surprisingly costly on Mac with latest SDL (may be fixed in next SDL version).
// 2023-02-02: Added support for SDL 2.0.18+ preciseX/preciseY mouse wheel data for smooth scrolling + Scaling X value on Emscripten (bug?). (#4019, #6096)
// 2023-02-02: Removed SDL_MOUSEWHEEL value clamping, as values seem correct in latest Emscripten. (#4019)
// 2023-02-01: Flipping SDL_MOUSEWHEEL 'wheel.x' value to match other backends and offer consistent horizontal scrolling direction. (#4019, #6096, #1463)
// 2022-10-11: Using 'nullptr' instead of 'NULL' as per our switch to C++11.
// 2022-09-26: Inputs: Disable SDL 2.0.22 new "auto capture" (SDL_HINT_MOUSE_AUTO_CAPTURE) which prevents drag and drop across windows for multi-viewport support + don't capture when drag and dropping. (#5710)
// 2022-09-26: Inputs: Renamed ImGuiKey_ModXXX introduced in 1.87 to ImGuiMod_XXX (old names still supported).
// 2022-03-22: Inputs: Fix mouse position issues when dragging outside of boundaries. SDL_CaptureMouse() erroneously still gives out LEAVE events when hovering OS decorations.
// 2022-03-22: Inputs: Added support for extra mouse buttons (SDL_BUTTON_X1/SDL_BUTTON_X2).
// 2022-02-04: Added SDL_Renderer* parameter to ImGui_ImplSDL2_InitForSDLRenderer(), so we can use SDL_GetRendererOutputSize() instead of SDL_GL_GetDrawableSize() when bound to a SDL_Renderer.
// 2022-01-26: Inputs: replaced short-lived io.AddKeyModsEvent() (added two weeks ago) with io.AddKeyEvent() using ImGuiKey_ModXXX flags. Sorry for the confusion.
// 2021-01-20: Inputs: calling new io.AddKeyAnalogEvent() for gamepad support, instead of writing directly to io.NavInputs[].
// 2022-01-17: Inputs: calling new io.AddMousePosEvent(), io.AddMouseButtonEvent(), io.AddMouseWheelEvent() API (1.87+).
// 2022-01-17: Inputs: always update key mods next and before key event (not in NewFrame) to fix input queue with very low framerates.
// 2022-01-12: Update mouse inputs using SDL_MOUSEMOTION/SDL_WINDOWEVENT_LEAVE + fallback to provide it when focused but not hovered/captured. More standard and will allow us to pass it to future input queue API.
// 2022-01-12: Maintain our own copy of MouseButtonsDown mask instead of using ImGui::IsAnyMouseDown() which will be obsoleted.
// 2022-01-10: Inputs: calling new io.AddKeyEvent(), io.AddKeyModsEvent() + io.SetKeyEventNativeData() API (1.87+). Support for full ImGuiKey range.
// 2021-08-17: Calling io.AddFocusEvent() on SDL_WINDOWEVENT_FOCUS_GAINED/SDL_WINDOWEVENT_FOCUS_LOST.
// 2021-07-29: Inputs: MousePos is correctly reported when the host platform window is hovered but not focused (using SDL_GetMouseFocus() + SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, requires SDL 2.0.5+)
// 2021-06-29: *BREAKING CHANGE* Removed 'SDL_Window* window' parameter to ImGui_ImplSDL2_NewFrame() which was unnecessary.
// 2021-06-29: Reorganized backend to pull data from a single structure to facilitate usage with multiple-contexts (all g_XXXX access changed to bd->XXXX).
// 2021-03-22: Rework global mouse pos availability check listing supported platforms explicitly, effectively fixing mouse access on Raspberry Pi. (#2837, #3950)
// 2020-05-25: Misc: Report a zero display-size when window is minimized, to be consistent with other backends.
// 2020-02-20: Inputs: Fixed mapping for ImGuiKey_KeyPadEnter (using SDL_SCANCODE_KP_ENTER instead of SDL_SCANCODE_RETURN2).
// 2019-12-17: Inputs: On Wayland, use SDL_GetMouseState (because there is no global mouse state).
// 2019-12-05: Inputs: Added support for ImGuiMouseCursor_NotAllowed mouse cursor.
// 2019-07-21: Inputs: Added mapping for ImGuiKey_KeyPadEnter.
// 2019-04-23: Inputs: Added support for SDL_GameController (if ImGuiConfigFlags_NavEnableGamepad is set by user application).
// 2019-03-12: Misc: Preserve DisplayFramebufferScale when main window is minimized.
// 2018-12-21: Inputs: Workaround for Android/iOS which don't seem to handle focus related calls.
// 2018-11-30: Misc: Setting up io.BackendPlatformName so it can be displayed in the About Window.
// 2018-11-14: Changed the signature of ImGui_ImplSDL2_ProcessEvent() to take a 'const SDL_Event*'.
// 2018-08-01: Inputs: Workaround for Emscripten which doesn't seem to handle focus related calls.
// 2018-06-29: Inputs: Added support for the ImGuiMouseCursor_Hand cursor.
// 2018-06-08: Misc: Extracted imgui_impl_sdl.cpp/.h away from the old combined SDL2+OpenGL/Vulkan examples.
// 2018-06-08: Misc: ImGui_ImplSDL2_InitForOpenGL() now takes a SDL_GLContext parameter.
// 2018-05-09: Misc: Fixed clipboard paste memory leak (we didn't call SDL_FreeMemory on the data returned by SDL_GetClipboardText).
// 2018-03-20: Misc: Setup io.BackendFlags ImGuiBackendFlags_HasMouseCursors flag + honor ImGuiConfigFlags_NoMouseCursorChange flag.
// 2018-02-16: Inputs: Added support for mouse cursors, honoring ImGui::GetMouseCursor() value.
// 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves.
// 2018-02-06: Inputs: Added mapping for ImGuiKey_Space.
// 2018-02-05: Misc: Using SDL_GetPerformanceCounter() instead of SDL_GetTicks() to be able to handle very high framerate (1000+ FPS).
// 2018-02-05: Inputs: Keyboard mapping is using scancodes everywhere instead of a confusing mixture of keycodes and scancodes.
// 2018-01-20: Inputs: Added Horizontal Mouse Wheel support.
// 2018-01-19: Inputs: When available (SDL 2.0.4+) using SDL_CaptureMouse() to retrieve coordinates outside of client area when dragging. Otherwise (SDL 2.0.3 and before) testing for SDL_WINDOW_INPUT_FOCUS instead of SDL_WINDOW_MOUSE_FOCUS.
// 2018-01-18: Inputs: Added mapping for ImGuiKey_Insert.
// 2017-08-25: Inputs: MousePos set to -FLT_MAX,-FLT_MAX when mouse is unavailable/missing (instead of -1,-1).
// 2016-10-15: Misc: Added a void* user_data parameter to Clipboard function handlers.
#include "imgui.h"
#ifndef IMGUI_DISABLE
#include "imgui_impl_sdl2.h"
// Clang warnings with -Weverything
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#endif
// SDL
#include <SDL2/SDL.h>
#include <SDL2/SDL_syswm.h>
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
#if SDL_VERSION_ATLEAST(2,0,4) && !defined(__EMSCRIPTEN__) && !defined(__ANDROID__) && !(defined(__APPLE__) && TARGET_OS_IOS) && !defined(__amigaos4__)
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 1
#else
#define SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE 0
#endif
#define SDL_HAS_VULKAN SDL_VERSION_ATLEAST(2,0,6)
// SDL Data
struct ImGui_ImplSDL2_Data
{
SDL_Window* Window;
SDL_Renderer* Renderer;
Uint64 Time;
Uint32 MouseWindowID;
int MouseButtonsDown;
SDL_Cursor* MouseCursors[ImGuiMouseCursor_COUNT];
SDL_Cursor* LastMouseCursor;
int PendingMouseLeaveFrame;
char* ClipboardTextData;
bool MouseCanUseGlobalState;
ImGui_ImplSDL2_Data() { memset((void*)this, 0, sizeof(*this)); }
};
// Backend data stored in io.BackendPlatformUserData to allow support for multiple Dear ImGui contexts
// It is STRONGLY preferred that you use docking branch with multi-viewports (== single Dear ImGui context + multiple windows) instead of multiple Dear ImGui contexts.
// FIXME: multi-context support is not well tested and probably dysfunctional in this backend.
// FIXME: some shared resources (mouse cursor shape, gamepad) are mishandled when using multi-context.
static ImGui_ImplSDL2_Data* ImGui_ImplSDL2_GetBackendData()
{
return ImGui::GetCurrentContext() ? (ImGui_ImplSDL2_Data*)ImGui::GetIO().BackendPlatformUserData : nullptr;
}
// Functions
static const char* ImGui_ImplSDL2_GetClipboardText(void*)
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
if (bd->ClipboardTextData)
SDL_free(bd->ClipboardTextData);
bd->ClipboardTextData = SDL_GetClipboardText();
return bd->ClipboardTextData;
}
static void ImGui_ImplSDL2_SetClipboardText(void*, const char* text)
{
SDL_SetClipboardText(text);
}
// Note: native IME will only display if user calls SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1") _before_ SDL_CreateWindow().
static void ImGui_ImplSDL2_SetPlatformImeData(ImGuiViewport*, ImGuiPlatformImeData* data)
{
if (data->WantVisible)
{
SDL_Rect r;
r.x = (int)data->InputPos.x;
r.y = (int)data->InputPos.y;
r.w = 1;
r.h = (int)data->InputLineHeight;
SDL_SetTextInputRect(&r);
}
}
static ImGuiKey ImGui_ImplSDL2_KeycodeToImGuiKey(int keycode)
{
switch (keycode)
{
case SDLK_TAB: return ImGuiKey_Tab;
case SDLK_LEFT: return ImGuiKey_LeftArrow;
case SDLK_RIGHT: return ImGuiKey_RightArrow;
case SDLK_UP: return ImGuiKey_UpArrow;
case SDLK_DOWN: return ImGuiKey_DownArrow;
case SDLK_PAGEUP: return ImGuiKey_PageUp;
case SDLK_PAGEDOWN: return ImGuiKey_PageDown;
case SDLK_HOME: return ImGuiKey_Home;
case SDLK_END: return ImGuiKey_End;
case SDLK_INSERT: return ImGuiKey_Insert;
case SDLK_DELETE: return ImGuiKey_Delete;
case SDLK_BACKSPACE: return ImGuiKey_Backspace;
case SDLK_SPACE: return ImGuiKey_Space;
case SDLK_RETURN: return ImGuiKey_Enter;
case SDLK_ESCAPE: return ImGuiKey_Escape;
case SDLK_QUOTE: return ImGuiKey_Apostrophe;
case SDLK_COMMA: return ImGuiKey_Comma;
case SDLK_MINUS: return ImGuiKey_Minus;
case SDLK_PERIOD: return ImGuiKey_Period;
case SDLK_SLASH: return ImGuiKey_Slash;
case SDLK_SEMICOLON: return ImGuiKey_Semicolon;
case SDLK_EQUALS: return ImGuiKey_Equal;
case SDLK_LEFTBRACKET: return ImGuiKey_LeftBracket;
case SDLK_BACKSLASH: return ImGuiKey_Backslash;
case SDLK_RIGHTBRACKET: return ImGuiKey_RightBracket;
case SDLK_BACKQUOTE: return ImGuiKey_GraveAccent;
case SDLK_CAPSLOCK: return ImGuiKey_CapsLock;
case SDLK_SCROLLLOCK: return ImGuiKey_ScrollLock;
case SDLK_NUMLOCKCLEAR: return ImGuiKey_NumLock;
case SDLK_PRINTSCREEN: return ImGuiKey_PrintScreen;
case SDLK_PAUSE: return ImGuiKey_Pause;
case SDLK_KP_0: return ImGuiKey_Keypad0;
case SDLK_KP_1: return ImGuiKey_Keypad1;
case SDLK_KP_2: return ImGuiKey_Keypad2;
case SDLK_KP_3: return ImGuiKey_Keypad3;
case SDLK_KP_4: return ImGuiKey_Keypad4;
case SDLK_KP_5: return ImGuiKey_Keypad5;
case SDLK_KP_6: return ImGuiKey_Keypad6;
case SDLK_KP_7: return ImGuiKey_Keypad7;
case SDLK_KP_8: return ImGuiKey_Keypad8;
case SDLK_KP_9: return ImGuiKey_Keypad9;
case SDLK_KP_PERIOD: return ImGuiKey_KeypadDecimal;
case SDLK_KP_DIVIDE: return ImGuiKey_KeypadDivide;
case SDLK_KP_MULTIPLY: return ImGuiKey_KeypadMultiply;
case SDLK_KP_MINUS: return ImGuiKey_KeypadSubtract;
case SDLK_KP_PLUS: return ImGuiKey_KeypadAdd;
case SDLK_KP_ENTER: return ImGuiKey_KeypadEnter;
case SDLK_KP_EQUALS: return ImGuiKey_KeypadEqual;
case SDLK_LCTRL: return ImGuiKey_LeftCtrl;
case SDLK_LSHIFT: return ImGuiKey_LeftShift;
case SDLK_LALT: return ImGuiKey_LeftAlt;
case SDLK_LGUI: return ImGuiKey_LeftSuper;
case SDLK_RCTRL: return ImGuiKey_RightCtrl;
case SDLK_RSHIFT: return ImGuiKey_RightShift;
case SDLK_RALT: return ImGuiKey_RightAlt;
case SDLK_RGUI: return ImGuiKey_RightSuper;
case SDLK_APPLICATION: return ImGuiKey_Menu;
case SDLK_0: return ImGuiKey_0;
case SDLK_1: return ImGuiKey_1;
case SDLK_2: return ImGuiKey_2;
case SDLK_3: return ImGuiKey_3;
case SDLK_4: return ImGuiKey_4;
case SDLK_5: return ImGuiKey_5;
case SDLK_6: return ImGuiKey_6;
case SDLK_7: return ImGuiKey_7;
case SDLK_8: return ImGuiKey_8;
case SDLK_9: return ImGuiKey_9;
case SDLK_a: return ImGuiKey_A;
case SDLK_b: return ImGuiKey_B;
case SDLK_c: return ImGuiKey_C;
case SDLK_d: return ImGuiKey_D;
case SDLK_e: return ImGuiKey_E;
case SDLK_f: return ImGuiKey_F;
case SDLK_g: return ImGuiKey_G;
case SDLK_h: return ImGuiKey_H;
case SDLK_i: return ImGuiKey_I;
case SDLK_j: return ImGuiKey_J;
case SDLK_k: return ImGuiKey_K;
case SDLK_l: return ImGuiKey_L;
case SDLK_m: return ImGuiKey_M;
case SDLK_n: return ImGuiKey_N;
case SDLK_o: return ImGuiKey_O;
case SDLK_p: return ImGuiKey_P;
case SDLK_q: return ImGuiKey_Q;
case SDLK_r: return ImGuiKey_R;
case SDLK_s: return ImGuiKey_S;
case SDLK_t: return ImGuiKey_T;
case SDLK_u: return ImGuiKey_U;
case SDLK_v: return ImGuiKey_V;
case SDLK_w: return ImGuiKey_W;
case SDLK_x: return ImGuiKey_X;
case SDLK_y: return ImGuiKey_Y;
case SDLK_z: return ImGuiKey_Z;
case SDLK_F1: return ImGuiKey_F1;
case SDLK_F2: return ImGuiKey_F2;
case SDLK_F3: return ImGuiKey_F3;
case SDLK_F4: return ImGuiKey_F4;
case SDLK_F5: return ImGuiKey_F5;
case SDLK_F6: return ImGuiKey_F6;
case SDLK_F7: return ImGuiKey_F7;
case SDLK_F8: return ImGuiKey_F8;
case SDLK_F9: return ImGuiKey_F9;
case SDLK_F10: return ImGuiKey_F10;
case SDLK_F11: return ImGuiKey_F11;
case SDLK_F12: return ImGuiKey_F12;
}
return ImGuiKey_None;
}
static void ImGui_ImplSDL2_UpdateKeyModifiers(SDL_Keymod sdl_key_mods)
{
ImGuiIO& io = ImGui::GetIO();
io.AddKeyEvent(ImGuiMod_Ctrl, (sdl_key_mods & KMOD_CTRL) != 0);
io.AddKeyEvent(ImGuiMod_Shift, (sdl_key_mods & KMOD_SHIFT) != 0);
io.AddKeyEvent(ImGuiMod_Alt, (sdl_key_mods & KMOD_ALT) != 0);
io.AddKeyEvent(ImGuiMod_Super, (sdl_key_mods & KMOD_GUI) != 0);
}
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application, or clear/overwrite your copy of the mouse data.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application, or clear/overwrite your copy of the keyboard data.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
// If you have multiple SDL events and some of them are not meant to be used by dear imgui, you may need to filter events based on their windowID field.
bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event)
{
ImGuiIO& io = ImGui::GetIO();
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
switch (event->type)
{
case SDL_MOUSEMOTION:
{
ImVec2 mouse_pos((float)event->motion.x, (float)event->motion.y);
io.AddMouseSourceEvent(event->motion.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMousePosEvent(mouse_pos.x, mouse_pos.y);
return true;
}
case SDL_MOUSEWHEEL:
{
//IMGUI_DEBUG_LOG("wheel %.2f %.2f, precise %.2f %.2f\n", (float)event->wheel.x, (float)event->wheel.y, event->wheel.preciseX, event->wheel.preciseY);
#if SDL_VERSION_ATLEAST(2,0,18) // If this fails to compile on Emscripten: update to latest Emscripten!
float wheel_x = -event->wheel.preciseX;
float wheel_y = event->wheel.preciseY;
#else
float wheel_x = -(float)event->wheel.x;
float wheel_y = (float)event->wheel.y;
#endif
#ifdef __EMSCRIPTEN__
wheel_x /= 100.0f;
#endif
io.AddMouseSourceEvent(event->wheel.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMouseWheelEvent(wheel_x, wheel_y);
return true;
}
case SDL_MOUSEBUTTONDOWN:
case SDL_MOUSEBUTTONUP:
{
int mouse_button = -1;
if (event->button.button == SDL_BUTTON_LEFT) { mouse_button = 0; }
if (event->button.button == SDL_BUTTON_RIGHT) { mouse_button = 1; }
if (event->button.button == SDL_BUTTON_MIDDLE) { mouse_button = 2; }
if (event->button.button == SDL_BUTTON_X1) { mouse_button = 3; }
if (event->button.button == SDL_BUTTON_X2) { mouse_button = 4; }
if (mouse_button == -1)
break;
io.AddMouseSourceEvent(event->button.which == SDL_TOUCH_MOUSEID ? ImGuiMouseSource_TouchScreen : ImGuiMouseSource_Mouse);
io.AddMouseButtonEvent(mouse_button, (event->type == SDL_MOUSEBUTTONDOWN));
bd->MouseButtonsDown = (event->type == SDL_MOUSEBUTTONDOWN) ? (bd->MouseButtonsDown | (1 << mouse_button)) : (bd->MouseButtonsDown & ~(1 << mouse_button));
return true;
}
case SDL_TEXTINPUT:
{
io.AddInputCharactersUTF8(event->text.text);
return true;
}
case SDL_KEYDOWN:
case SDL_KEYUP:
{
ImGui_ImplSDL2_UpdateKeyModifiers((SDL_Keymod)event->key.keysym.mod);
ImGuiKey key = ImGui_ImplSDL2_KeycodeToImGuiKey(event->key.keysym.sym);
io.AddKeyEvent(key, (event->type == SDL_KEYDOWN));
io.SetKeyEventNativeData(key, event->key.keysym.sym, event->key.keysym.scancode, event->key.keysym.scancode); // To support legacy indexing (<1.87 user code). Legacy backend uses SDLK_*** as indices to IsKeyXXX() functions.
return true;
}
case SDL_WINDOWEVENT:
{
// - When capturing mouse, SDL will send a bunch of conflicting LEAVE/ENTER event on every mouse move, but the final ENTER tends to be right.
// - However we won't get a correct LEAVE event for a captured window.
// - In some cases, when detaching a window from main viewport SDL may send SDL_WINDOWEVENT_ENTER one frame too late,
// causing SDL_WINDOWEVENT_LEAVE on previous frame to interrupt drag operation by clear mouse position. This is why
// we delay process the SDL_WINDOWEVENT_LEAVE events by one frame. See issue #5012 for details.
Uint8 window_event = event->window.event;
if (window_event == SDL_WINDOWEVENT_ENTER)
{
bd->MouseWindowID = event->window.windowID;
bd->PendingMouseLeaveFrame = 0;
}
if (window_event == SDL_WINDOWEVENT_LEAVE)
bd->PendingMouseLeaveFrame = ImGui::GetFrameCount() + 1;
if (window_event == SDL_WINDOWEVENT_FOCUS_GAINED)
io.AddFocusEvent(true);
else if (event->window.event == SDL_WINDOWEVENT_FOCUS_LOST)
io.AddFocusEvent(false);
return true;
}
}
return false;
}
static bool ImGui_ImplSDL2_Init(SDL_Window* window, SDL_Renderer* renderer)
{
ImGuiIO& io = ImGui::GetIO();
IM_ASSERT(io.BackendPlatformUserData == nullptr && "Already initialized a platform backend!");
// Check and store if we are on a SDL backend that supports global mouse position
// ("wayland" and "rpi" don't support it, but we chose to use a white-list instead of a black-list)
bool mouse_can_use_global_state = false;
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
const char* sdl_backend = SDL_GetCurrentVideoDriver();
const char* global_mouse_whitelist[] = { "windows", "cocoa", "x11", "DIVE", "VMAN" };
for (int n = 0; n < IM_ARRAYSIZE(global_mouse_whitelist); n++)
if (strncmp(sdl_backend, global_mouse_whitelist[n], strlen(global_mouse_whitelist[n])) == 0)
mouse_can_use_global_state = true;
#endif
// Setup backend capabilities flags
ImGui_ImplSDL2_Data* bd = IM_NEW(ImGui_ImplSDL2_Data)();
io.BackendPlatformUserData = (void*)bd;
io.BackendPlatformName = "imgui_impl_sdl2";
io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; // We can honor GetMouseCursor() values (optional)
io.BackendFlags |= ImGuiBackendFlags_HasSetMousePos; // We can honor io.WantSetMousePos requests (optional, rarely used)
bd->Window = window;
bd->Renderer = renderer;
bd->MouseCanUseGlobalState = mouse_can_use_global_state;
io.SetClipboardTextFn = ImGui_ImplSDL2_SetClipboardText;
io.GetClipboardTextFn = ImGui_ImplSDL2_GetClipboardText;
io.ClipboardUserData = nullptr;
io.SetPlatformImeDataFn = ImGui_ImplSDL2_SetPlatformImeData;
// Load mouse cursors
bd->MouseCursors[ImGuiMouseCursor_Arrow] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_ARROW);
bd->MouseCursors[ImGuiMouseCursor_TextInput] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_IBEAM);
bd->MouseCursors[ImGuiMouseCursor_ResizeAll] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEALL);
bd->MouseCursors[ImGuiMouseCursor_ResizeNS] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENS);
bd->MouseCursors[ImGuiMouseCursor_ResizeEW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZEWE);
bd->MouseCursors[ImGuiMouseCursor_ResizeNESW] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENESW);
bd->MouseCursors[ImGuiMouseCursor_ResizeNWSE] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_SIZENWSE);
bd->MouseCursors[ImGuiMouseCursor_Hand] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_HAND);
bd->MouseCursors[ImGuiMouseCursor_NotAllowed] = SDL_CreateSystemCursor(SDL_SYSTEM_CURSOR_NO);
// Set platform dependent data in viewport
// Our mouse update function expect PlatformHandle to be filled for the main viewport
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
main_viewport->PlatformHandleRaw = nullptr;
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWindowWMInfo(window, &info))
{
#if defined(SDL_VIDEO_DRIVER_WINDOWS)
main_viewport->PlatformHandleRaw = (void*)info.info.win.window;
#elif defined(__APPLE__) && defined(SDL_VIDEO_DRIVER_COCOA)
main_viewport->PlatformHandleRaw = (void*)info.info.cocoa.window;
#endif
}
// From 2.0.5: Set SDL hint to receive mouse click events on window focus, otherwise SDL doesn't emit the event.
// Without this, when clicking to gain focus, our widgets wouldn't activate even though they showed as hovered.
// (This is unfortunately a global SDL setting, so enabling it might have a side-effect on your application.
// It is unlikely to make a difference, but if your app absolutely needs to ignore the initial on-focus click:
// you can ignore SDL_MOUSEBUTTONDOWN events coming right after a SDL_WINDOWEVENT_FOCUS_GAINED)
#ifdef SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH
SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1");
#endif
// From 2.0.18: Enable native IME.
// IMPORTANT: This is used at the time of SDL_CreateWindow() so this will only affects secondary windows, if any.
// For the main window to be affected, your application needs to call this manually before calling SDL_CreateWindow().
#ifdef SDL_HINT_IME_SHOW_UI
SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");
#endif
// From 2.0.22: Disable auto-capture, this is preventing drag and drop across multiple windows (see #5710)
#ifdef SDL_HINT_MOUSE_AUTO_CAPTURE
SDL_SetHint(SDL_HINT_MOUSE_AUTO_CAPTURE, "0");
#endif
return true;
}
bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context)
{
IM_UNUSED(sdl_gl_context); // Viewport branch will need this.
return ImGui_ImplSDL2_Init(window, nullptr);
}
bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window)
{
#if !SDL_HAS_VULKAN
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window, nullptr);
}
bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window)
{
#if !defined(_WIN32)
IM_ASSERT(0 && "Unsupported");
#endif
return ImGui_ImplSDL2_Init(window, nullptr);
}
bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window)
{
return ImGui_ImplSDL2_Init(window, nullptr);
}
bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer)
{
return ImGui_ImplSDL2_Init(window, renderer);
}
bool ImGui_ImplSDL2_InitForOther(SDL_Window* window)
{
return ImGui_ImplSDL2_Init(window, nullptr);
}
void ImGui_ImplSDL2_Shutdown()
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
IM_ASSERT(bd != nullptr && "No platform backend to shutdown, or already shutdown?");
ImGuiIO& io = ImGui::GetIO();
if (bd->ClipboardTextData)
SDL_free(bd->ClipboardTextData);
for (ImGuiMouseCursor cursor_n = 0; cursor_n < ImGuiMouseCursor_COUNT; cursor_n++)
SDL_FreeCursor(bd->MouseCursors[cursor_n]);
bd->LastMouseCursor = nullptr;
io.BackendPlatformName = nullptr;
io.BackendPlatformUserData = nullptr;
io.BackendFlags &= ~(ImGuiBackendFlags_HasMouseCursors | ImGuiBackendFlags_HasSetMousePos | ImGuiBackendFlags_HasGamepad);
IM_DELETE(bd);
}
static void ImGui_ImplSDL2_UpdateMouseData()
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
ImGuiIO& io = ImGui::GetIO();
// We forward mouse input when hovered or captured (via SDL_MOUSEMOTION) or when focused (below)
#if SDL_HAS_CAPTURE_AND_GLOBAL_MOUSE
// SDL_CaptureMouse() let the OS know e.g. that our imgui drag outside the SDL window boundaries shouldn't e.g. trigger other operations outside
SDL_CaptureMouse((bd->MouseButtonsDown != 0) ? SDL_TRUE : SDL_FALSE);
SDL_Window* focused_window = SDL_GetKeyboardFocus();
const bool is_app_focused = (bd->Window == focused_window);
#else
const bool is_app_focused = (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_INPUT_FOCUS) != 0; // SDL 2.0.3 and non-windowed systems: single-viewport only
#endif
if (is_app_focused)
{
// (Optional) Set OS mouse position from Dear ImGui if requested (rarely used, only when ImGuiConfigFlags_NavEnableSetMousePos is enabled by user)
if (io.WantSetMousePos)
SDL_WarpMouseInWindow(bd->Window, (int)io.MousePos.x, (int)io.MousePos.y);
// (Optional) Fallback to provide mouse position when focused (SDL_MOUSEMOTION already provides this when hovered or captured)
if (bd->MouseCanUseGlobalState && bd->MouseButtonsDown == 0)
{
int window_x, window_y, mouse_x_global, mouse_y_global;
SDL_GetGlobalMouseState(&mouse_x_global, &mouse_y_global);
SDL_GetWindowPosition(bd->Window, &window_x, &window_y);
io.AddMousePosEvent((float)(mouse_x_global - window_x), (float)(mouse_y_global - window_y));
}
}
}
static void ImGui_ImplSDL2_UpdateMouseCursor()
{
ImGuiIO& io = ImGui::GetIO();
if (io.ConfigFlags & ImGuiConfigFlags_NoMouseCursorChange)
return;
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
ImGuiMouseCursor imgui_cursor = ImGui::GetMouseCursor();
if (io.MouseDrawCursor || imgui_cursor == ImGuiMouseCursor_None)
{
// Hide OS mouse cursor if imgui is drawing it or if it wants no cursor
SDL_ShowCursor(SDL_FALSE);
}
else
{
// Show OS mouse cursor
SDL_Cursor* expected_cursor = bd->MouseCursors[imgui_cursor] ? bd->MouseCursors[imgui_cursor] : bd->MouseCursors[ImGuiMouseCursor_Arrow];
if (bd->LastMouseCursor != expected_cursor)
{
SDL_SetCursor(expected_cursor); // SDL function doesn't have an early out (see #6113)
bd->LastMouseCursor = expected_cursor;
}
SDL_ShowCursor(SDL_TRUE);
}
}
static void ImGui_ImplSDL2_UpdateGamepads()
{
ImGuiIO& io = ImGui::GetIO();
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) == 0) // FIXME: Technically feeding gamepad shouldn't depend on this now that they are regular inputs.
return;
// Get gamepad
io.BackendFlags &= ~ImGuiBackendFlags_HasGamepad;
SDL_GameController* game_controller = SDL_GameControllerOpen(0);
if (!game_controller)
return;
io.BackendFlags |= ImGuiBackendFlags_HasGamepad;
// Update gamepad inputs
#define IM_SATURATE(V) (V < 0.0f ? 0.0f : V > 1.0f ? 1.0f : V)
#define MAP_BUTTON(KEY_NO, BUTTON_NO) { io.AddKeyEvent(KEY_NO, SDL_GameControllerGetButton(game_controller, BUTTON_NO) != 0); }
#define MAP_ANALOG(KEY_NO, AXIS_NO, V0, V1) { float vn = (float)(SDL_GameControllerGetAxis(game_controller, AXIS_NO) - V0) / (float)(V1 - V0); vn = IM_SATURATE(vn); io.AddKeyAnalogEvent(KEY_NO, vn > 0.1f, vn); }
const int thumb_dead_zone = 8000; // SDL_gamecontroller.h suggests using this value.
MAP_BUTTON(ImGuiKey_GamepadStart, SDL_CONTROLLER_BUTTON_START);
MAP_BUTTON(ImGuiKey_GamepadBack, SDL_CONTROLLER_BUTTON_BACK);
MAP_BUTTON(ImGuiKey_GamepadFaceLeft, SDL_CONTROLLER_BUTTON_X); // Xbox X, PS Square
MAP_BUTTON(ImGuiKey_GamepadFaceRight, SDL_CONTROLLER_BUTTON_B); // Xbox B, PS Circle
MAP_BUTTON(ImGuiKey_GamepadFaceUp, SDL_CONTROLLER_BUTTON_Y); // Xbox Y, PS Triangle
MAP_BUTTON(ImGuiKey_GamepadFaceDown, SDL_CONTROLLER_BUTTON_A); // Xbox A, PS Cross
MAP_BUTTON(ImGuiKey_GamepadDpadLeft, SDL_CONTROLLER_BUTTON_DPAD_LEFT);
MAP_BUTTON(ImGuiKey_GamepadDpadRight, SDL_CONTROLLER_BUTTON_DPAD_RIGHT);
MAP_BUTTON(ImGuiKey_GamepadDpadUp, SDL_CONTROLLER_BUTTON_DPAD_UP);
MAP_BUTTON(ImGuiKey_GamepadDpadDown, SDL_CONTROLLER_BUTTON_DPAD_DOWN);
MAP_BUTTON(ImGuiKey_GamepadL1, SDL_CONTROLLER_BUTTON_LEFTSHOULDER);
MAP_BUTTON(ImGuiKey_GamepadR1, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);
MAP_ANALOG(ImGuiKey_GamepadL2, SDL_CONTROLLER_AXIS_TRIGGERLEFT, 0.0f, 32767);
MAP_ANALOG(ImGuiKey_GamepadR2, SDL_CONTROLLER_AXIS_TRIGGERRIGHT, 0.0f, 32767);
MAP_BUTTON(ImGuiKey_GamepadL3, SDL_CONTROLLER_BUTTON_LEFTSTICK);
MAP_BUTTON(ImGuiKey_GamepadR3, SDL_CONTROLLER_BUTTON_RIGHTSTICK);
MAP_ANALOG(ImGuiKey_GamepadLStickLeft, SDL_CONTROLLER_AXIS_LEFTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickRight, SDL_CONTROLLER_AXIS_LEFTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadLStickUp, SDL_CONTROLLER_AXIS_LEFTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadLStickDown, SDL_CONTROLLER_AXIS_LEFTY, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickLeft, SDL_CONTROLLER_AXIS_RIGHTX, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickRight, SDL_CONTROLLER_AXIS_RIGHTX, +thumb_dead_zone, +32767);
MAP_ANALOG(ImGuiKey_GamepadRStickUp, SDL_CONTROLLER_AXIS_RIGHTY, -thumb_dead_zone, -32768);
MAP_ANALOG(ImGuiKey_GamepadRStickDown, SDL_CONTROLLER_AXIS_RIGHTY, +thumb_dead_zone, +32767);
#undef MAP_BUTTON
#undef MAP_ANALOG
}
void ImGui_ImplSDL2_NewFrame()
{
ImGui_ImplSDL2_Data* bd = ImGui_ImplSDL2_GetBackendData();
IM_ASSERT(bd != nullptr && "Did you call ImGui_ImplSDL2_Init()?");
ImGuiIO& io = ImGui::GetIO();
// Setup display size (every frame to accommodate for window resizing)
int w, h;
int display_w, display_h;
SDL_GetWindowSize(bd->Window, &w, &h);
if (SDL_GetWindowFlags(bd->Window) & SDL_WINDOW_MINIMIZED)
w = h = 0;
if (bd->Renderer != nullptr)
SDL_GetRendererOutputSize(bd->Renderer, &display_w, &display_h);
else
SDL_GL_GetDrawableSize(bd->Window, &display_w, &display_h);
io.DisplaySize = ImVec2((float)w, (float)h);
if (w > 0 && h > 0)
io.DisplayFramebufferScale = ImVec2((float)display_w / w, (float)display_h / h);
// Setup time step (we don't use SDL_GetTicks() because it is using millisecond resolution)
// (Accept SDL_GetPerformanceCounter() not returning a monotonically increasing value. Happens in VMs and Emscripten, see #6189, #6114, #3644)
static Uint64 frequency = SDL_GetPerformanceFrequency();
Uint64 current_time = SDL_GetPerformanceCounter();
if (current_time <= bd->Time)
current_time = bd->Time + 1;
io.DeltaTime = bd->Time > 0 ? (float)((double)(current_time - bd->Time) / frequency) : (float)(1.0f / 60.0f);
bd->Time = current_time;
if (bd->PendingMouseLeaveFrame && bd->PendingMouseLeaveFrame >= ImGui::GetFrameCount() && bd->MouseButtonsDown == 0)
{
bd->MouseWindowID = 0;
bd->PendingMouseLeaveFrame = 0;
io.AddMousePosEvent(-FLT_MAX, -FLT_MAX);
}
ImGui_ImplSDL2_UpdateMouseData();
ImGui_ImplSDL2_UpdateMouseCursor();
// Update game controllers (if enabled and available)
ImGui_ImplSDL2_UpdateGamepads();
}
//-----------------------------------------------------------------------------
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#endif // #ifndef IMGUI_DISABLE

View File

@@ -1,40 +0,0 @@
// dear imgui: Platform Backend for SDL2
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// (Info: SDL2 is a cross-platform general purpose library for handling windows, inputs, graphics context creation, etc.)
// Implemented features:
// [X] Platform: Clipboard support.
// [X] Platform: Mouse support. Can discriminate Mouse/TouchScreen.
// [X] Platform: Keyboard support. Since 1.87 we are using the io.AddKeyEvent() function. Pass ImGuiKey values to all key functions e.g. ImGui::IsKeyPressed(ImGuiKey_Space). [Legacy SDL_SCANCODE_* values will also be supported unless IMGUI_DISABLE_OBSOLETE_KEYIO is set]
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Basic IME support. App needs to call 'SDL_SetHint(SDL_HINT_IME_SHOW_UI, "1");' before SDL_CreateWindow()!.
// You can use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// Prefer including the entire imgui/ repository into your project (either as a copy or as a submodule), and only build the backends you need.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#pragma once
#include "imgui.h" // IMGUI_IMPL_API
#ifndef IMGUI_DISABLE
class SDL_Window;
struct SDL_Renderer;
typedef union SDL_Event SDL_Event;
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOpenGL(SDL_Window* window, void* sdl_gl_context);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForVulkan(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForD3D(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForMetal(SDL_Window* window);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForSDLRenderer(SDL_Window* window, SDL_Renderer* renderer);
IMGUI_IMPL_API bool ImGui_ImplSDL2_InitForOther(SDL_Window* window);
IMGUI_IMPL_API void ImGui_ImplSDL2_Shutdown();
IMGUI_IMPL_API void ImGui_ImplSDL2_NewFrame();
IMGUI_IMPL_API bool ImGui_ImplSDL2_ProcessEvent(const SDL_Event* event);
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
static inline void ImGui_ImplSDL2_NewFrame(SDL_Window*) { ImGui_ImplSDL2_NewFrame(); } // 1.84: removed unnecessary parameter
#endif
#endif // #ifndef IMGUI_DISABLE

View File

@@ -1,129 +0,0 @@
//-----------------------------------------------------------------------------
// DEAR IMGUI COMPILE-TIME OPTIONS
// Runtime options (clipboard callbacks, enabling various features, etc.) can generally be set via the ImGuiIO structure.
// You can use ImGui::SetAllocatorFunctions() before calling ImGui::CreateContext() to rewire memory allocation functions.
//-----------------------------------------------------------------------------
// A) You may edit imconfig.h (and not overwrite it when updating Dear ImGui, or maintain a patch/rebased branch with your modifications to it)
// B) or '#define IMGUI_USER_CONFIG "my_imgui_config.h"' in your project and then add directives in your own file without touching this template.
//-----------------------------------------------------------------------------
// You need to make sure that configuration settings are defined consistently _everywhere_ Dear ImGui is used, which include the imgui*.cpp
// files but also _any_ of your code that uses Dear ImGui. This is because some compile-time options have an affect on data structures.
// Defining those options in imconfig.h will ensure every compilation unit gets to see the same data structure layouts.
// Call IMGUI_CHECKVERSION() from your .cpp file to verify that the data structures your files are using are matching the ones imgui.cpp is using.
//-----------------------------------------------------------------------------
#pragma once
//---- Define assertion handler. Defaults to calling assert().
// If your macro uses multiple statements, make sure is enclosed in a 'do { .. } while (0)' block so it can be used as a single statement.
//#define IM_ASSERT(_EXPR) MyAssert(_EXPR)
//#define IM_ASSERT(_EXPR) ((void)(_EXPR)) // Disable asserts
//---- Define attributes of all API symbols declarations, e.g. for DLL under Windows
// Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// DLL users: heaps and globals are not shared across DLL boundaries! You will need to call SetCurrentContext() + SetAllocatorFunctions()
// for each static/DLL boundary you are calling from. Read "Context and Memory Allocators" section of imgui.cpp for more details.
//#define IMGUI_API __declspec( dllexport )
//#define IMGUI_API __declspec( dllimport )
//---- Don't define obsolete functions/enums/behaviors. Consider enabling from time to time after updating to clean your code of obsolete function/names.
//#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS
//#define IMGUI_DISABLE_OBSOLETE_KEYIO // 1.87: disable legacy io.KeyMap[]+io.KeysDown[] in favor io.AddKeyEvent(). This will be folded into IMGUI_DISABLE_OBSOLETE_FUNCTIONS in a few versions.
//---- Disable all of Dear ImGui or don't implement standard windows/tools.
// It is very strongly recommended to NOT disable the demo windows and debug tool during development. They are extremely useful in day to day work. Please read comments in imgui_demo.cpp.
//#define IMGUI_DISABLE // Disable everything: all headers and source files will be empty.
//#define IMGUI_DISABLE_DEMO_WINDOWS // Disable demo windows: ShowDemoWindow()/ShowStyleEditor() will be empty.
//#define IMGUI_DISABLE_DEBUG_TOOLS // Disable metrics/debugger and other debug tools: ShowMetricsWindow(), ShowDebugLogWindow() and ShowStackToolWindow() will be empty (this was called IMGUI_DISABLE_METRICS_WINDOW before 1.88).
//---- Don't implement some functions to reduce linkage requirements.
//#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS // [Win32] Don't implement default clipboard handler. Won't use and link with OpenClipboard/GetClipboardData/CloseClipboard etc. (user32.lib/.a, kernel32.lib/.a)
//#define IMGUI_ENABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with Visual Studio] Implement default IME handler (require imm32.lib/.a, auto-link for Visual Studio, -limm32 on command-line for MinGW)
//#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS // [Win32] [Default with non-Visual Studio compilers] Don't implement default IME handler (won't require imm32.lib/.a)
//#define IMGUI_DISABLE_WIN32_FUNCTIONS // [Win32] Won't use and link with any Win32 function (clipboard, IME).
//#define IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS // [OSX] Implement default OSX clipboard handler (need to link with '-framework ApplicationServices', this is why this is not the default).
//#define IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS // Don't implement ImFormatString/ImFormatStringV so you can implement them yourself (e.g. if you don't want to link with vsnprintf)
//#define IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS // Don't implement ImFabs/ImSqrt/ImPow/ImFmod/ImCos/ImSin/ImAcos/ImAtan2 so you can implement them yourself.
//#define IMGUI_DISABLE_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle at all (replace them with dummies)
//#define IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS // Don't implement ImFileOpen/ImFileClose/ImFileRead/ImFileWrite and ImFileHandle so you can implement them yourself if you don't want to link with fopen/fclose/fread/fwrite. This will also disable the LogToTTY() function.
//#define IMGUI_DISABLE_DEFAULT_ALLOCATORS // Don't implement default allocators calling malloc()/free() to avoid linking with them. You will need to call ImGui::SetAllocatorFunctions().
//#define IMGUI_DISABLE_SSE // Disable use of SSE intrinsics even if available
//---- Include imgui_user.h at the end of imgui.h as a convenience
//#define IMGUI_INCLUDE_IMGUI_USER_H
//---- Pack colors to BGRA8 instead of RGBA8 (to avoid converting from one to another)
//#define IMGUI_USE_BGRA_PACKED_COLOR
//---- Use 32-bit for ImWchar (default is 16-bit) to support unicode planes 1-16. (e.g. point beyond 0xFFFF like emoticons, dingbats, symbols, shapes, ancient languages, etc...)
//#define IMGUI_USE_WCHAR32
//---- Avoid multiple STB libraries implementations, or redefine path/filenames to prioritize another version
// By default the embedded implementations are declared static and not available outside of Dear ImGui sources files.
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_STB_SPRINTF_FILENAME "my_folder/stb_sprintf.h" // only used if IMGUI_USE_STB_SPRINTF is defined.
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_SPRINTF_IMPLEMENTATION // only disabled if IMGUI_USE_STB_SPRINTF is defined.
//---- Use stb_sprintf.h for a faster implementation of vsnprintf instead of the one from libc (unless IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS is defined)
// Compatibility checks of arguments and formats done by clang and GCC will be disabled in order to support the extra formats provided by stb_sprintf.h.
//#define IMGUI_USE_STB_SPRINTF
//---- Use FreeType to build and rasterize the font atlas (instead of stb_truetype which is embedded by default in Dear ImGui)
// Requires FreeType headers to be available in the include path. Requires program to be compiled with 'misc/freetype/imgui_freetype.cpp' (in this repository) + the FreeType library (not provided).
// On Windows you may use vcpkg with 'vcpkg install freetype --triplet=x64-windows' + 'vcpkg integrate install'.
//#define IMGUI_ENABLE_FREETYPE
//---- Use FreeType+lunasvg library to render OpenType SVG fonts (SVGinOT)
// Requires lunasvg headers to be available in the include path + program to be linked with the lunasvg library (not provided).
// Only works in combination with IMGUI_ENABLE_FREETYPE.
// (implementation is based on Freetype's rsvg-port.c which is licensed under CeCILL-C Free Software License Agreement)
//#define IMGUI_ENABLE_FREETYPE_LUNASVG
//---- Use stb_truetype to build and rasterize the font atlas (default)
// The only purpose of this define is if you want force compilation of the stb_truetype backend ALONG with the FreeType backend.
//#define IMGUI_ENABLE_STB_TRUETYPE
//---- Define constructor and implicit cast operators to convert back<>forth between your math types and ImVec2/ImVec4.
// This will be inlined as part of ImVec2 and ImVec4 class declarations.
/*
#define IM_VEC2_CLASS_EXTRA \
constexpr ImVec2(const MyVec2& f) : x(f.x), y(f.y) {} \
operator MyVec2() const { return MyVec2(x,y); }
#define IM_VEC4_CLASS_EXTRA \
constexpr ImVec4(const MyVec4& f) : x(f.x), y(f.y), z(f.z), w(f.w) {} \
operator MyVec4() const { return MyVec4(x,y,z,w); }
*/
//---- ...Or use Dear ImGui's own very basic math operators.
//#define IMGUI_DEFINE_MATH_OPERATORS
//---- Use 32-bit vertex indices (default is 16-bit) is one way to allow large meshes with more than 64K vertices.
// Your renderer backend will need to support it (most example renderer backends support both 16/32-bit indices).
// Another way to allow large meshes while keeping 16-bit indices is to handle ImDrawCmd::VtxOffset in your renderer.
// Read about ImGuiBackendFlags_RendererHasVtxOffset for details.
//#define ImDrawIdx unsigned int
//---- Override ImDrawCallback signature (will need to modify renderer backends accordingly)
//struct ImDrawList;
//struct ImDrawCmd;
//typedef void (*MyImDrawCallback)(const ImDrawList* draw_list, const ImDrawCmd* cmd, void* my_renderer_user_data);
//#define ImDrawCallback MyImDrawCallback
//---- Debug Tools: Macro to break in Debugger (we provide a default implementation of this in the codebase)
// (use 'Metrics->Tools->Item Picker' to pick widgets with the mouse and break into them for easy debugging.)
//#define IM_DEBUG_BREAK IM_ASSERT(0)
//#define IM_DEBUG_BREAK __debugbreak()
//---- Debug Tools: Enable slower asserts
//#define IMGUI_DEBUG_PARANOID
//---- Tip: You can add extra functions within the ImGui:: namespace from anywhere (e.g. your own sources/header files)
/*
namespace ImGui
{
void MyFunction(const char* name, MyMatrix44* mtx);
}
*/

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,627 +0,0 @@
// [DEAR IMGUI]
// This is a slightly modified version of stb_rect_pack.h 1.01.
// Grep for [DEAR IMGUI] to find the changes.
//
// stb_rect_pack.h - v1.01 - public domain - rectangle packing
// Sean Barrett 2014
//
// Useful for e.g. packing rectangular textures into an atlas.
// Does not do rotation.
//
// Before #including,
//
// #define STB_RECT_PACK_IMPLEMENTATION
//
// in the file that you want to have the implementation.
//
// Not necessarily the awesomest packing method, but better than
// the totally naive one in stb_truetype (which is primarily what
// this is meant to replace).
//
// Has only had a few tests run, may have issues.
//
// More docs to come.
//
// No memory allocations; uses qsort() and assert() from stdlib.
// Can override those by defining STBRP_SORT and STBRP_ASSERT.
//
// This library currently uses the Skyline Bottom-Left algorithm.
//
// Please note: better rectangle packers are welcome! Please
// implement them to the same API, but with a different init
// function.
//
// Credits
//
// Library
// Sean Barrett
// Minor features
// Martins Mozeiko
// github:IntellectualKitty
//
// Bugfixes / warning fixes
// Jeremy Jaussaud
// Fabian Giesen
//
// Version history:
//
// 1.01 (2021-07-11) always use large rect mode, expose STBRP__MAXVAL in public section
// 1.00 (2019-02-25) avoid small space waste; gracefully fail too-wide rectangles
// 0.99 (2019-02-07) warning fixes
// 0.11 (2017-03-03) return packing success/fail result
// 0.10 (2016-10-25) remove cast-away-const to avoid warnings
// 0.09 (2016-08-27) fix compiler warnings
// 0.08 (2015-09-13) really fix bug with empty rects (w=0 or h=0)
// 0.07 (2015-09-13) fix bug with empty rects (w=0 or h=0)
// 0.06 (2015-04-15) added STBRP_SORT to allow replacing qsort
// 0.05: added STBRP_ASSERT to allow replacing assert
// 0.04: fixed minor bug in STBRP_LARGE_RECTS support
// 0.01: initial release
//
// LICENSE
//
// See end of file for license information.
//////////////////////////////////////////////////////////////////////////////
//
// INCLUDE SECTION
//
#ifndef STB_INCLUDE_STB_RECT_PACK_H
#define STB_INCLUDE_STB_RECT_PACK_H
#define STB_RECT_PACK_VERSION 1
#ifdef STBRP_STATIC
#define STBRP_DEF static
#else
#define STBRP_DEF extern
#endif
#ifdef __cplusplus
extern "C" {
#endif
typedef struct stbrp_context stbrp_context;
typedef struct stbrp_node stbrp_node;
typedef struct stbrp_rect stbrp_rect;
typedef int stbrp_coord;
#define STBRP__MAXVAL 0x7fffffff
// Mostly for internal use, but this is the maximum supported coordinate value.
STBRP_DEF int stbrp_pack_rects (stbrp_context *context, stbrp_rect *rects, int num_rects);
// Assign packed locations to rectangles. The rectangles are of type
// 'stbrp_rect' defined below, stored in the array 'rects', and there
// are 'num_rects' many of them.
//
// Rectangles which are successfully packed have the 'was_packed' flag
// set to a non-zero value and 'x' and 'y' store the minimum location
// on each axis (i.e. bottom-left in cartesian coordinates, top-left
// if you imagine y increasing downwards). Rectangles which do not fit
// have the 'was_packed' flag set to 0.
//
// You should not try to access the 'rects' array from another thread
// while this function is running, as the function temporarily reorders
// the array while it executes.
//
// To pack into another rectangle, you need to call stbrp_init_target
// again. To continue packing into the same rectangle, you can call
// this function again. Calling this multiple times with multiple rect
// arrays will probably produce worse packing results than calling it
// a single time with the full rectangle array, but the option is
// available.
//
// The function returns 1 if all of the rectangles were successfully
// packed and 0 otherwise.
struct stbrp_rect
{
// reserved for your use:
int id;
// input:
stbrp_coord w, h;
// output:
stbrp_coord x, y;
int was_packed; // non-zero if valid packing
}; // 16 bytes, nominally
STBRP_DEF void stbrp_init_target (stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes);
// Initialize a rectangle packer to:
// pack a rectangle that is 'width' by 'height' in dimensions
// using temporary storage provided by the array 'nodes', which is 'num_nodes' long
//
// You must call this function every time you start packing into a new target.
//
// There is no "shutdown" function. The 'nodes' memory must stay valid for
// the following stbrp_pack_rects() call (or calls), but can be freed after
// the call (or calls) finish.
//
// Note: to guarantee best results, either:
// 1. make sure 'num_nodes' >= 'width'
// or 2. call stbrp_allow_out_of_mem() defined below with 'allow_out_of_mem = 1'
//
// If you don't do either of the above things, widths will be quantized to multiples
// of small integers to guarantee the algorithm doesn't run out of temporary storage.
//
// If you do #2, then the non-quantized algorithm will be used, but the algorithm
// may run out of temporary storage and be unable to pack some rectangles.
STBRP_DEF void stbrp_setup_allow_out_of_mem (stbrp_context *context, int allow_out_of_mem);
// Optionally call this function after init but before doing any packing to
// change the handling of the out-of-temp-memory scenario, described above.
// If you call init again, this will be reset to the default (false).
STBRP_DEF void stbrp_setup_heuristic (stbrp_context *context, int heuristic);
// Optionally select which packing heuristic the library should use. Different
// heuristics will produce better/worse results for different data sets.
// If you call init again, this will be reset to the default.
enum
{
STBRP_HEURISTIC_Skyline_default=0,
STBRP_HEURISTIC_Skyline_BL_sortHeight = STBRP_HEURISTIC_Skyline_default,
STBRP_HEURISTIC_Skyline_BF_sortHeight
};
//////////////////////////////////////////////////////////////////////////////
//
// the details of the following structures don't matter to you, but they must
// be visible so you can handle the memory allocations for them
struct stbrp_node
{
stbrp_coord x,y;
stbrp_node *next;
};
struct stbrp_context
{
int width;
int height;
int align;
int init_mode;
int heuristic;
int num_nodes;
stbrp_node *active_head;
stbrp_node *free_head;
stbrp_node extra[2]; // we allocate two extra nodes so optimal user-node-count is 'width' not 'width+2'
};
#ifdef __cplusplus
}
#endif
#endif
//////////////////////////////////////////////////////////////////////////////
//
// IMPLEMENTATION SECTION
//
#ifdef STB_RECT_PACK_IMPLEMENTATION
#ifndef STBRP_SORT
#include <stdlib.h>
#define STBRP_SORT qsort
#endif
#ifndef STBRP_ASSERT
#include <assert.h>
#define STBRP_ASSERT assert
#endif
#ifdef _MSC_VER
#define STBRP__NOTUSED(v) (void)(v)
#define STBRP__CDECL __cdecl
#else
#define STBRP__NOTUSED(v) (void)sizeof(v)
#define STBRP__CDECL
#endif
enum
{
STBRP__INIT_skyline = 1
};
STBRP_DEF void stbrp_setup_heuristic(stbrp_context *context, int heuristic)
{
switch (context->init_mode) {
case STBRP__INIT_skyline:
STBRP_ASSERT(heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight || heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight);
context->heuristic = heuristic;
break;
default:
STBRP_ASSERT(0);
}
}
STBRP_DEF void stbrp_setup_allow_out_of_mem(stbrp_context *context, int allow_out_of_mem)
{
if (allow_out_of_mem)
// if it's ok to run out of memory, then don't bother aligning them;
// this gives better packing, but may fail due to OOM (even though
// the rectangles easily fit). @TODO a smarter approach would be to only
// quantize once we've hit OOM, then we could get rid of this parameter.
context->align = 1;
else {
// if it's not ok to run out of memory, then quantize the widths
// so that num_nodes is always enough nodes.
//
// I.e. num_nodes * align >= width
// align >= width / num_nodes
// align = ceil(width/num_nodes)
context->align = (context->width + context->num_nodes-1) / context->num_nodes;
}
}
STBRP_DEF void stbrp_init_target(stbrp_context *context, int width, int height, stbrp_node *nodes, int num_nodes)
{
int i;
for (i=0; i < num_nodes-1; ++i)
nodes[i].next = &nodes[i+1];
nodes[i].next = NULL;
context->init_mode = STBRP__INIT_skyline;
context->heuristic = STBRP_HEURISTIC_Skyline_default;
context->free_head = &nodes[0];
context->active_head = &context->extra[0];
context->width = width;
context->height = height;
context->num_nodes = num_nodes;
stbrp_setup_allow_out_of_mem(context, 0);
// node 0 is the full width, node 1 is the sentinel (lets us not store width explicitly)
context->extra[0].x = 0;
context->extra[0].y = 0;
context->extra[0].next = &context->extra[1];
context->extra[1].x = (stbrp_coord) width;
context->extra[1].y = (1<<30);
context->extra[1].next = NULL;
}
// find minimum y position if it starts at x1
static int stbrp__skyline_find_min_y(stbrp_context *c, stbrp_node *first, int x0, int width, int *pwaste)
{
stbrp_node *node = first;
int x1 = x0 + width;
int min_y, visited_width, waste_area;
STBRP__NOTUSED(c);
STBRP_ASSERT(first->x <= x0);
#if 0
// skip in case we're past the node
while (node->next->x <= x0)
++node;
#else
STBRP_ASSERT(node->next->x > x0); // we ended up handling this in the caller for efficiency
#endif
STBRP_ASSERT(node->x <= x0);
min_y = 0;
waste_area = 0;
visited_width = 0;
while (node->x < x1) {
if (node->y > min_y) {
// raise min_y higher.
// we've accounted for all waste up to min_y,
// but we'll now add more waste for everything we've visted
waste_area += visited_width * (node->y - min_y);
min_y = node->y;
// the first time through, visited_width might be reduced
if (node->x < x0)
visited_width += node->next->x - x0;
else
visited_width += node->next->x - node->x;
} else {
// add waste area
int under_width = node->next->x - node->x;
if (under_width + visited_width > width)
under_width = width - visited_width;
waste_area += under_width * (min_y - node->y);
visited_width += under_width;
}
node = node->next;
}
*pwaste = waste_area;
return min_y;
}
typedef struct
{
int x,y;
stbrp_node **prev_link;
} stbrp__findresult;
static stbrp__findresult stbrp__skyline_find_best_pos(stbrp_context *c, int width, int height)
{
int best_waste = (1<<30), best_x, best_y = (1 << 30);
stbrp__findresult fr;
stbrp_node **prev, *node, *tail, **best = NULL;
// align to multiple of c->align
width = (width + c->align - 1);
width -= width % c->align;
STBRP_ASSERT(width % c->align == 0);
// if it can't possibly fit, bail immediately
if (width > c->width || height > c->height) {
fr.prev_link = NULL;
fr.x = fr.y = 0;
return fr;
}
node = c->active_head;
prev = &c->active_head;
while (node->x + width <= c->width) {
int y,waste;
y = stbrp__skyline_find_min_y(c, node, node->x, width, &waste);
if (c->heuristic == STBRP_HEURISTIC_Skyline_BL_sortHeight) { // actually just want to test BL
// bottom left
if (y < best_y) {
best_y = y;
best = prev;
}
} else {
// best-fit
if (y + height <= c->height) {
// can only use it if it first vertically
if (y < best_y || (y == best_y && waste < best_waste)) {
best_y = y;
best_waste = waste;
best = prev;
}
}
}
prev = &node->next;
node = node->next;
}
best_x = (best == NULL) ? 0 : (*best)->x;
// if doing best-fit (BF), we also have to try aligning right edge to each node position
//
// e.g, if fitting
//
// ____________________
// |____________________|
//
// into
//
// | |
// | ____________|
// |____________|
//
// then right-aligned reduces waste, but bottom-left BL is always chooses left-aligned
//
// This makes BF take about 2x the time
if (c->heuristic == STBRP_HEURISTIC_Skyline_BF_sortHeight) {
tail = c->active_head;
node = c->active_head;
prev = &c->active_head;
// find first node that's admissible
while (tail->x < width)
tail = tail->next;
while (tail) {
int xpos = tail->x - width;
int y,waste;
STBRP_ASSERT(xpos >= 0);
// find the left position that matches this
while (node->next->x <= xpos) {
prev = &node->next;
node = node->next;
}
STBRP_ASSERT(node->next->x > xpos && node->x <= xpos);
y = stbrp__skyline_find_min_y(c, node, xpos, width, &waste);
if (y + height <= c->height) {
if (y <= best_y) {
if (y < best_y || waste < best_waste || (waste==best_waste && xpos < best_x)) {
best_x = xpos;
//STBRP_ASSERT(y <= best_y); [DEAR IMGUI]
best_y = y;
best_waste = waste;
best = prev;
}
}
}
tail = tail->next;
}
}
fr.prev_link = best;
fr.x = best_x;
fr.y = best_y;
return fr;
}
static stbrp__findresult stbrp__skyline_pack_rectangle(stbrp_context *context, int width, int height)
{
// find best position according to heuristic
stbrp__findresult res = stbrp__skyline_find_best_pos(context, width, height);
stbrp_node *node, *cur;
// bail if:
// 1. it failed
// 2. the best node doesn't fit (we don't always check this)
// 3. we're out of memory
if (res.prev_link == NULL || res.y + height > context->height || context->free_head == NULL) {
res.prev_link = NULL;
return res;
}
// on success, create new node
node = context->free_head;
node->x = (stbrp_coord) res.x;
node->y = (stbrp_coord) (res.y + height);
context->free_head = node->next;
// insert the new node into the right starting point, and
// let 'cur' point to the remaining nodes needing to be
// stiched back in
cur = *res.prev_link;
if (cur->x < res.x) {
// preserve the existing one, so start testing with the next one
stbrp_node *next = cur->next;
cur->next = node;
cur = next;
} else {
*res.prev_link = node;
}
// from here, traverse cur and free the nodes, until we get to one
// that shouldn't be freed
while (cur->next && cur->next->x <= res.x + width) {
stbrp_node *next = cur->next;
// move the current node to the free list
cur->next = context->free_head;
context->free_head = cur;
cur = next;
}
// stitch the list back in
node->next = cur;
if (cur->x < res.x + width)
cur->x = (stbrp_coord) (res.x + width);
#ifdef _DEBUG
cur = context->active_head;
while (cur->x < context->width) {
STBRP_ASSERT(cur->x < cur->next->x);
cur = cur->next;
}
STBRP_ASSERT(cur->next == NULL);
{
int count=0;
cur = context->active_head;
while (cur) {
cur = cur->next;
++count;
}
cur = context->free_head;
while (cur) {
cur = cur->next;
++count;
}
STBRP_ASSERT(count == context->num_nodes+2);
}
#endif
return res;
}
static int STBRP__CDECL rect_height_compare(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
if (p->h > q->h)
return -1;
if (p->h < q->h)
return 1;
return (p->w > q->w) ? -1 : (p->w < q->w);
}
static int STBRP__CDECL rect_original_order(const void *a, const void *b)
{
const stbrp_rect *p = (const stbrp_rect *) a;
const stbrp_rect *q = (const stbrp_rect *) b;
return (p->was_packed < q->was_packed) ? -1 : (p->was_packed > q->was_packed);
}
STBRP_DEF int stbrp_pack_rects(stbrp_context *context, stbrp_rect *rects, int num_rects)
{
int i, all_rects_packed = 1;
// we use the 'was_packed' field internally to allow sorting/unsorting
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = i;
}
// sort according to heuristic
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_height_compare);
for (i=0; i < num_rects; ++i) {
if (rects[i].w == 0 || rects[i].h == 0) {
rects[i].x = rects[i].y = 0; // empty rect needs no space
} else {
stbrp__findresult fr = stbrp__skyline_pack_rectangle(context, rects[i].w, rects[i].h);
if (fr.prev_link) {
rects[i].x = (stbrp_coord) fr.x;
rects[i].y = (stbrp_coord) fr.y;
} else {
rects[i].x = rects[i].y = STBRP__MAXVAL;
}
}
}
// unsort
STBRP_SORT(rects, num_rects, sizeof(rects[0]), rect_original_order);
// set was_packed flags and all_rects_packed status
for (i=0; i < num_rects; ++i) {
rects[i].was_packed = !(rects[i].x == STBRP__MAXVAL && rects[i].y == STBRP__MAXVAL);
if (!rects[i].was_packed)
all_rects_packed = 0;
}
// return the all_rects_packed status
return all_rects_packed;
}
#endif
/*
------------------------------------------------------------------------------
This software is available under 2 licenses -- choose whichever you prefer.
------------------------------------------------------------------------------
ALTERNATIVE A - MIT License
Copyright (c) 2017 Sean Barrett
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
------------------------------------------------------------------------------
ALTERNATIVE B - Public Domain (www.unlicense.org)
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
software, either in source code form or as a compiled binary, for any purpose,
commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
*/

File diff suppressed because it is too large Load Diff

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