Using private static variable across multiple classes - c++

I've a class for my one of programs which is drawing image sequences at different positions on the window. The class has multiple instances but it's the same image sequence which is being drawn at all the positions inside the window. I want to prevent multiple instances of class initializaing multiple image sequences to avoid eating memory, for which I have the image sequence variable as static variable
class Drawer{
private:
static ImageSequence imgSequence;
};
In the .cpp file, I am doing the following to initialize the static var.
#include "Drawer.h"
ImageSequence Drawer::imgSequence = ImageSequence();
However, I have two methods to specify the path to image sequences and preload al frames - and confused about where to put these methods so that each Drawer class instantiation does not preload the frames time and again. How'd this be done in C++?
--EDIT
The two methods as asked for: i) loadSequence, ii)preloadAllFrames();
loadSequence(string prefix, string firstFrame, string lastFrame){
for(int i=0;i<numFrames;++i){
//adds and pushes values of all the files in the sequence to a vector
}
}
preloadAllFrames(){
for(int i=0;i<numFrames;++i){
//create pointers to image textures and store then in a vector so that it doesn't take time to load them for drawing
}
}

Have an accompanying boolean value with the image and check if the image has been already loaded when you try to load it. You can also load it when your program is initializing only once instead of attempting to load it every frame.

Just have a static pointer instead of instance and initialize in a static method:
class Drawer{
private:
static std::unique_ptr<ImageSequence> imgSequence;
public:
static void initializeMethod1()
{
if( imgSequence ) return; // or throw exception
imgSequence.reset( new ImageSequence( ... ) );
...
}
static void initializeMethod2() {}
{
if( imgSequence ) return; // or throw exception
imgSequence.reset( new ImageSequence( ... ) );
...
}
static ImageSequence &getSequence()
{
if( !imgSequence ) throw std::runtime_error( "image sequence is not intialized" );
return *imgSequence;
}
};

Related

C++ design for init static members, any time required

