PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Dynamic calculation of resource IDs

Hello all...

I frequently run into the situation where I have a series of resources, cells of animation for instance, that I need to load into an array. The resources might be named:

GFX_PLAYER_CELL_1
GFX_PLAYER_CELL_2

...and so on. I usually wind up writing code like this (this is for GapiDraw, but ignore that fact, it's still a generic question)...

pPlayer[0]->CreateSurface(NULL, hInst, GFX_PLAYER_CELL_1, TEXT("GRAPHICS"));
pPlayer[1]->CreateSurface(NULL, hInst, GFX_PLAYER_CELL_2, TEXT("GRAPHICS"));

...and so on for all the cells of animation. Here's my question... is there any way to dynamically get the resourceID (GFX_PLAYER_CELL_x) instead of hardcoding it?

I know I could find the resourceID of the first cell and just add one for each subsequent cell, but that will only work if the resources are numbered sequentially, which they might usually be, but I can't assume VC++ will do that, and I don't want to be renumbering them myself each time I add or change something.

Any ideas? Sure, they could be external files, then I could construct the filename dynamically no problem, and I may in fact do that later on, but for development it's usually easier if they are resources, then there's just one file to toss from desktop to PPC to test.

Thanks all!
NOTE: I love discussing game design (especially if it's something within the realm of my understanding), and I ended up rambling on a little bit. Sorry. :)

I don't think there's a dynamic way of doing it. Maybe if you could somehow get access to all of the resources available, then go through them one by one (must like you would if they were files stored in a folder). However, you'd still have to know which cells go with which object. How else would you determine which cell goes with which object if you don't have a hardcoded ID? I personally prefer the hardcoded ID because I have a GraphicManager which keeps track of which graphics are being referenced, which ones need to be created, and which ones need to be destroyed. All graphics I need are retrieved via GraphicManager::Reference(Resource ID);

In any case.. the only "dynamic" solution I can think of would be to try and store the resource.h file as a resource itself, then parse it for #define GFX_* values.

It sounds like you have all of your animation frames (or cells as you call them) as seperate graphics. If this is the case, perhaps you could store the entire animation as a single graphic, then dynamically create the cells when it's loaded. This would at the very least dramatically cut down on your code that needs to be hardcoded. I have a Graphic and Animation class that does just that. Now instead of having to load 32 individual cells for a single animation, you only have to create a single graphic, then have an animation class handle all of the animation stuff for you.

Personally, I have all of the animations for an object stored in a single graphic image (walking, running, jumping, etc.). I then have a Graphic class which breaks it down into an array of cells. After that, I have individual Animation objects which encapsulate Graphic objects and control animations (there are several Animation objects per Graphic object). All of my Graphics are kept track of in a GraphicManager, and Animations are created via AnimationFactory.
Yep, that's one decent approach, the single "sheet" of images for all the cells.

I havne't done that in the past, at least not early on in development, just because it makes it a little harder to make changes and tweak the animation sequences, and that tends to happen a lot early on. That being said, I think I might go that route anyway, it's the best solution I can see.

Don't worry about rambling on by the way... I'm not exactly known for my brevity around here ;)
I'm not sure I follow the question's intent or purpose perfectly, but I'll take a convoluted stab at it.

I'd run a script on resource.h (C-style. we'll just add another preprocessor):
1.) Run through a script through resource.h tp
parse it all out; do some regular expression magic to find the interrelated/chained RIDs

2.) take the chained RIDs; translate each 'chain' into a linked list.

3.) have the script generate macros to load these chains.

#define LOAD_GFX_PLAYER(pPlayer) ....

4.) or, if you need to do this at runtime for some reason: throw those chains into a hashtable and generate c-code to duplicate the datastructure in some arbitrary .cpp file.

[hashtable] -> [chain] -> [RID]

Code:

void load(int id) {
for(int i = 0; i < ResHash.GetChainSize(id); ++i)
pPlayer[i]->CreateSurface(NULL, hInst, ResHash.GetNextRID(id), ResHash.GetType(id));
}

...

load(GFX_PLAYER);
Interesting thought! I think it would have to be at runtime, so I'd have to be able to enumerate a list of resource IDs.

Eh, too much work :)

I decided to pretty much do what dan.p suggested anyway... I just threw together a function to populate an array by loading the larger animation sequence surface, then blit out each cell into the individual surfaces in the array.

