Is this a good design? - c++

Right now my gui is abstract and basically has a Bitmap class which holds a void* to the native bitmap type. The way it works is I have an abstract bitmap loader which returns a void pointer to the image data given a path string. the loader is a static pointer in the Bitmap data type and is set by the user for whatever backend used. The Graphics class is abstract and a pointer to it is asked for by the Gui class. When the backend for the Graphics class draws an image it does something like this:
void Allegro5GraphicsManager::drawImage( const Bitmap &bmp,
const Point &position,
const Point &regionStart,
const Dimension &regionSize,
const float &opacity /*= 1.0f*/ )
{
al_draw_tinted_bitmap_region((ALLEGRO_BITMAP*)bmp.getBitmap(),
al_map_rgba_f(opacity,opacity,opacity,opacity),
regionStart.getX(),regionStart.getY(),
regionSize.getWidth(),regionSize.getHeight(),
position.getX() + getOffset().getX(),position.getY() + getOffset().getY(), 0);
}
So as you can see it mearly type casts the void* to what it needs.
The problem is I hear void*s are not a good idea in C++.
The other solution I thought of is for something like Allegro5Bitmap which would inherit from Bitmap.
The problem I had with this method was that the user would then have to plaster Allegro5Bitmap all over their code. And this defeats the concept of my API which is for all code written to be portable to other backends like sdl, etc, by simply initializing the Gui class with sdl manager pointers.
What could I do?
Thanks

No, this is bad design. void* is what you definitely want to get rid of in C++.
It is not fully clear to me what problem you are trying to solve. Is it only about abstracting I/O of images or also drawing of them?
the typical solution to the I/O problem is to have ImageReader/ImageWriter abstract classes. Then their implementations are based on image type or I/O backend. These classes are basically factories for Image objects.
What you are handling in your code afterwards is still a generic Image (btw. you know that a "bitmap" actually is a black+white image?).
Note: Even if you need to have different types of Image objects (derivations), the factory is the typical pattern to resolve your issue while staying generic in your other code. You obtain an Image object from the factory, that in fact is an AllegroImage or whatever other type. You only call the base class methods on the Image so you don't care.

Related

Setting a function from one object to called by another object in arduino library

I'm a little new to writing in C so I hope I'm not to far off base here.
I'm working on a library to handle the control of multiple types of LED ICs. There are a ton of different types of RGB Pixel libraries each with their own unique naming, but all really perform the same basic actions. A "strip" or "strand" object is created, each pixel gets a color value set, and the strip then gets updated.
My library handles getting pixel color values from software in the back ground and providing the user with the most recent values from an array belonging to the object.
What I would like is to allow the user to initiate their LED strip object and pass a reference to that object to my library, and then allow them to pass their objects "setPixelColor()" function and "UpdateStrip()" function to the library as well. If this is achievable then I believe my library could then handle all of light control operations for any given PixelLibrary.
I believe what I'm looking for is the proper way to pass a functions pointer between objects? Not looking for someone to do this for me, but just looking for directed guidance. Been searching google for while this morning, but I don't know that I'm even using the proper terms. Any advice or guidance would be a big help. Thanks!
Sounds like what you need is a base class or virtual base/interface. You define a class with common data and methods which work across all your LEDs. This common or abstract class defines the common functions. Each of your LED strand types will then inherit the base class/interface and implement the specific functions to set an LED for example.
Using this approach the application code works using the Base class/interface methods treating all the strands the same way.
If you use this approach, I also recommend you create a static factory method which returns a base class/interface pointer after creating the specifically required object.
abstractController=CreateLEDStrandController("Strand Type");//Creates the right object, returns an abstracted base class pointer.
abstractController.SetLEDColor("RED"); //Actually calls the specific object SetLEDColor

How do I register all subclasses of a certain parent to a different class