I'm developing a little game engine for Android with Android NDK and opengl es 2.0, recently the project is getting big, and I need to refactor some code, and I couldn't find a proper design pattern for the next problem.
On android when the app reach the OnPause() state the opengl context is destroyed, but the state of the variables and objects in java and c++ are maintained. so each time the player pauses and resumes the app I have to reinitializate the opengl part, buffers, shaders, vertex, etc.
I have classes like "Square" that makes "square objects", and each one has its own attributes, and each "square object" can be drawn, so the squares can access to static (opengl) members of the class, that are used to be properly rendered. So this static members must be initialized before objects can be drawn, I do it when the opengl context is created or recreated.
moreover each class has its own opengl attributes, so each class is initialized individually with its own parameters, so I want a design in what each class can set some initial parameters, pass or catch those parameters to initialize the static members of the class (I forgot to say that these parameters are private). But as I said before, these parameters need to be reinitialized each time the app is resumed.
currently I initialize these members individually like
Square::init(/*hardcoded parameters*/);
Circle::init(/*hardcoded parameters*/);
Triangle::init(/*hardcoded parameters*/);
Polygon::init(/*hardcoded parameters*/);
Shape::init(/*hardcoded parameters*/);
.
.
.
.
// Many other inits.....
.
and I want to write something like
// here all the classes with opengl part are initialized
// all init methods of each class are called here, with their respective parameters
Opengl_Initializer::init(); // <--- magic way, no other init calls
So I want to set some (static/harcoded) variables to the class and then when the opengl context be created, the class be initialized in a "magic" way, and not having the need to code the call to an init method for each class.
I've tried to use inheritance, but the issue is that I need to initialize the class not the object, also tried to implement a static object and initialize this object in the cpp file, and store a pointer to the object in a vector when this is created in his contructor, in a vector that is in the object's own class, but this design has gave me many problems.
Does anyone know some design that can help me?
EDIT: the stucture of my classes
the init() function is really big because shader and frag parameters are paths file and I perform some task on them, pass the result of that perform to opengl and returns me a ID that is the program static variable, all clases with opengl part implement this same process, the parameter camera is just to attach it into a camera
class Square {
// static variable all classes have
static GLuint program;
// other glparameters not in common, initialized in the same static init() method
static GLint uniform1;
static GLint uniform2;
public;
// the static init function has the same header on all the classes
static init(const char* shader, const char* frag, const char *camera);
}
and maybe some structure I'd want is
class Square {
static GLuint program;
static const char *vertex = "hardcode";
static const char *frag = "hardcode";
static const char *cam = "harcode";
static init();
/// or somethig like
static Initializer init(
"harcode shader", "hardcode frag", "hardcode camera",
[&] (void) ->void {
//this is the init function
}
);
public:
}
This is one more solution how your task can be solved. The idea is to have some initialization list (std::vector) of functions that should be called in yout Opengl_Initializer::init() :
std::vector<std::function<void()>> initializer_list;
If we can put all your Square/Circle/Triangle... init functions into this list, your task become trivial - just iterate list and call all functions:
// inside Opengl_Initializer::init()
for (auto fn : initializer_list)
fn();
You can add functions manually, for example, from int main():
initializer_list.push_back(&Square::init);
...
But I suggest that you need some arhitecture design that will make you able adding functions into initializer list without changing main or any other global code.
To solve this task we can make small helper class that will register your init functions automatically:
struct OpenGLHelper_initializer
{
OpenGLHelper_initializer(std::function<void()> fn)
{
initializer_list.push_back(fn);
}
};
So you can declare instance of this class in your Square/Circle:
struct Square
{
static OpenGLHelper_initializer __initializer;
};
And in your Square.cpp file:
OpenGLHelper_initializer Square::__initializer(&Square::init);
So, when program loads, all this initializer will be constructed and all your "init" function will be registered into initializer_list.
This looks like more code, but it will make you able to add as many shapes as you need without changing Opengl_Initializer::init(); or main.cpp or any other global code
Your can now remove init functions, if you dont like them and use lambdas:
// in square.cpp
OpenGLHelper_initializer Square::__initializer([](){
std::cout << "Square is initialized now" << std::endl;
});
Here is complete source code (Updated with using static function) (but without cpp files - all in one):
#include <iostream>
#include <memory>
#include <vector>
using namespace std;
/////////////////////////////////////////
// opengl_helper.h
// this is some manager class that knows what should be initialized later
struct OpenGLHelper
{
typedef std::function<void()> function_type;
static std::vector<function_type>& get_initialization_list();
static void register_initializer(function_type fn);
static void run_init();
};
// helper class that will register some function at construction time
struct OpenGLHelper_initializer
{
OpenGLHelper_initializer(OpenGLHelper::function_type fn)
{
OpenGLHelper::register_initializer(fn);
}
};
/////////////////////////////////////////
//opengl_helper.cpp
// using this function we will make our initializer_list be constructued
// before adding anything into it
std::vector<OpenGLHelper::function_type>& OpenGLHelper::get_initialization_list()
{
static std::vector<function_type> initializer_list;
return initializer_list;
}
// function that puts initializer into a list.
void OpenGLHelper::register_initializer(OpenGLHelper::function_type fn)
{
get_initialization_list().push_back(fn);
}
void OpenGLHelper::run_init()
{
for (auto fn : get_initialization_list())
fn();
}
/////////////////////////////////////////
// figure.h
// here is sample class that will be registered for initialization
struct Square
{
static int to_be_initialized;
// static member that will register Square class to be initialized
static OpenGLHelper_initializer __initializer;
};
/////////////////////////////////////////
// Square.cpp
int Square::to_be_initialized = 0;
// this is the most interesting part - register square into initializer list
OpenGLHelper_initializer Square::__initializer([](){
Square::to_be_initialized = 15;
std::cout << "Called Square::init: " << to_be_initialized << std::endl;
});
int main()
{
std::cout << "Before initialization : " << Square::to_be_initialized << std::endl;
OpenGLHelper::run_init();
std::cout << "After initialization : " << Square::to_be_initialized << std::endl;
return 0;
}
Output:
Before initialization : 0
Called Square::init: 15
After initialization : 15
Live test
BTW, such way of initialization is used by QT's metatype system - it uses macros to simplify code
UPDATE:
As Ben suggested, we can eliminate small memory leak from bynamic link allocation if we will put initialization list into a static function. Here is new code
I suggest a versioning system, so that initialization can be automatically performed at time-of-use, but in a way that skips it very cheaply when the initialization has already been done. Something like
int global_gl_generation = 0; // increment each time you recreate the context
inline bool check_gl_generation(int& local_generation)
{
if (local_generation == global_gl_generation)
return false;
local_generation = global_gl_generation;
return true;
}
and then in each class,
class Square
{
// static variable all classes have
static int generation_inited;
static GLuint program;
static GLint uniform1;
static GLint uniform2;
static init(const char* shader, const char* frag, const char *camera);
public;
void draw() override
{
if (check_gl_generation(generation_inited)) init(...);
// use program, uniform1, uniform2
}
};

