Handmade Hero » Forums » Code » Day 017: game_controller_input bounds checking
Salads
5 posts
#5901 Day 017: game_controller_input bounds checking
1 year, 1 month ago Edited by on Feb. 18, 2016, 12:03 a.m.

I thought of an easier way to bounds check the game_controller_input union in handmade.h

The original assert for reference
1
Assert((&Input->Controllers[0].Terminator - &Input->Controllers[0].Buttons[0]) == (ArrayCount(Input->Controllers[0].Buttons) - 1));


Since game_controller_input is a union, couldn't we copy-pasta the anonymous struct and add an identifier to the end of it?

 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
struct game_controller_input
{
	bool32 IsConnected;
	bool32 IsAnalog;

	real32 StickAverageX;
	real32 StickAverageY;

	union
	{
		game_button_state Buttons[12];
		struct
		{
			game_button_state MoveUp;
			game_button_state MoveDown;
			game_button_state MoveLeft;
			game_button_state MoveRight;

			game_button_state ActionUp;
			game_button_state ActionDown;
			game_button_state ActionLeft;
			game_button_state ActionRight;

			game_button_state LeftShoulder;
			game_button_state RightShoulder;

			game_button_state Back;
			game_button_state Start;
		};

		struct
		{
			game_button_state MoveUp;
			game_button_state MoveDown;
			game_button_state MoveLeft;
			game_button_state MoveRight;

			game_button_state ActionUp;
			game_button_state ActionDown;
			game_button_state ActionLeft;
			game_button_state ActionRight;

			game_button_state LeftShoulder;
			game_button_state RightShoulder;

			game_button_state Back;
			game_button_state Start;
		} u;
	};
};


This way, the assert becomes much more straightforward.

Comparison:
1
Assert((&Input->Controllers[0].Terminator - &Input->Controllers[0].Buttons[0]) == (ArrayCount(Input->Controllers[0].Buttons) - 1));

1
Assert(sizeof(Input->Controllers[0].Buttons) == sizeof(Input->Controllers[0].u));


I remember seeing in the MSDN docs somewhere that they did this with one of the structs we used. I'm trying to find info about this technique online but I don't know what it's called... :(
mmozeiko
Mārtiņš Možeiko
1251 posts
1 project
#5903 Day 017: game_controller_input bounds checking
1 year, 1 month ago Edited by Mārtiņš Možeiko on Feb. 18, 2016, 12:47 a.m.

Why would you want that copy&paste?
Imho that is very ugly. Better way would be to remove first structure, rename u to Button, and use it like "Input->Button.MoveUp.IsDown".

This is called "anonymous structure". You are not giving structure type name, but directly using it for member type.
Salads
5 posts
#5914 Day 017: game_controller_input bounds checking
1 year, 1 month ago

I agree it IS very ugly...

Also thanks! :)