I am designing an application, where multiple geometric primitive types (all inheriting the base Primitive class) are stored in an object of class Scene.
Instead of having a function in my main() that programmatically creates a scene by constructing the primitives and then calling Scene::add(...), I'd like to have some sort of configuration file that is read at runtime.
This would save me from having to recompile every time I change something about the scene, and seems like a general good idea (in case someone else that can't program might need to use my program sometime)
I've devised a little scheme that defines the scene through a .ini file like so:
[primitivefoo]
type = sphere
pos = 10 20 30
radius = 5.5
[primitivebar]
type = triangle
vertexA = 10 10 -10
vertexB = ...
...
You get the idea.
My plan is to have each subclass of Primitive register their own method interpretINI(...) in the class Scene. Scene would need some sort of map that maps string->void* (...), so that I know which type-string from the .ini file corresponds to which subclass of Primitive.
If this entire approach is bad design, and there is already a much more elegant way to achieve what I want to achieve, I would love to hear it. If not, I would be very grateful if someone could help me realize my design. I'm stuck on how to iterate over all Primitive subclasses to have them register themselves in Scene...
Your approach sounds good to me, with the exception that the names should map to a function returning Primitive* (instead of void*). This is a factory pattern (on two levels)
One limitation of this approach is that the factory functions registered will have to accept the same number/type of parameters. [Update: upon reading your comment to your question, this should not be a problem in your case].
I do not know of any automatic way of enumerating subclasses of a particular class, you will need to manually register the known classes (in main, or a special register function)
Update: you could get around the subclass enumeration by using static variables (in-class or otherwise) that will run a "register" function specific to the class-in-question:
class MyShape : public Shape
{
static int reg;
// appropriate constructor
};
int registerMyShape();
int MyShape::reg = registerMyShape(); // this will be called at program startup
The only problem is, there is no guarantee about the static initialization order in separate compilation units. Maybe if you can make the shapes module-like and "load" them after the registry class is fully initialized?

Design: GraphicManager, TexturesPool, Texture

I have system in which present class sigleton GraphicManager, class TexturePool and class Texture.
Texture have some subtles in creation. Then it constructing itself they use DirectX stuff from GraphicManager and some d3d constants. Now i use CreateInstance method and private cons in Texture class, but as for me its not goot what Texture now so much about real engine, may be better to build it from GraphicManager? Do i need use for it friend function or may be else approach?
I really couldn't understand your question, but I'll try to give you some tips. It's ok if you use Singleton in GraphicManager or in TexturePool, but you have to be careful, because singleton allows you to use the unique instance even when you shouldn't. Singleton can make the code easier to type, but a quite dangerous too. As I could understand you are now using Singleton in Texture class, but I think that in your system you can have more than one Texture, so it doesn't make sense. However, you can create a method in your TexturePool class to load a texture from a image file. Something like:
Texture* TexturePool::loadTexture(std::string fileName);
Then, anything that you need to use to create a texture, you should get from GraphicsManager's unique instance. I hope this could be useful for you.

Should I make wrappers for polymorphic classes that need to be allocatd on the heap?

Right now, the GUI API for games I''m developing has an abstract Image and Font class. Depending on whether they use a GL, SDL etc Font, they load fonts like this:
Font *segoe = Font::load("segoe.ttf");
There is also a corresponding destroy() static function as well.
I like this design, but I was wondering if it would be a good idea to wrap it so that no pointers needed. Something like this (with better naming conventions)
WrappedFont segoe = WrappedFont(Font::load("segoe.ttf"));
It would also have overloaded = and a copy ctor, and a destructor.
Is it generally more desired for a game gui for the user to manage their Images and Fonts, or is a wrapped pattern more desirable?
Thanks
Basically, that's a custom smart pointer type to handle the load/destroy logic. This is very idiomatic and the way to go in C++. Resource management should be automatic.
So your wrapper is fine, but perhaps you are reinventing the wheel here. You may consider rewriting the font system that the work done by destroy is moved to the Font destructor, in which case you could use a regular boost::shared_ptr (also available from std in C++0x respectively std::tr1 in older compilers with support for the Technical Report 1). With your current code you can use shared_ptr as well, but you need to supply a custom deleter, which I find a bit cumbersome.
Yes, that's the way to go. Minor point: why not just have
WrappedFont segoe = WrappedFont("segoe.ttf");
You don't need to expose every detail to the user. The simpler it is, the fewer errors. If they really need to know the font involved, add a Font getFont() method.
This is always a personal choice. If you decide to allocate in constructor/init methods and destroy in destructor then it's a good idea (for that you have shared_ptr<> also.
But be informed that, if it's polymorphic then the virtual calls outside the class scope will be something like,
WrappedFont segoe = WrappedFont(Font::load("segoe.ttf"));
seogoe.getFontPtr()->VirtualFunction(); // more text !
You could yes, but the idea is to simplify the user life.
I usually introduce 2 classes for this:
Font: a base non-virtual class, which acts as a wrapper and resource manager and delegate the calls to an implementation (internal)
FontInterface: a pure interface
Customization comes by deriving from FontInterface and then somehow hooking into Font. In the case where I have full control over the code, I usually ask that an enum member be added for each derived class, the constructor for Font switches on this enum to instantiate the right derived class.
This is, indeed, a mix of Strategy and Factory pattern:
class Font
{
public:
enum Type { Segoe };
explicit Font(Type type);
void call1() const { _impl->call1(); }
void call2() const { _impl->call2(); }
private:
std::unique_ptr<FontInterface> _impl;
};
What's really interesting here is that the interface is stable in the face of redesign (for the user). The fact that there is an internal implementation which depends from the font selected is completely hidden.
Indeed, it is easy enough to move toward a FlyWeight pattern, for in the case of fonts the Font itself is normally stateless, only specifying behavior. Just change the std::unique_ptr for a std::shared_ptr, and have a simple cache system to maintain in memory the currently loaded fonts (using weak_ptr) and hand them over as necessary.

c++ generic pixel array (supporting multiple channels) for image class

I am currently working on a simple image class in c++ which uses FreeImage internally to load and parse the image files. Anyways I am not really sure about how to implement my pixel array as generic, simple and safe as possible. For instance the class is supposed to handle different channel counts. Since for now I simply want to decide which pixel format to use based on the file type and pixel information freeImage gives me, the exact decisions have to be made at runtime, when actually loading the image. I think the only way to deal with this is to have a pointer to some abstract "Pixels" baseclass in the image class definition, and then allocate the correct format on the heap like this (basically a factory pattern):
//pseudo code
class Image{
template<class T, class TNumChannels>
struct Pixel
{
T v[TNumChannels];
};
class BasePixelArray{...};
class RGBPixelArray :
public std::vector<Pixel<uint8, 3> >,
public BasePixelArray
{
...
};
private:
BasePixelArray * m_pixelPtr;
public:
void loadImage(const std::string & _bla)
{
//parse and decide what pixelformat to use, i.e
m_pixelPtr = static_cast<BasePixelArray*>(new RGBPixelArray);
//fill array
....
}
};
i don't think this is ideal at all since I would like to avoid allocating from the heap , but since it has to be done at runtime I could not really think of anything else, so I was wondering if anybody of you guys might have a better idea!
Thanks
If you know all dimensions of image beforehand and if it's a large image (actually, it should be relatively small image), you can make it compile-time allocation on stack. If you don't know those details or you want to allocate large image, then allocation on heap is the only solution.
For more inspiration, you may want to take a look at the image and any_image models from Boost.GIL library.
You didn't mention your platform, but from the Windows perspective, here's my advice:
Stack, but keep in mind that the default user stack size is 1MB, which can be changed if you control the thread creation using _beginthreadex().
Heap, probably the most common choice
Use ::VirtualAlloc directly if you alloc/dealloc either very large buffers, or alloc/dealloc very frequently