C delegate to C++

I have a small problem using a library that gets images from a CMOS camera.
The library permits to use a stream functionality and I have three access point to set (three delegates) for when I get an image, when an image is dropped and when there is an error.
typedef void(* StreamCallbackPtr)( IMAGE *image );
typedef void(* StreamErrorCallbackPtr)();
typedef void(* StreamFrameDroppedCallbackPtr)();
int Stream_Start( DEVICE device, IMAGEFORMAT format, StreamCallbackPtr stream_callback, StreamFrameDroppedCallbackPtr f_dropped_callback, StreamErrorCallbackPtr error_callback );
I enter a StreamCallbackPtr as soon as an image is ready on the camera, but keep in mind that I do not have any ways of changing the library code.
And here is the question: How do I plug my own delegate in C++ ?
Lets say I use this stream functionality inside a class, I know that I have at least two options; the wrapper, and global variables. The first one seems compromised since I cannot pass anything else than an IMAGE, and I want to avoid using global variables (it would be static members in this case).
Any ideas ?
You could use a static member function as the StreamCallbackPtr which then can access a private static reference or list of references to the C++ delegates which wish to receive the message.
That way you have hidden most of the details as private to the class.
The code below is pseudo-C++ (I haven't checked it properly) but it should give you the idea of what I am suggesting.
class Delegate
{
protected:
void Callback( IMAGE *image ) = 0;
void Error() = 0;
void FrameDropped() = 0;
public:
static void SetDelegate(Delegate* d) { delegateInstance = d; }
static void StaticCallback( IMAGE *image)
{
// Invoke the delegate instance
if (delegateInstance != nullptr) delegateInstance->Callback();
}
// Same for the others...
private:
static Delegate* delegateInstance = nullptr;
};
class MyClass : public Delegate
{
protected:
void Callback( IMAGE *image )
{
// Now the callback is in a delegate instance
}
};
int main(void)
{
MyClass mc;
Delegate::SetDelegate(&mc);
StreamCallbackPtr scp = &Delegate::StaticCallback;
// Register the other static callbacks...
return 0;
}

Circular dependency conundrums

In my C++ project, I have an Engine class, a Renderer class and an Object class.
The instance of Renderer renders instances of Object. However instances of Object add themselves or remove themselves from the list of things to render.
From a usability point of view, it should be possible to set whether an instance of Object is drawn or not from the Object, but without the circular dependency.
I have a possible solution to this problem, but I do not know if it is a good idea:
The update cycle in the game is done through an Update() function in the Engine class that calls the Update() functions for every object. When it comes to call the Update() function for each instance of Object, I could set it to check for two boolean variables in the Object class. One, for whether it should be drawn, and one for whether it is actually being drawn. This should thus allow for an instance of Object to be added or removed from the list of things to render as required.
Is it a good idea to do it this way? Is this way efficient or is there a better way without the circular dependency?
EDIT:
I have rewritten my question for greater clarity and moved the second part to a new question where it was probably more relevant and to avoid confusing things further here.
You would want Object to inherit from Rendered, and Renderer to only be aware of Rendered, not Object (See below):
#include <iostream>
#include <list>
struct Renderer;
struct Rendered
{
virtual void renderMe( Renderer& ) = 0;
protected:
//Renderer won't delete me...
virtual ~Rendered(){}
};
struct Object : Rendered
{
virtual void renderMe( Renderer& )
{
std::cout << "I'm rendered!" << std::endl;
}
};
struct Renderer
{
void add( Rendered& r )
{
renderList_.push_back( & r );
}
void remove( Rendered& r );//...use your imagination
void render()
{
for( std::list<Rendered*>::iterator i = renderList_.begin(); i != renderList_.end(); ++i )
{
(*i)->renderMe( *this );
}
}
private:
std::list<Rendered*> renderList_;
};
struct Engine
{
Renderer& renderer_;
Object myObject_;
Engine( Renderer& r )
: renderer_( r )
{
renderer_.add( myObject_ );
}
~Engine()
{
renderer_.remove( myObject_ );
}
};
int test()
{
Renderer r;
Enginer e( r );
r.render();
return 0;
}
Not sure I really understand the intention. However, i would like to revisit your original question:
Currently, in order for an instance of Object to be drawn, it needs to
add itself to the instance of Renderer's list of objects to draw. This
means it needs a pointer to the instance of Renderer, however Renderer
also needs to know about Object in order to draw it.
Why is this a problem? If you just need pointers, you can declare the class type upfront:
class Object;
class Renderer;
class Engine;
Although, even cleaner would be using an Interface class.
EDIT:
Do I understand correctly, the problem is that you want to pass Rendered instance to Object, so the object can paint itself using the renderer?
What about the Interface class then:
class Paintable
{
public:
virtual void paint(Renderer *) = 0;
};
class Object : public Paintable
{
...
}
All your paintable object will be extending from the interface. This way the Renderer class doesn't need to hold vector of Objects, but vector of pointers to Paintable. (e.g. Renderer is no longer dependent on Object)
ANSWER: to second comment
Not sure you have a choice. You need the rendering piece of code to have access to Object's internal data (color, position, etc ...) and to the Renderer handle. Your choices are have the code in Renderer accessing object's internal data. This is, I think, a bad idea, as the Renderer would need to have different code handling different objects, and also possibly accessing private members of the Object. The other way around is to have intelligent objects that can render themselves given the Renderer handle. So they can call: renderer.paintLine(...), etc. Using the Interface class is neat, as the Renderer doen't need to have any knowledge about the Objects it holds.

C++: Making method return the same object every time

I would like to have a function that loads a file (in this case an OpenGL texture), but only actually loads the file once, and every time it is called after that it just returns what it initially loaded.
What would be a good way to do this?
Thanks.
You need some place to store that state. That can be either inside an object or as a static variable. Let's say:
class TextureLoader {
public:
TextureLoader() {}
GLuint loadTexture(std::string const & filename){
std::map<std::string, GLuint>::iterator it = m_loadedTextures.find(filename);
if(it == m_loadedTextures.end()){
GLuint id = load(filename);
m_loadedTextures[filename] = id;
return id;
}
else{
return it->second;
}
}
~TextureLoader(){
// iterate and delete textures
}
private:
GLuint load(std::string const & filename){
// real loading
}
std::map<std::string, GLuint> m_loadedTextures;
};
One way to do this would be to have a static map inside the function that associates the parameters to the function (here, the filename) with a pointer to the unique value it returns. You can then have the function check whether the map contains the input and, if so, hand back the texture associated with it. Otherwise, you can then do the load, store the result in the map, and hand back the result. For example:
Texture* LoadTexture(const std::string& filename) {
static std::map<std::string, Texture*> previousResults;
/* Look up existing value. */
Texture* result = previousResults[filename];
/* If this doesn't exist, then go create it and pretend it was there all along. */
if (result == NULL)
result = previousResults[filename] = ActuallyLoadTexture(filename);
/* Hand back the cached result. */
return result;
}
If you do this, you should be careful about thread-safety, since multiple calls to the function could cause problems with the map. Syncrhonize as appropriate.
It sounds like what you are looking for is an implementation of the Singleton Design Pattern.
There are a variety of ways to implement this, and now that you know what it is called, you can decide what method is best. Your first stop could be a search of this site for other similar questions.
Typically, you would either associate with a map or unordered_map filepaths to Texture*s.
class render_state {
std::map<std::string, Texture> textures;
Texture* load_texture(std::string filepath) {
if (textures.find(filepath) != textures.end()) {
return &textures[filepath];
}
// load the texture here if it's not in cache
}
// Other rendering methods and state here.
};
But now, you have another problem, which is that sometimes you might use a relative filepath, or sometimes, an absolute filepath. Also, in some libraries, they can accept varying versions of newlines and backslashes or forward slashes. What if I loaded a Texture, then only used it for a specific time and didn't need it again? Whoops, memory leak.
The best thing to do is just return a Texture object (or (possibly smart) pointer to such) and let the user worry about managing it. If someone creates a resource, it's their job to manage it, not yours.
See boost::flyweight. It does pretty much what you want. Load objects avoiding duplicates.
Would this be what you are looking for:
Texture& loadTexture(cosnt std::string& texture)
{
// Store all loaded data here
// Each file maps to a loded texture object
static boost::ptr_map<std::string, Texture> data;
boost::ptr_map<std::string, Texture>::iterator find = data.find(texture);
if (find == data.end())
{
// If it is not in the structure then load it this one time
find = data.insert(texture, doLoad(texture));
}
// return a reference to the texture
return *(find->second);
}

Accessing an object from a different class - Design

I have three classes, TImageProcessingEngine, TImage and TProcessing
TImageProcessingEngine is the one which i am using to expose all my methods to the world.
TImage is the one i plan to use generic image read and image write functions.
TProcessing contains methods that will perform imaging operations.
class TImageProcessingEngine
{
public:
TImage* mpImageProcessingEngine;
};
class TImage
{
public:
int ReadImage();
int WriteImage();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
class TProcessing
{
public:
int ConvertToBinary();
int ConvertToGrayScale();
};
My question is how do i access the object mpImageMatrix in class TProcessing? So that my calling application can use the following
TImageProcessingEngine* vEngine = new TImageProcessingEngine;
//Converts an input gray scsale image to binary image
vEngine->ReadImage().ConvertToBinary();
//Write the converted image to disk
vEngine->WriteImage();
delete vEngine;
vEngine = NULL;
//During this whole processing internally,
//the image is read in to `mpImageMatrix`
//and will also be holding the binarised image data,
//till writing the image to disk.
Or Do you recommend any other approach to my class design?
I would certainly recommend a different implementation, but let's check the design first.
I don't really understand the added value of TImageProcessingEngine, it doesn't bring any functionality.
My advice would be quite simple in fact:
Image class, to hold the values
Processing class (interface), to apply operations
Encoder and Decoder classes (interfaces), to read and write to different formats
It does make sense for the Processing class to have access to the images internal only if you can get efficiency from it (which is likely), in this case you can simply makes Processing friend and having it unpack the values for its derived
class Image
{
public:
Image();
void Accept(Processing& p);
void Encode(Encoder& e) const; // Image is not modified by encoding
void Decode(Decoder& d); // This actually resets the image content
private:
friend class Processing;
size_t mHeight;
size_t mWidth;
std::vector<Pixel> mPixels; // 2D array of Pixels
};
class Processing
{
public:
void apply(Image& image)
{
this->applyImpl(image.mHeight, image.mWidth, image.mPixels);
}
private:
virtual void applyImpl(size_t h, size_t w, std::vector<Pixel>& pixels) = 0;
};
Encoder and Decoder follow the same principle.
Note how I never needed an explicit pointer, and the guaranteed correctness that results from it.
First off, based on your provided code there are no ReadImage() & WriteImage() functions in the TImageProcessingEngine class, so the later code where you use such functionality is flawed.
As for the solution, you can make a getter function for the tImageMatrix pointer like this:
tImageMatrix* GetImageMatrix() { return mpImageMatrix; }
Then just pass that pointer (or a pointer to the whole TImage instance) to the TProcessing function you want to call.
Why you want to have a separate TProcessing process, when it specifically has functions just accessing mpImageMatrix;
In OOP, you have to bind the data members and it's operations..
So, IMO, remove your TProcessing class and have both the functions within TImage..
Your TImage will be like,
class TImage
{
public:
int ReadImage();
int WriteImage();
int ConvertToBinary();
int ConvertToGrayScale();
private:
//a two dimensional array holding the pixel values
tImageMatrix* mpImageMatrix;
};
You could create an accessor TImage class:
byte * pixelAt(unsigned x, unsigned y);