Alternatively, I could just blit rects from the larger surface, and I actually think that's ultimately the right answer, but there were a few complexities with that I don't want to tackle right now (time to go home!). Probably tomorrow.

Thanks all!
I reckon it's really painful storing everything in resource files - even for development like you are saying. Instead I use a single data file that has an index with sensible names and offsets, and then the data tacked on the end for each file. I built a little Delphi util that you can just specify all of the files that make up the "package" (they can be anywhere on your pc/network), and when you click "Rebuild" it fetches them all and compiles them into a single file. This way you have two files instead of one, but it's no problem sending down a 2nd file every now and then.

As for animations I keep each frame a separate file and just named them like "Tank1", "Tank2", "Tank3" ... etc. So my LoadAnim function is told how many frames and what the anim name is, e.g. LoadAnim("Tank", 3). I much prefer keeping the frames separate as it's easier to work with in photoshop with my poor graphics skills.
I prefer them as resources because then everything is internal to VC++ when developing. I could do any number of different things, and everyone will have their own approach that they like (which is at it should be). Whatever is most efficient for each of us.

I ultimately wrote a populateAnimArray() function that takes in an array, a resourceID, resourceGroup, width and height of each cell. The function populates the array from a larger surface that contains all the cells. No need to even tell it how many cells, it figures it out (as at this point I don't know how long most of the sequences will wind up being). I allowed for a single vertical line between each cell, so it's easy to see each individualy cell in Paint Shop Pro (not that I care, it's only for development, my artist can deal with it however he wants for the real thing!)

This works great and even saves space since the combined surface is smaller (storage-wise) than having all the individual images. Also of course cut down all my numerous lines of code to a single line.

Incidentally, I thought about just loading the large surface and blitting rects off it, but I decided not to... Have to do some calculations to determine the rect coordinates, and I didn't want to be doing that multiple times per frame. I figure it's better to incur the slight up-front array population costs than the per-frame costs.
Pardon me, but I'd like to give the grumpy old man reply...
Build yourself a resource manager (like j. edwards suggests) and store all of your data files in there. The resource manager should support file i/o for all objects just as if they are individual files as well as compression/conversion. Do this now instead of what is easy for development. Taking the easy way out now will only lead to big problems in the future.. suffer a little now and save yourself a *whole* lot a suffering later.
Typically true, no argument. But, my past projects have all been done a certain way (individual items as resources), and I find that works great for me. Just condensing all the animation cells to one image is one step up that was well worth the ten minutes it took.

Taking the time to write a full-blown file manager isn't something I'm too interested in. I frankly don't see enough benefit to make it worth it. You mileage may vary, as always ;)

Incidentally, I thought about just loading the large surface and blitting rects off it, but I decided not to... Have to do some calculations to determine the rect coordinates, and I didn't want to be doing that multiple times per frame. I figure it's better to incur the slight up-front array population costs than the per-frame costs.


Maybe my ignorance is getting the best of me, but isn't this what you're already doing?

Either way, you don't have to do calculations per frame. Dynamically create an array of RECTs that pre-cache each cell location when the graphic is loaded. You can then access each cell individually with a single call to the array. You can then do things like this:

Graphic::DrawCell(CGapiSurface* pBuffer, DWORD cell, POINT location);

That's basically how my graphic class works. Here's the Create function for my Graphic class (Note: I use the word Frames instead of Cells):

Code:

void Graphic::Create()
{
// Surface must be created first.
if (m_surface.CreateSurface(GRAPHIC_FLAGS, m_hInstance, m_resourceID, GRAPHIC_TYPE) != GD_OK) {
// Failed.
return;
}

// Use surface width/height if no frame width/height is specified.

if (m_frameWidth == 0) {
m_frameWidth = m_surface.GetWidth();
}

if (m_frameHeight == 0) {
m_frameHeight = m_surface.GetHeight();
}

// Calculate number of frames.
DWORD rows = m_surface.GetHeight() / m_frameHeight;
DWORD cols = m_surface.GetWidth() / m_frameWidth;
m_frameCount = rows * cols;

// Create each individual frame.
m_pFrames = new CRect[m_frameCount];
CRect* pFrame = m_pFrames;

for (DWORD r = 0; r < rows; ++r) {
for (DWORD c = 0; c < cols; ++c) {
// Set frame values.
pFrame->left = c * m_frameWidth;
pFrame->top = r * m_frameHeight;
pFrame->right = pFrame->left + m_frameWidth;
pFrame->bottom = pFrame->top + m_frameHeight;

pFrame++; // Move to next frame.
}
}
}


Although I must confess, I don't know much about efficiency and all that jazz for the PPC, as this'll be my first game for one.
By Golly, your right! I'm embarassed to say I didn't think of just caching the rects. Long day, dead brain, I missed the obvious. Yes, that makes all the difference in the world.

It IS different than what I have coded now though... The way it is now, I load the large surface, then for each frame I create a new surface and blit to it from the large surface. But this is done only at startup, so each frame I'm just blitting a surface from my array.

Your approach is better though in that it eliminates the startup cost as well (at least the majority of it) since there's no blit for each frame and no extra surface creations, etc. Calculating the rects is trivial in comparison. Just a simple array of rects is what I'll do though, it's a simpler change than a whole new graphics class as you've done (it's ironic... when I do PPC development, I'm decidedly NOT object-oriented, in contrast to my "day job" that is nothing BUT object-oriented!)
You should make your compound image a tall, single-frame width image, which makes each frame a contiguous piece of memory. If the images are side by side in columns then there is a cache miss each scanline.

Dan East
Thanks Dan, I wouldn't have realized that. When I change the code tomorrow to do the "blit with rects" I'll do that too.
Since someone above mentioned making your own custom resource manager, has anyone considered CGapiVFS for storing resources (since he's using GapiDraw)? Or is that not a valid solution? It would certainly save development time if he didn't have to roll out his own.
I looked at it for a little while, but I decided against it, for much the same reason I originally had all the animation cells independant: easier to tweak things, especially during development. With something like VFS, I'd need to "rebuild" it when I made a change, and that's just extra work in my eyes. Especially since I have no plans to develop for anything but Win32 and PocketPC. I'm not saying it's a bad suggestion by any means, just pointing ut that I had considered it and ultimately rejected it.

In the interest of not having anyone expending more cycles on this debate than they have to, I want to say that I am actually rather happy with how things are being done now. I'm not by any stretch claiming it's the best way or anything, but it is working for me, and in fact better than before as a result of this discussion. I just didn't want anyone thinking I still had a problem here to be addressed, I no longer do :)

(Of course, feel free to continue to debate in a general kind of way all you like! Discussion is rarely a bad thing!)
Actually I'm about the same stage in my development as you (or so it seems), so I was just curious. Right now I do what you do: throw everything in as a resource and flop in a few lines of code to load it up. So I was curious as to anyones opinions on VFS more than anything. :)
Well, let me know what you find out if you do use it, if you wouldn't mind :) I wouldn't rule it out for the final release.

If you are doing what I did, which basically means three lines of code per image, I highly suggest going the "one large image with all the animation cells on it" route. That has made my life a lot easier, to the point that I'm hitting myself for not doing it sooner :)

Also, if you want, I could provide you the function I wrote to populate an array with the cells. It's nice in that you don't need to supply it the number of frames, so you can change your animation sequences without changing any code. Very handy early on in development.
Isn't that exactly what I suggested above? :) The code from my Graphic class that I pasted above does exactly what you describe. Although I do have my Animation class seperate. It sounds like your approach (although handled basically the same) is quite different. Your graphic and animation class appear to be all in one. Although I am curious, how are you changing animation sequences without altering code? Animation sequence to me means, from running to walking, or dying, etc. Do you mean something else?

Creating a graphic is actually only one line of code for me: gGraphicManager->Register(new Graphic(...)); Although I do split it up into two for readability.

I'll have a few different types of graphics for my game. One will contain all tiles for individual maps environments. Like if I have a level with snow type environment, a map graphic will contain all tiles for it, including buildings, etc.

The other type are things like special effects and characters (including monsters). A single character/monster will have it's own graphic, which will contain all animations (walking, running, dying, etc.). The special effect graphics will be in categories. I'll have one for spells, for example, and another for projectiles.

Or did you mean something different? If so, could you be more specific? I honestly can't imagine having all the graphics for the game in a single graphic file, which is the only other thing that you might be talking about.