Created
April 14, 2011 11:33
-
-
Save louisdx/919304 to your computer and use it in GitHub Desktop.
Plugin system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Current plug-ing system, schematically: | |
std::vector<Block*> BlockCB; // Dirt, Stone, Stairs, Torch, ... | |
PacketHandler::player_does_something() | |
{ | |
int16_t block_type = figureOutAffectedBlockType(); | |
for ( each Block* blockcb in BlockCB) | |
{ | |
if (blockcb != NULL && blockcb->affectedBlock(block_type)) | |
{ | |
blockcb->onRelevantEvent(); | |
// ... | |
} | |
} | |
// repeated many times | |
} | |
/***********************/ | |
/// Observation: affectedBlock() ONLY returns "true" for at most 2 blocks: The actual affected block, and the default block. Yet each time the entire BlockCB vector has to be traversed. Here's how this could be accelerated: | |
clever_map_type<int8_t, Block*> BLOCK_ACTIONS; | |
PacketHandler::player_does_something() | |
{ | |
int16_t block_type = figureOutAffectedBlockType(); | |
if (BLOCK_ACTIONS[block_type]) | |
{ | |
BLOCK_ACTIONS[block_type]->onRelevantEvent(); | |
} | |
BLOCK_ACTIONS["default"]->onRelevantEvent(); | |
} | |
/// The assumption is that the default handler is called AFTER the specific one. One could split this up into PRE and POST default actions if desired. | |
/// Even better, wrap it up (requires modification of the inherited classes): | |
struct BlockHelper | |
{ | |
static Block * get(int16_t block_type) | |
{ | |
iterator it = BLOCK_ACTIONS.find(block_type); | |
if (it == BLOCK_ACTIONS.end()) return BLOCK_ACTIONS["default"]; | |
return it->second; | |
} | |
private: | |
static clever_map_type<int8_t, Block*> BLOCK_ACTIONS; | |
}; | |
/* We must modify the derived classes to call the default action: */ | |
class BlockStairs : public BlockBasic | |
{ | |
// ... | |
void onPlace(args...) | |
{ | |
// ... | |
BlockBasic::onPlace(args...); | |
} | |
// ... | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment