Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do mods work?

Tags:

c++

How exactly do people get mods to work, for example, in a game? By mods I mean additions to the final executable.

If I were to make a game (Using a compiled language), could I allow for myself or others to make additions to it without having to create some kind of scripting language.

My idea: (would this work?)

  • In the base program itself, create a stack or FIFO or even a linked list.
  • Then outside the program, a loader would load the base and any mods, then pass the address of the mods to the base program.
  • Finally, the base program does its thing, then switches execution to the mods(Perhaps with some kind of callback mechanism, like a [gasp!] goto). When they're done, code execution goes back to the base where it can do its own thing.
like image 835
Will Young Avatar asked Dec 13 '22 15:12

Will Young


1 Answers

Usually you will expose some of your application (game?) internal interfaces and objects to the mod writers. The mod writer will build a dll, that uses these objects and interfaces to do something useful. The application will then load mod dll dynamically and call the mod implementation where necessary.

Another way to think about it, is to imagine that your game is an operating system (Windows), and your mod is an application (Word). The OS provides some APIs to create, and manage windows, the application utilizes them where necessary.

So as a game dev your may create and distribute the following interface:

//mod.h
class Mod {
    //takes suggested damage as an arg and returns modified damage
    virtual int takeDamage(int damage);
};

And instruct the users to provide exported functions to instantiate and delete the mod objects.

Implement it:

//godmod.h
class GodMod : public Mod {
    int takeDamage(int damage) { return 0; } // god mode!!
}

__declspec(dllexport) Mod *create_mod() { return new GodMode(); }
__declspec(dllexport) void delete_mod(Mod *mod) { delete mod; }

Then you will have to load the dll (LoadLibrary API on Windows), export create_mod and delete_mod symbols with GetProcAddress API. Afterwards somewhere in the game you will instantiate the mod with create_mod, and use it where needed:

int damage = 100; //original damage
for (int i = 0; i < mods_count; i++) {
    damage = mods[i]->tageDamage(damage);
}
decrease_health(damage);

after all you will have to release the mod with delete_mod from the corresponding dll.

like image 125
ak. Avatar answered Jan 23 '23 14:01

ak.