The Melodist»Blog

Devlog #4 (Under The Hood) Uploaded (2/26/2017)

Hello, everyone!

It's been quite a busy few weeks, which is why I'm surprised at the fact that I somehow managed to squeak out a new devlog. The devlog series is changing a bit; now, there will be two videos per episode. One of these will be titled Under The Hood, where I explain more programming-related things and where the video focuses on the code and programming; the other will be titled Behind The Scenes, which is the usual game update video where the content deals more with the game itself.

This is the first Under The Hood video (starting on Episode #4). That being said, here it is; I hope you enjoy!

Thank you so much for your support.
Jeremiah Goerdt,
Cool stuff. Using unions in this way is something I want to do more of. Since I write pure C, I don't have the option for classes and this is a great way to get some much-needed behavior for games.

Keep the videos coming, They're great.
Jeroen van Rijn,
Yet another cool update :)
Thanks, Delix!
Ryan Fleury,

Thank you so much!

Yeah, I very recently learned about this use of unions, which is actually a far better way of achieving some of the things that inheritance allows you to do; it's an incredibly useful tool. Despite programming for ~6 years at this point, I just recently learned about it... OOP has dominated programming education, leaving people like me oblivious to certain non-OOP methods of getting things done (which turn out to be superior in my opinion).
Ryan Fleury,
@Jeroen van Rijn

Thanks so much for the support!
Ginger Bill,
Tagged/Discriminated unions are one of my favourite "complex" data structures. I use them for whenever I need a single level "hierarchy"/"category".

The best thing about them is that even thing is the same size. Which means I can preallocate the things I need and even memcpy in a different one if I need without worrying.

A subtyping style does have its benefits such as each thing is a different size which can be more memory compact. You can use both together to get even better results!

To make things a little more "sane" (in C), I use an x-macro which allows me to generate the tags which specific names, the enums for each tag, a list of strings with the names of each tag, and the actual union. It's not pretty much it's needed as there is no support for it in C nor C++ (unless you use very crazy templates).
Dumitru Frunza,
If the size of the struct is of concern, what are the available options? One solution that I can think of, is to keep pointers to the "sub-structs". Any others?

struct Shape {
  ShapeType type;
  union {
    Triangle* trig;
    Rectangle* rect;
    Square* square;

Mārtiņš Možeiko,
Pack them next to each other in memory - like Casey is doing for render commands. The disadvantage is loosing random access, only serial iteration is supported, but for many use cases this is enough.