Thursday, December 5, 2013

Remaking SOUND and THREAD into Classes

This post continues my series about rewriting the code from Game and Graphics Programming for iOS and Android with OpenGL ES 2.0 to better leverage C++ abilities.  In Chapter 9 the author introduces his module which wraps the OpenAL library.  This wrapper is the SOUND module.  Also, the author introduces his module for managing threads, called THREAD.

To get a copy of the code as described in this post pull a copy from GitHub using the tag chapter9.

Most of the changes to SOUND are straight forward.  The original version of the module defines two data types:  SOUND, and SOUNDBUFFER. The original code implements a sort of poor man's polymorphism.  The module does this by providing two different ways to allocate and initialize a SOUNDBUFFER:  the functions SOUNDBUFFER_load(), and SOUNDBUFFER_load_stream().  In my rewrite of the module I mimic this by making a new class called SOUNDBUFFERSTREAM which is subclassed from SOUNDBUFFER.  The old SOUNDBUFFER_load() function becomes the constructor for the SOUNDBUFFER class, and SOUNDBUFFER_load_stream() becomes the constructor for the SOUNDBUFFERSTREAM class.  All of the other methods for the SOUNDBUFFERSTREAM class are inherited directly from the SOUNDBUFFER class.

I did notice that there is a fair amount of duplicate code between the constructors for the SOUNDBUFFER, and SOUNDBUFFERSTREAM classes so I created a new, private SOUNDBUFFER:init() method so that all of the formerly duplicated code is in one place.

The SOUND module leverages the AUDIO module.  The AUDIO module creates a singleton, that is, it creates a class which can only be used to create a single instance of the AUDIO data type.  The AUDIO module shares this trait with the GFX module, which is, in part, why I haven't yet rewritten the GFX module.  It's been suggested to me that to make the code more general purpose that the AUDIO module should be rewritten to support more than one audio device.  For the time being I've left AUDIO alone but have been experimenting with various ways of implementing AUDIO as a singleton class using various C++ techniques.

Regarding the changes needed to make THREAD into a class, there really isn't anything which hasn't been discussed in previous posts.

The next post will cover real C++ polymorphism when I discuss the changes I made to the LAMP data type, and its subclasses in Chapter 10.

No comments:

Post a Comment