-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathkarl2d.odin
More file actions
2685 lines (2219 loc) · 73.4 KB
/
Copy pathkarl2d.odin
File metadata and controls
2685 lines (2219 loc) · 73.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#+vet explicit-allocators
package karl2d
import "base:runtime"
import "core:mem"
import "log"
import "core:math"
import "core:math/linalg"
import "core:slice"
import "core:strings"
import "core:reflect"
import "core:os"
import "core:time"
import fs "vendor:fontstash"
import "core:image"
import "core:image/jpeg"
import "core:image/bmp"
import "core:image/png"
import "core:image/tga"
import hm "handle_map"
//-----------------------------------------------//
// SETUP, WINDOW MANAGEMENT AND FRAME MANAGEMENT //
//-----------------------------------------------//
// Opens a window and initializes some internal state. The internal state will use `allocator` for
// all dynamically allocated memory. The return value can be ignored unless you need to later call
// `set_internal_state`.
//
// `screen_width` and `screen_height` refer to the the resolution of the drawable area of the
// window. The window might be slightly larger due borders and headers.
init :: proc(
screen_width: int,
screen_height: int,
window_title: string,
options := Init_Options {},
allocator := context.allocator,
loc := #caller_location
) -> ^State {
assert(s == nil, "Don't call 'init' twice.")
context.allocator = allocator
s = new(State, allocator, loc)
// This is the same type of arena as the default temp allocator. This arena is for allocations
// that have a lifetime of "one frame". They are valid until you call `present()`, at which
// point the frame allocator is cleared.
s.frame_allocator = runtime.arena_allocator(&s.frame_arena)
frame_allocator = s.frame_allocator
s.allocator = allocator
when ODIN_OS == .Windows {
s.platform = PLATFORM_WINDOWS
} else when ODIN_OS == .JS {
s.platform = PLATFORM_WEB
} else when ODIN_OS == .Linux {
s.platform = PLATFORM_LINUX
} else when ODIN_OS == .Darwin {
s.platform = PLATFORM_MAC
} else {
#panic("Unsupported platform")
}
pf = s.platform
// We alloc memory for the windowing backend and pass the blob of memory to it.
platform_state_alloc_error: runtime.Allocator_Error
s.platform_state, platform_state_alloc_error = mem.alloc(
pf.state_size(),
allocator = allocator,
)
log.assertf(
platform_state_alloc_error == nil,
"Failed allocating memory for platform state: %v",
platform_state_alloc_error,
)
pf.init(s.platform_state, screen_width, screen_height, window_title, options, allocator)
// This is a OS-independent handle that we can pass to any rendering backend.
window_render_glue := pf.get_window_render_glue()
// See `render_backend_chooser.odin` for how this is picked.
s.render_backend = RENDER_BACKEND
rb = s.render_backend
rb_alloc_error: runtime.Allocator_Error
s.render_backend_state, rb_alloc_error = mem.alloc(rb.state_size(), allocator = allocator)
log.assertf(rb_alloc_error == nil, "Failed allocating memory for rendering backend: %v", rb_alloc_error)
s.proj_matrix = make_default_projection(pf.get_width(), pf.get_height())
s.view_matrix = 1
// Boot up the render backend. It will render into our previously created window.
rb.init(s.render_backend_state, window_render_glue, pf.get_width(), pf.get_height(), allocator)
// The vertex buffer is created in a render backend-independent way. It is passed to the
// render backend each frame as part of `draw_current_batch()`
s.vertex_buffer_cpu = make([]u8, VERTEX_BUFFER_MAX, allocator, loc)
// The shapes drawing texture is sampled when any shape is drawn. This way we can use the same
// shader for textured drawing and shape drawing. It's just a white box.
white_rect: [16*16*4]u8
slice.fill(white_rect[:], 255)
s.shape_drawing_texture = rb.load_texture(white_rect[:], 16, 16, .RGBA_8_Norm)
// The default shader will arrive in a different format depending on backend. GLSL for GL,
// HLSL for d3d etc.
s.default_shader = load_shader_from_bytes(rb.default_shader_vertex_source(), rb.default_shader_fragment_source())
s.batch_shader = s.default_shader
// FontStash enables us to bake fonts from TTF files on-the-fly.
fs.Init(&s.fs, FONT_DEFAULT_ATLAS_SIZE, FONT_DEFAULT_ATLAS_SIZE, .TOPLEFT)
fs.SetAlignVertical(&s.fs, .TOP)
DEFAULT_FONT_DATA :: #load("roboto.ttf")
// Dummy element so font with index 0 means 'no font'.
append_nothing(&s.fonts)
s.default_font = load_font_from_bytes(DEFAULT_FONT_DATA)
_set_font(s.default_font)
return s
}
// Updates the internal state of the library. Call this early in the frame to make sure inputs and
// frame times are up-to-date.
//
// Returns a bool that says if the player has attempted to close the window. It's up to the
// application to decide if it wants to shut down or if it (for example) wants to show a
// confirmation dialogue.
//
// Commonly used for creating the "main loop" of a game: `for k2.update() {}`
//
// To get more control over how the frame is set up, you can skip calling this proc and instead use
// the procs it calls directly:
//
//// for {
//// k2.reset_frame_allocator()
//// k2.calculate_frame_time()
//// k2.process_events()
////
//// k2.clear(k2.BLUE)
//// k2.present()
////
//// if k2.close_window_requested() {
//// break
//// }
//// }
update :: proc() -> bool {
reset_frame_allocator()
calculate_frame_time()
process_events()
return !close_window_requested()
}
// Returns true the user has pressed the close button on the window, or used a key stroke such as
// ALT+F4 on Windows. The application can decide if it wants to shut down or if it wants to show
// some kind of confirmation dialogue.
//
// Called by `update`, but can be called manually if you need more control.
close_window_requested :: proc() -> bool {
return s.close_window_requested
}
// Closes the window and cleans up Karl2D's internal state.
shutdown :: proc() {
assert(s != nil, "You've called 'shutdown' without calling 'init' first")
delete(s.events)
destroy_font(s.default_font)
rb.destroy_texture(s.shape_drawing_texture)
destroy_shader(s.default_shader)
rb.shutdown()
delete(s.vertex_buffer_cpu, s.allocator)
pf.shutdown()
fs.Destroy(&s.fs)
delete(s.fonts)
a := s.allocator
free(s.platform_state, a)
free(s.render_backend_state, a)
free(s, a)
s = nil
}
// Clear the "screen" with the supplied color. By default this will clear your window. But if you
// have set a Render Texture using the `set_render_texture` procedure, then that Render Texture will
// be cleared instead.
clear :: proc(color: Color) {
draw_current_batch()
rb.clear(s.batch_render_target, color)
}
// The library may do some internal allocations that have the lifetime of a single frame. This
// procedure empties that Frame Allocator.
//
// Called as part of `update`, but can be called manually if you need more control.
reset_frame_allocator :: proc() {
free_all(s.frame_allocator)
}
// Calculates how long the previous frame took and how it has been since the application started.
// You can fetch the calculated values using `get_frame_time` and `get_time`.
//
// Called as part of `update`, but can be called manually if you need more control.
calculate_frame_time :: proc() {
now := time.now()
if s.prev_frame_time != {} {
since := time.diff(s.prev_frame_time, now)
s.frame_time = f32(time.duration_seconds(since))
}
s.prev_frame_time = now
if s.start_time == {} {
s.start_time = time.now()
}
s.time = time.duration_seconds(time.since(s.start_time))
}
// Present the drawn stuff to the player. Also known as "flipping the backbuffer": Call at end of
// frame to make everything you've drawn appear on the screen.
//
// When you draw using for example `draw_texture`, then that stuff is drawn to an invisible texture
// called a "backbuffer". This makes sure that we don't see half-drawn frames. So when you are happy
// with a frame and want to show it to the player, call this procedure.
//
// WebGL note: WebGL does the backbuffer flipping automatically. But you should still call this to
// make sure that all rendering has been sent off to the GPU (as it calls `draw_current_batch()`).
present :: proc() {
draw_current_batch()
rb.present()
}
// Process all events that have arrived from the platform APIs. This includes keyboard, mouse,
// gamepad and window events. This procedure processes and stores the information that procs like
// `key_went_down` need.
//
// Called by `update`, but can be called manually if you need more control.
process_events :: proc() {
s.key_went_up = {}
s.key_went_down = {}
s.mouse_button_went_up = {}
s.mouse_button_went_down = {}
s.gamepad_button_went_up = {}
s.gamepad_button_went_down = {}
s.mouse_delta = {}
s.mouse_wheel_delta = 0
runtime.clear(&s.events)
pf.get_events(&s.events)
for &event in s.events {
switch &e in event {
case Event_Close_Window_Requested:
s.close_window_requested = true
case Event_Key_Went_Down:
s.key_went_down[e.key] = true
s.key_is_held[e.key] = true
case Event_Key_Went_Up:
s.key_went_up[e.key] = true
s.key_is_held[e.key] = false
case Event_Mouse_Button_Went_Down:
s.mouse_button_went_down[e.button] = true
s.mouse_button_is_held[e.button] = true
case Event_Mouse_Button_Went_Up:
s.mouse_button_went_up[e.button] = true
s.mouse_button_is_held[e.button] = false
case Event_Mouse_Move:
prev_pos := s.mouse_position
s.mouse_position.x = e.position.x
s.mouse_position.y = e.position.y
s.mouse_delta = s.mouse_position - prev_pos
case Event_Mouse_Wheel:
s.mouse_wheel_delta = e.delta
case Event_Gamepad_Button_Went_Down:
if e.gamepad < MAX_GAMEPADS {
s.gamepad_button_went_down[e.gamepad][e.button] = true
s.gamepad_button_is_held[e.gamepad][e.button] = true
}
case Event_Gamepad_Button_Went_Up:
if e.gamepad < MAX_GAMEPADS {
s.gamepad_button_went_up[e.gamepad][e.button] = true
s.gamepad_button_is_held[e.gamepad][e.button] = false
}
case Event_Resize:
rb.resize_swapchain(e.width, e.height)
s.proj_matrix = make_default_projection(e.width, e.height)
case Event_Window_Focused:
case Event_Window_Unfocused:
for k in Keyboard_Key {
if s.key_is_held[k] {
s.key_is_held[k] = false
s.key_went_up[k] = true
}
}
for b in Mouse_Button {
if s.mouse_button_is_held[b] {
s.mouse_button_is_held[b] = false
s.mouse_button_went_up[b] = true
}
}
for gp in 0..<MAX_GAMEPADS {
for b in Gamepad_Button {
if s.gamepad_button_is_held[gp][b] {
s.gamepad_button_is_held[gp][b] = false
s.gamepad_button_went_up[gp][b] = true
}
}
}
}
}
}
// Fetch a list of all events that happened this frame. Most games can use the `key_is_held`,
// `mouse_button_went_down` etc procedures to check input state. But if you want a list of events
// instead, then you can use this. These events will also include things like "Window Focus" events
// and "Window Resize" events.
//
// Note: Gamepad axis movement (analogue sticks and analogue triggers) are _not_ events. Those can
// only be queried using `k2.get_gamepad_axis`.
//
// Warning: The returned slice is only valid during the current frame! You can make a clone of it
// using the `slice.clone` procedure (import `core:slice`).
get_events :: proc() -> []Event {
return s.events[:]
}
// Returns how many seconds the previous frame took. Often a tiny number such as 0.016 s.
//
// This value is updated when `calculate_frame_time()` runs (which is also called by `update()`).
get_frame_time :: proc() -> f32 {
return s.frame_time
}
// Returns how many seconds has elapsed since the game started. This is a `f64` number, giving good
// precision when the application runs for a long time.
//
// This value is updated when `calculate_frame_time()` runs (which is also called by `update()`).
get_time :: proc() -> f64 {
return s.time
}
// Gets the width of the drawing area within the window.
get_screen_width :: proc() -> int {
return pf.get_width()
}
// Gets the height of the drawing area within the window.
get_screen_height :: proc() -> int {
return pf.get_height()
}
// Moves the window.
//
// This does nothing for web builds.
set_window_position :: proc(x: int, y: int) {
pf.set_position(x, y)
}
// Resize the window to a new size. While the user cannot resize windows with
// `window_mode == .Windowed_Resizable`, this procedure will resize them.
set_window_size :: proc(width: int, height: int) {
// TODO not sure if we should resize swapchain here. On windows the WM_SIZE event fires and
// it all works out. But perhaps not on all platforms?
pf.set_size(width, height)
}
// Fetch the scale of the window. This usually comes from some DPI scaling setting in the OS.
// 1 means 100% scale, 1.5 means 150% etc.
get_window_scale :: proc() -> f32 {
return pf.get_window_scale()
}
// Use to change between windowed mode, resizable windowed mode and fullscreen
set_window_mode :: proc(window_mode: Window_Mode) {
pf.set_window_mode(window_mode)
}
// Flushes the current batch. This sends off everything to the GPU that has been queued in the
// current batch. Normally, you do not need to do this manually. It is done automatically when these
// procedures run:
//
// - present
// - set_camera
// - set_shader
// - set_shader_constant
// - set_scissor_rect
// - set_blend_mode
// - set_render_texture
// - clear
// - draw_texture_* IF previous draw did not use the same texture (1)
// - draw_rect_*, draw_circle_*, draw_line IF previous draw did not use the shapes drawing texture (2)
//
// (1) When drawing textures, the current texture is fed into the active shader. Everything within
// the same batch must use the same texture. So drawing with a new texture forces the current to
// be drawn. You can combine several textures into an atlas to get bigger batches.
//
// (2) In order to use the same shader for shapes drawing and textured drawing, the shapes drawing
// uses a blank, white texture. For the same reasons as (1), drawing something else than shapes
// before drawing a shape will break up the batches. In a future update I'll add so that you can
// set your own shapes drawing texture, making it possible to combine it with a bigger atlas.
//
// The batch has maximum size of VERTEX_BUFFER_MAX bytes. The shader dictates how big a vertex is
// so the maximum number of vertices that can be drawn in each batch is
// VERTEX_BUFFER_MAX / shader.vertex_size
draw_current_batch :: proc() {
if s.vertex_buffer_cpu_used == 0 {
return
}
_update_font(s.batch_font)
shader := s.batch_shader
view_projection := s.proj_matrix * s.view_matrix
for mloc, builtin in shader.constant_builtin_locations {
constant, constant_ok := mloc.?
if !constant_ok {
continue
}
switch builtin {
case .View_Projection_Matrix:
if constant.size == size_of(view_projection) {
dst := (^matrix[4,4]f32)(&shader.constants_data[constant.offset])
dst^ = view_projection
}
}
}
if def_tex_idx, has_def_tex_idx := shader.default_texture_index.?; has_def_tex_idx {
shader.texture_bindpoints[def_tex_idx] = s.batch_texture
}
rb.draw(shader, s.batch_render_target, shader.texture_bindpoints, s.batch_scissor, s.batch_blend_mode, s.vertex_buffer_cpu[:s.vertex_buffer_cpu_used])
s.vertex_buffer_cpu_used = 0
}
//-------//
// INPUT //
//-------//
// Returns true if a keyboard key went down between the current and the previous frame. Set when
// 'process_events' runs.
key_went_down :: proc(key: Keyboard_Key) -> bool {
return s.key_went_down[key]
}
// Returns true if a keyboard key went up (was released) between the current and the previous frame.
// Set when 'process_events' runs.
key_went_up :: proc(key: Keyboard_Key) -> bool {
return s.key_went_up[key]
}
// Returns true if a keyboard is currently being held down. Set when 'process_events' runs.
key_is_held :: proc(key: Keyboard_Key) -> bool {
return s.key_is_held[key]
}
// Returns true if a mouse button went down between the current and the previous frame. Specify
// which mouse button using the `button` parameter.
//
// Set when 'process_events' runs.
mouse_button_went_down :: proc(button: Mouse_Button) -> bool {
return s.mouse_button_went_down[button]
}
// Returns true if a mouse button went up (was released) between the current and the previous frame.
// Specify which mouse button using the `button` parameter.
//
// Set when 'process_events' runs.
mouse_button_went_up :: proc(button: Mouse_Button) -> bool {
return s.mouse_button_went_up[button]
}
// Returns true if a mouse button is currently being held down. Specify which mouse button using the
// `button` parameter. Set when 'process_events' runs.
mouse_button_is_held :: proc(button: Mouse_Button) -> bool {
return s.mouse_button_is_held[button]
}
// Returns how many clicks the mouse wheel has scrolled between the previous and current frame.
get_mouse_wheel_delta :: proc() -> f32 {
return s.mouse_wheel_delta
}
// Returns the mouse position, measured from the top-left corner of the window.
get_mouse_position :: proc() -> Vec2 {
return s.mouse_position
}
// Returns how many pixels the mouse moved between the previous and the current frame.
get_mouse_delta :: proc() -> Vec2 {
return s.mouse_delta
}
// Returns true if a gamepad with the supplied index is connected. The parameter should be a value
// between 0 and MAX_GAMEPADS.
is_gamepad_active :: proc(gamepad: Gamepad_Index) -> bool {
return pf.is_gamepad_active(gamepad)
}
// Returns true if a gamepad button went down between the previous and the current frame.
gamepad_button_went_down :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
if gamepad < 0 || gamepad >= MAX_GAMEPADS {
return false
}
return s.gamepad_button_went_down[gamepad][button]
}
// Returns true if a gamepad button went up (was released) between the previous and the current
// frame.
gamepad_button_went_up :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
if gamepad < 0 || gamepad >= MAX_GAMEPADS {
return false
}
return s.gamepad_button_went_up[gamepad][button]
}
// Returns true if a gamepad button is currently held down.
//
// The "trigger buttons" on some gamepads also have an analogue "axis value" associated with them.
// Fetch that value using `get_gamepad_axis()`.
gamepad_button_is_held :: proc(gamepad: Gamepad_Index, button: Gamepad_Button) -> bool {
if gamepad < 0 || gamepad >= MAX_GAMEPADS {
return false
}
return s.gamepad_button_is_held[gamepad][button]
}
// Returns the value of analogue gamepad axes such as the thumbsticks and trigger buttons. The value
// is in the range -1 to 1 for sticks and 0 to 1 for trigger buttons.
get_gamepad_axis :: proc(gamepad: Gamepad_Index, axis: Gamepad_Axis) -> f32 {
return pf.get_gamepad_axis(gamepad, axis)
}
// Set the left and right vibration motor speed. The range of left and right is 0 to 1. Note that on
// most gamepads, the left motor is "low frequency" and the right motor is "high frequency". They do
// not vibrate with the same speed.
set_gamepad_vibration :: proc(gamepad: Gamepad_Index, left: f32, right: f32) {
pf.set_gamepad_vibration(gamepad, left, right)
}
//---------//
// DRAWING //
//---------//
// Draw a colored rectangle. The rectangles have their (x, y) position in the top-left corner of the
// rectangle.
draw_rect :: proc(r: Rect, c: Color) {
if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
draw_current_batch()
}
if s.batch_texture != s.shape_drawing_texture {
draw_current_batch()
}
s.batch_texture = s.shape_drawing_texture
z := f32(0)
batch_vertex({r.x, r.y}, {0, 0}, c)
batch_vertex({r.x + r.w, r.y}, {1, 0}, c)
batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
batch_vertex({r.x, r.y}, {0, 0}, c)
batch_vertex({r.x + r.w, r.y + r.h}, {1, 1}, c)
batch_vertex({r.x, r.y + r.h}, {0, 1}, c)
}
// Creates a rectangle from a position and a size and draws it.
draw_rect_vec :: proc(pos: Vec2, size: Vec2, c: Color) {
draw_rect({pos.x, pos.y, size.x, size.y}, c)
}
// Draw a rectangle with a custom origin and rotation.
//
// The origin says which point the rotation rotates around. If the origin is `(0, 0)`, then the
// rectangle rotates around the top-left corner of the rectangle. If it is `(rect.w/2, rect.h/2)`
// then the rectangle rotates around its center.
//
// Rotation unit: Radians.
draw_rect_ex :: proc(r: Rect, origin: Vec2, rot: f32, c: Color) {
if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 6 > len(s.vertex_buffer_cpu) {
draw_current_batch()
}
if s.batch_texture != s.shape_drawing_texture {
draw_current_batch()
}
s.batch_texture = s.shape_drawing_texture
tl, tr, bl, br: Vec2
// Rotation adapted from Raylib's "DrawTexturePro"
if rot == 0 {
x := r.x - origin.x
y := r.y - origin.y
tl = { x, y }
tr = { x + r.w, y }
bl = { x, y + r.h }
br = { x + r.w, y + r.h }
} else {
sin_rot := math.sin(rot)
cos_rot := math.cos(rot)
x := r.x
y := r.y
dx := -origin.x
dy := -origin.y
tl = {
x + dx * cos_rot - dy * sin_rot,
y + dx * sin_rot + dy * cos_rot,
}
tr = {
x + (dx + r.w) * cos_rot - dy * sin_rot,
y + (dx + r.w) * sin_rot + dy * cos_rot,
}
bl = {
x + dx * cos_rot - (dy + r.h) * sin_rot,
y + dx * sin_rot + (dy + r.h) * cos_rot,
}
br = {
x + (dx + r.w) * cos_rot - (dy + r.h) * sin_rot,
y + (dx + r.w) * sin_rot + (dy + r.h) * cos_rot,
}
}
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
}
// Draw the outline of a rectangle with a specific thickness. The outline is drawn using four
// rectangles.
draw_rect_outline :: proc(r: Rect, thickness: f32, color: Color) {
t := thickness
// Based on DrawRectangleLinesEx from Raylib
top := Rect {
r.x,
r.y,
r.w,
t,
}
bottom := Rect {
r.x,
r.y + r.h - t,
r.w,
t,
}
left := Rect {
r.x,
r.y + t,
t,
r.h - t * 2,
}
right := Rect {
r.x + r.w - t,
r.y + t,
t,
r.h - t * 2,
}
draw_rect(top, color)
draw_rect(bottom, color)
draw_rect(left, color)
draw_rect(right, color)
}
// Draw rectangle with rounded edges
// Segments represents how many triangles the corners will have multiplied by 2
draw_rect_rounded::proc(rec: Rect, roundness: f32, c: Color, origin: Vec2 = 0, rot: f32 = 0, segments: int = 3,) {
roundness:=roundness
segments:=segments * 2
// Not a rounded rectangle
if roundness <= 0 {
draw_rect_ex(rec, origin, rot, c)
return
}
if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * ((6 * segments)+(6*5)) > len(s.vertex_buffer_cpu) {
draw_current_batch()
}
if s.batch_texture != s.shape_drawing_texture {
draw_current_batch()
}
s.batch_texture = s.shape_drawing_texture
// clamps the roundness value to 1
if roundness >= 1 {
roundness = 1
}
// Calculate corner radius
radius :f32
if rec.w > rec.h {
radius = (rec.h * roundness) / 2
}else{
radius = (rec.w * roundness) / 2
}
if radius <= 0 {
return
}
stepLength:f32 = 90 / cast(f32)segments
// Diagram points and part of the math was adapted from Raylib's "DrawRectangleRounded"
/*
Quick sketch to make sense of all of this,
there are 9 parts to draw, also mark the 12 points we'll use
P0____________________P1
/| |\
/1| 2 |3\
P7 /__|____________________|__\ P2
| |P8 P9| |
| 8 | 9 | 4 |
| __|____________________|__ |
P6 \ |P11 P10| / P3
\7| 6 |5/
\|____________________|/
P5 P4
*/
// Coordinates of the 12 points that define the rounded rect
point:[12]Vec2
point = {
{ rec.x + radius-origin.x, rec.y - origin.y}, // P0
{(rec.x + rec.w) - radius-origin.x, rec.y - origin.y}, // P1
{ rec.x + rec.w-origin.x, rec.y + radius - origin.y}, // P2
{ rec.x + rec.w-origin.x, (rec.y + rec.h) - radius - origin.y}, // P3
{(rec.x + rec.w) - radius-origin.x, rec.y + rec.h - origin.y}, // P4
{ rec.x + radius-origin.x, rec.y + rec.h - origin.y}, // P5
{ rec.x - origin.x, (rec.y + rec.h) - radius - origin.y}, // P6
{ rec.x - origin.x, rec.y + radius - origin.y}, // P7
{ rec.x + radius-origin.x, rec.y + radius - origin.y}, // P8
{(rec.x + rec.w) - radius-origin.x, rec.y + radius - origin.y}, // P9
{(rec.x + rec.w) - radius-origin.x, (rec.y + rec.h) - radius - origin.y}, // P10
{ rec.x + radius-origin.x, (rec.y + rec.h) - radius - origin.y} // P11
}
centers:[4]Vec2= { point[8], point[9], point[10], point[11] }// The center of the 4 rounded corners
angles:[4]f32 = { 180, 270, 0, 90 }
tl, tr, bl, br :Vec2
if rot != 0 {
sin_rot := math.sin(rot)
cos_rot := math.cos(rot)
x :f32= rec.x
y :f32= rec.y
dx :f32= -rec.x
dy :f32= -rec.y
point[0] = {
x + (dx + point[0].x) * cos_rot - (dy + point[0].y) * sin_rot,
y + (dx + point[0].x) * sin_rot + (dy + point[0].y) * cos_rot,
}
point[1] = {
x + (dx + point[1].x) * cos_rot - (dy + point[1].y) * sin_rot,
y + (dx + point[1].x) * sin_rot + (dy + point[1].y) * cos_rot,
}
point[2] = {
x + (dx + point[2].x) * cos_rot - (dy + point[2].y) * sin_rot,
y + (dx + point[2].x) * sin_rot + (dy + point[2].y) * cos_rot,
}
point[3] = {
x + (dx + point[3].x) * cos_rot - (dy + point[3].y) * sin_rot,
y + (dx + point[3].x) * sin_rot + (dy + point[3].y) * cos_rot,
}
point[4] = {
x + (dx + point[4].x) * cos_rot - (dy + point[4].y) * sin_rot,
y + (dx + point[4].x) * sin_rot + (dy + point[4].y) * cos_rot,
}
point[5] = {
x + (dx + point[5].x) * cos_rot - (dy + point[5].y) * sin_rot,
y + (dx + point[5].x) * sin_rot + (dy + point[5].y) * cos_rot,
}
point[6] = {
x + (dx + point[6].x) * cos_rot - (dy + point[6].y) * sin_rot,
y + (dx + point[6].x) * sin_rot + (dy + point[6].y) * cos_rot,
}
point[7] = {
x + (dx + point[7].x) * cos_rot - (dy + point[7].y) * sin_rot,
y + (dx + point[7].x) * sin_rot + (dy + point[7].y) * cos_rot,
}
point[8] = {
x + (dx + point[8].x) * cos_rot - (dy + point[8].y) * sin_rot,
y + (dx + point[8].x) * sin_rot + (dy + point[8].y) * cos_rot,
}
point[9] = {
x + (dx + point[9].x) * cos_rot - (dy + point[9].y) * sin_rot,
y + (dx + point[9].x) * sin_rot + (dy + point[9].y) * cos_rot,
}
point[10] = {
x + (dx + point[10].x) * cos_rot - (dy + point[10].y) * sin_rot,
y + (dx + point[10].x) * sin_rot + (dy + point[10].y) * cos_rot,
}
point[11] = {
x + (dx + point[11].x) * cos_rot - (dy + point[11].y) * sin_rot,
y + (dx + point[11].x) * sin_rot + (dy + point[11].y) * cos_rot,
}
}
// Draw all the 4 corners:
// [1] Upper Left Corner,
// [3] Upper Right Corner,
// [5] Lower Right Corner,
// [7] Lower Left Corner
for k :int= 0; k < 4; k+=1 {
angle :f32= angles[k]
center :Vec2= centers[k]
// NOTE: Every QUAD actually represents two segments
for i:int = 0; i < segments/2; i+=1 {
// Rotation adapted from Raylib's "DrawTexturePro"
if rot == 0 {
x := center.x
y := center.y
tl = { x,y }
tr = {
x + math.cos_f32((math.PI/180)*(angle + stepLength*2))*radius,
y + math.sin_f32((math.PI/180)*(angle + stepLength*2))*radius,
}
bl = {
x + math.cos_f32((math.PI/180)*(angle + stepLength))*radius,
y + math.sin_f32((math.PI/180)*(angle + stepLength))*radius,
}
br = {
x + math.cos_f32((math.PI/180)*angle)*radius,
y + math.sin_f32((math.PI/180)*angle)*radius,
}
} else {
sin_rot := math.sin(rot)
cos_rot := math.cos(rot)
x := rec.x
y := rec.y
dx :f32= center.x-x
dy :f32= center.y-y
tl = {
x + (dx) * cos_rot - (dy) * sin_rot,
y + (dx) * sin_rot + (dy) * cos_rot,
}
tr_cos_rot := math.cos_f32((math.PI/180)*(angle + stepLength*2))*radius
tr_sin_rot := math.sin_f32((math.PI/180)*(angle + stepLength*2))*radius
tr = {
x + (dx + tr_cos_rot) * cos_rot - (dy + tr_sin_rot) * sin_rot,
y + (dx + tr_cos_rot) * sin_rot + (dy + tr_sin_rot) * cos_rot,
}
bl_cos_rot := math.cos_f32((math.PI/180)*(angle + stepLength))*radius
bl_sin_rot := math.sin_f32((math.PI/180)*(angle + stepLength))*radius
bl = {
x + (dx + bl_cos_rot) * cos_rot - (dy + bl_sin_rot) * sin_rot,
y + (dx + bl_cos_rot) * sin_rot + (dy + bl_sin_rot) * cos_rot,
}
br_cos_rot := math.cos_f32((math.PI/180)*angle)*radius
br_sin_rot := math.sin_f32((math.PI/180)*angle)*radius
br = {
x + (dx + br_cos_rot) * cos_rot - (dy + br_sin_rot) * sin_rot,
y + (dx + br_cos_rot) * sin_rot + (dy + br_sin_rot) * cos_rot,
}
}
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 0}, c)
batch_vertex(bl, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
angle += (stepLength*2)
}
}
// [2] Upper Rectangle
tl = point[0]
tr = point[8]
bl = point[1]
br = point[9]
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
// [4] Right Rectangle
tl = point[2]
tr = point[9]
bl = point[3]
br = point[10]
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
// [6] Bottom Rectangle
tl = point[11]
tr = point[5]
bl = point[10]
br = point[4]
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
// [8] Left Rectangle
tl = point[7]
tr = point[6]
bl = point[8]
br = point[11]
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
// [9] Middle Rectangle
tl = point[8]
tr = point[11]
bl = point[9]
br = point[10]
batch_vertex(tl, {0, 0}, c)
batch_vertex(tr, {1, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(tl, {0, 0}, c)
batch_vertex(br, {1, 1}, c)
batch_vertex(bl, {0, 1}, c)
}
// Draw a circle with a certain center and radius. Note the `segments` parameter: This circle is not
// perfect! It is drawn using a number of "cake segments".
draw_circle :: proc(center: Vec2, radius: f32, color: Color, segments := 16) {
if s.vertex_buffer_cpu_used + s.batch_shader.vertex_size * 3 * segments > len(s.vertex_buffer_cpu) {
draw_current_batch()
}
if s.batch_texture != s.shape_drawing_texture {
draw_current_batch()
}
s.batch_texture = s.shape_drawing_texture
prev := center + {radius, 0}