const ChatLine& ChatBuffer::getLine(u32 index) const
{
- assert(index < getLineCount());
+ assert(index < getLineCount()); // pre-condition
return m_unformatted[index];
}
// keep m_formatted in sync
if (del_formatted < m_formatted.size())
{
- assert(m_formatted[del_formatted].first);
+
+ sanity_check(m_formatted[del_formatted].first);
++del_formatted;
while (del_formatted < m_formatted.size() &&
!m_formatted[del_formatted].first)
{
DSTACK(__FUNCTION_NAME);
- assert(data);
+ assert(data); // pre-condition
JMutexAutoLock lock(m_mutex);
if(counter <= 0.0) {
counter = 2.0;
- Player *myplayer = m_env.getLocalPlayer();
- assert(myplayer != NULL);
+ Player *myplayer = m_env.getLocalPlayer();
+ FATAL_ERROR_IF(myplayer == NULL, "Local player not found in environment.");
+
// Send TOSERVER_INIT
// [0] u16 TOSERVER_INIT
// [2] u8 SER_FMT_VER_HIGHEST_READ
// Create an irrlicht memory file
io::IReadFile *rfile = irrfs->createMemoryReadFile(
*data_rw, data_rw.getSize(), "_tempreadfile");
- assert(rfile);
+
+ FATAL_ERROR_IF(!rfile, "Could not create irrlicht memory file.");
+
// Read image
video::IImage *img = vdrv->createImageFromFile(rfile);
if(!img){
std::ostringstream os(std::ios_base::binary);
writeU16(os, TOSERVER_REQUEST_MEDIA);
size_t file_requests_size = file_requests.size();
- assert(file_requests_size <= 0xFFFF);
+
+ FATAL_ERROR_IF(file_requests_size > 0xFFFF, "Unsupported number of file requests");
// Packet dynamicly resized
NetworkPacket* pkt = new NetworkPacket(TOSERVER_REQUEST_MEDIA, 2 + 0);
const std::map<std::string, std::string> &fields)
{
size_t fields_size = fields.size();
- assert(fields_size <= 0xFFFF);
+
+ FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of nodemeta fields");
NetworkPacket* pkt = new NetworkPacket(TOSERVER_NODEMETA_FIELDS, 0);
const std::map<std::string, std::string> &fields)
{
size_t fields_size = fields.size();
- assert(fields_size <= 0xFFFF);
+ FATAL_ERROR_IF(fields_size > 0xFFFF, "Unsupported number of inventory fields");
NetworkPacket* pkt = new NetworkPacket(TOSERVER_INVENTORY_FIELDS, 0);
*pkt << formname << (u16) (fields_size & 0xFFFF);
// Set peer id if not set already
if(myplayer->peer_id == PEER_ID_INEXISTENT)
myplayer->peer_id = our_peer_id;
- // Check that an existing peer_id is the same as the connection's
+
assert(myplayer->peer_id == our_peer_id);
v3f pf = myplayer->getPosition();
// Set peer id if not set already
if(myplayer->peer_id == PEER_ID_INEXISTENT)
myplayer->peer_id = our_peer_id;
-
- // Check that an existing peer_id is the same as the connection's
assert(myplayer->peer_id == our_peer_id);
NetworkPacket* pkt = new NetworkPacket(TOSERVER_PLAYERITEM, 2);
}
break;
default:
- assert(0);
+ FATAL_ERROR("Invalid inventory location type.");
}
return NULL;
}
void Client::afterContentReceived(IrrlichtDevice *device, gui::IGUIFont* font)
{
infostream<<"Client::afterContentReceived() started"<<std::endl;
- assert(m_itemdef_received);
- assert(m_nodedef_received);
- assert(mediaReceived());
+ assert(m_itemdef_received); // pre-condition
+ assert(m_nodedef_received); // pre-condition
+ assert(mediaReceived()); // pre-condition
const wchar_t* text = wgettext("Loading textures...");
}
u16 Client::allocateUnknownNodeId(const std::string &name)
{
- errorstream<<"Client::allocateUnknownNodeId(): "
- <<"Client cannot allocate node IDs"<<std::endl;
- assert(0);
+ errorstream << "Client::allocateUnknownNodeId(): "
+ << "Client cannot allocate node IDs" << std::endl;
+ FATAL_ERROR("Client allocated unknown node");
+
return CONTENT_IGNORE;
}
ISoundManager* Client::getSoundManager()
io::IFileSystem *irrfs = m_device->getFileSystem();
io::IReadFile *rfile = irrfs->createMemoryReadFile(
*data_rw, data_rw.getSize(), filename.c_str());
- assert(rfile);
+ FATAL_ERROR_IF(!rfile, "Could not create/open RAM file");
scene::IAnimatedMesh *mesh = smgr->getMesh(rfile);
rfile->drop();
skin->setColor(gui::EGDC_HIGH_LIGHT_TEXT, video::SColor(255, 255, 255, 255));
g_fontengine = new FontEngine(g_settings, guienv);
- assert(g_fontengine != NULL);
+ FATAL_ERROR_IF(g_fontengine == NULL, "Font engine creation failed.");
#if (IRRLICHT_VERSION_MAJOR >= 1 && IRRLICHT_VERSION_MINOR >= 8) || IRRLICHT_VERSION_MAJOR >= 2
// Irrlicht 1.8 input colours
void insert(const std::string &name, video::IImage *img,
bool prefer_local, video::IVideoDriver *driver)
{
- assert(img);
+ assert(img); // Pre-condition
// Remove old image
std::map<std::string, video::IImage*>::iterator n;
n = m_images.find(name);
TextureSource::TextureSource(IrrlichtDevice *device):
m_device(device)
{
- assert(m_device);
+ assert(m_device); // Pre-condition
m_main_thread = get_current_thread_id();
}
video::IVideoDriver *driver = m_device->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
video::IImage *img = generateImage(name);
{
//infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
- assert(get_current_thread_id() == m_main_thread);
+ sanity_check(get_current_thread_id() == m_main_thread);
m_sourcecache.insert(name, img, true, m_device->getVideoDriver());
m_source_image_existence.set(name, true);
JMutexAutoLock lock(m_textureinfo_cache_mutex);
video::IVideoDriver* driver = m_device->getVideoDriver();
- assert(driver != 0);
+ sanity_check(driver);
// Recreate textures
for (u32 i=0; i<m_textureinfo_cache.size(); i++){
video::IImage *img = generateImage(ti->name);
#ifdef __ANDROID__
img = Align2Npot2(img, driver);
- assert(img->getDimension().Height == npot2(img->getDimension().Height));
- assert(img->getDimension().Width == npot2(img->getDimension().Width));
+ sanity_check(img->getDimension().Height == npot2(img->getDimension().Height));
+ sanity_check(img->getDimension().Width == npot2(img->getDimension().Width));
#endif
// Create texture from resulting image
video::ITexture *t = NULL;
const TextureFromMeshParams ¶ms)
{
video::IVideoDriver *driver = m_device->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
#ifdef __ANDROID__
const GLubyte* renderstr = glGetString(GL_RENDERER);
) {
// Get a scene manager
scene::ISceneManager *smgr_main = m_device->getSceneManager();
- assert(smgr_main);
+ sanity_check(smgr_main);
scene::ISceneManager *smgr = smgr_main->createNewSceneManager();
- assert(smgr);
+ sanity_check(smgr);
const float scaling = 0.2;
video::IVideoDriver* driver = m_device->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
/*
Parse out the last part of the name of the image and act
video::IImage *& baseimg)
{
video::IVideoDriver* driver = m_device->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
// Stuff starting with [ are special commands
if (part_of_name.size() == 0 || part_of_name[0] != '[')
//core::dimension2d<u32> dim(2,2);
core::dimension2d<u32> dim(1,1);
image = driver->createImage(video::ECF_A8R8G8B8, dim);
- assert(image);
+ sanity_check(image != NULL);
/*image->setPixel(0,0, video::SColor(255,255,0,0));
image->setPixel(1,0, video::SColor(255,0,255,0));
image->setPixel(0,1, video::SColor(255,0,0,255));
transform, baseimg->getDimension());
video::IImage *image = driver->createImage(
baseimg->getColorFormat(), dim);
- assert(image);
+ sanity_check(image != NULL);
imageTransform(transform, baseimg, image);
baseimg->drop();
baseimg = image;
(imagename_left + "__temp__").c_str(), img_left);
video::ITexture *texture_right = driver->addTexture(
(imagename_right + "__temp__").c_str(), img_right);
- assert(texture_top && texture_left && texture_right);
+ FATAL_ERROR_IF(!(texture_top && texture_left && texture_right), "");
// Drop images
img_top->drop();
// Create image of render target
video::IImage *image = driver->createImage(rtt, v2s32(0, 0), params.dim);
- assert(image);
+ FATAL_ERROR_IF(!image, "Could not create image of render target");
// Cleanup texture
driver->removeTexture(rtt);
if (src == NULL || dst == NULL)
return;
- core::dimension2d<u32> srcdim = src->getDimension();
core::dimension2d<u32> dstdim = dst->getDimension();
- assert(dstdim == imageTransformDimension(transform, srcdim));
+ // Pre-conditions
+ assert(dstdim == imageTransformDimension(transform, src->getDimension()));
assert(transform <= 7);
/*
/* event to update client state */
void event(u16 peer_id, ClientStateEvent event);
- /* set environment */
- void setEnv(ServerEnvironment* env)
- { assert(m_env == 0); m_env = env; }
+ /* Set environment. Do not call this function if environment is already set */
+ void setEnv(ServerEnvironment *env)
+ {
+ assert(m_env == NULL); // pre-condition
+ m_env = env;
+ }
static std::string state2Name(ClientState state);
return sector;
}
-#if 0
-void ClientMap::deSerializeSector(v2s16 p2d, std::istream &is)
-{
- DSTACK(__FUNCTION_NAME);
- ClientMapSector *sector = NULL;
-
- //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
-
- core::map<v2s16, MapSector*>::Node *n = m_sectors.find(p2d);
-
- if(n != NULL)
- {
- sector = (ClientMapSector*)n->getValue();
- assert(sector->getId() == MAPSECTOR_CLIENT);
- }
- else
- {
- sector = new ClientMapSector(this, p2d);
- {
- //JMutexAutoLock lock(m_sector_mutex); // Bulk comment-out
- m_sectors.insert(p2d, sector);
- }
- }
-
- sector->deSerialize(is);
-}
-#endif
-
void ClientMap::OnRegisterSceneNode()
{
if(IsVisible)
void ClientMediaDownloader::addFile(std::string name, std::string sha1)
{
- assert(!m_initial_step_done);
+ assert(!m_initial_step_done); // pre-condition
// if name was already announced, ignore the new announcement
if (m_files.count(name) != 0) {
void ClientMediaDownloader::addRemoteServer(std::string baseurl)
{
- assert(!m_initial_step_done);
+ assert(!m_initial_step_done); // pre-condition
#ifdef USE_CURL
m_remote_file_transfers.erase(it);
}
- assert(m_files.count(name) != 0);
+ sanity_check(m_files.count(name) != 0);
FileStatus *filestatus = m_files[name];
- assert(!filestatus->received);
- assert(filestatus->current_remote >= 0);
+ sanity_check(!filestatus->received);
+ sanity_check(filestatus->current_remote >= 0);
RemoteServerStatus *remote = m_remotes[filestatus->current_remote];
s32 ClientMediaDownloader::selectRemoteServer(FileStatus *filestatus)
{
+ // Pre-conditions
assert(filestatus != NULL);
assert(!filestatus->received);
assert(filestatus->current_remote < 0);
void ClientMediaDownloader::startConventionalTransfers(Client *client)
{
- assert(m_httpfetch_active == 0);
+ assert(m_httpfetch_active == 0); // pre-condition
if (m_uncached_received_count != m_uncached_count) {
// Some media files have not been received yet, use the
it = m_files.begin();
it != m_files.end(); ++it) {
if (!it->second->received) {
- assert(it->second->sha1.size() == 20);
+ FATAL_ERROR_IF(it->second->sha1.size() != 20, "Invalid SHA1 size");
os << it->second->sha1;
}
}
{
//TimeTaker tt("wouldCollideWithCeiling");
- assert(y_increase >= 0);
+ assert(y_increase >= 0); // pre-condition
for(std::vector<aabb3f>::const_iterator
i = staticboxes.begin();
}
} //tt3
- assert(cboxes.size() == is_unloaded.size());
- assert(cboxes.size() == is_step_up.size());
- assert(cboxes.size() == bouncy_values.size());
- assert(cboxes.size() == node_positions.size());
- assert(cboxes.size() == is_object.size());
+ assert(cboxes.size() == is_unloaded.size()); // post-condition
+ assert(cboxes.size() == is_step_up.size()); // post-condition
+ assert(cboxes.size() == bouncy_values.size()); // post-condition
+ assert(cboxes.size() == node_positions.size()); // post-condition
+ assert(cboxes.size() == is_object.size()); // post-condition
/*
Collision detection
//f32 d = 0.15*BS;
// This should always apply, otherwise there are glitches
- assert(d > pos_max_d);
+ assert(d > pos_max_d); // invariant
int loopcount = 0;
}
}
+/* \pre punchitem != NULL
+ */
bool GenericCAO::directReportPunch(v3f dir, const ItemStack *punchitem,
float time_from_last_punch)
{
- assert(punchitem);
+ assert(punchitem); // pre-condition
const ToolCapabilities *toolcap =
&punchitem->getToolCapabilities(m_gamedef->idef());
PunchDamageResult result = getPunchDamage(
void makeCuboid(MeshCollector *collector, const aabb3f &box,
TileSpec *tiles, int tilecount, video::SColor &c, const f32* txc)
{
- assert(tilecount >= 1 && tilecount <= 6);
+ assert(tilecount >= 1 && tilecount <= 6); // pre-condition
v3f min = box.MinEdge;
v3f max = box.MaxEdge;
switch(f.drawtype){
default:
- infostream<<"Got "<<f.drawtype<<std::endl;
- assert(0);
+ infostream << "Got " << f.drawtype << std::endl;
+ FATAL_ERROR("Unknown drawtype");
break;
case NDT_AIRLIKE:
break;
break;}
case NDT_GLASSLIKE_FRAMED_OPTIONAL:
// This is always pre-converted to something else
- assert(0);
+ FATAL_ERROR("NDT_GLASSLIKE_FRAMED_OPTIONAL not pre-converted as expected");
break;
case NDT_GLASSLIKE_FRAMED:
{
break;}
case NDT_ALLFACES_OPTIONAL:
// This is always pre-converted to something else
- assert(0);
+ FATAL_ERROR("NDT_ALLFACES_OPTIONAL not pre-converted");
break;
case NDT_TORCHLIKE:
{
m_physics_override_sneak_glitch(true),
m_physics_override_sent(false)
{
- assert(m_player);
- assert(m_peer_id != 0);
+ assert(m_player); // pre-condition
+ assert(m_peer_id != 0); // pre-condition
setBasePosition(m_player->getPosition());
m_inventory = &m_player->inventory;
m_armor_groups["fleshy"] = 100;
std::string PlayerSAO::getStaticData()
{
- assert(0);
+ FATAL_ERROR("Deprecated function (?)");
return "";
}
void Database_SQLite3::createDatabase()
{
- assert(m_database);
+ assert(m_database); // Pre-condition
SQLOK(sqlite3_exec(m_database,
"CREATE TABLE IF NOT EXISTS `blocks` (\n"
" `pos` INT PRIMARY KEY,\n"
" `data` BLOB\n"
");\n",
NULL, NULL, NULL));
-
}
void Database_SQLite3::listAllLoadableBlocks(std::vector<v3s16> &dst)
Assert
*/
-void assert_fail(const char *assertion, const char *file,
+void sanity_check_fn(const char *assertion, const char *file,
unsigned int line, const char *function)
{
DEBUGPRINT("\nIn thread %lx:\n"
- "%s:%u: %s: Assertion '%s' failed.\n",
+ "%s:%u: %s: An engine assumption '%s' failed.\n",
(unsigned long)get_current_thread_id(),
file, line, function, assertion);
abort();
}
+void fatal_error_fn(const char *msg, const char *file,
+ unsigned int line, const char *function)
+{
+ DEBUGPRINT("\nIn thread %lx:\n"
+ "%s:%u: %s: A fatal error occurred: %s\n",
+ (unsigned long)get_current_thread_id(),
+ file, line, function, msg);
+
+ debug_stacks_print();
+
+ if(g_debugstreams[1])
+ fclose(g_debugstreams[1]);
+
+ abort();
+}
+
/*
DebugStack
*/
#include <iostream>
#include <exception>
+#include <assert.h>
#include "gettime.h"
#if (defined(WIN32) || defined(_WIN32_WCE))
extern std::ostream dstream_no_stderr;
extern Nullstream dummyout;
-/*
- Include assert.h and immediately undef assert so that it can't override
- our assert later on. leveldb/slice.h is a notable offender.
-*/
-#include <assert.h>
-#undef assert
+/* Abort program execution immediately
+ */
+__NORETURN extern void fatal_error_fn(
+ const char *msg, const char *file,
+ unsigned int line, const char *function);
+
+#define FATAL_ERROR(msg) \
+ fatal_error_fn((msg), __FILE__, __LINE__, __FUNCTION_NAME)
+
+#define FATAL_ERROR_IF(expr, msg) \
+ ((expr) \
+ ? fatal_error_fn((msg), __FILE__, __LINE__, __FUNCTION_NAME) \
+ : (void)(0))
/*
- Assert
+ sanity_check()
+ Equivalent to assert() but persists in Release builds (i.e. when NDEBUG is
+ defined)
*/
-__NORETURN extern void assert_fail(
+__NORETURN extern void sanity_check_fn(
const char *assertion, const char *file,
unsigned int line, const char *function);
-#define ASSERT(expr)\
- ((expr)\
- ? (void)(0)\
- : assert_fail(#expr, __FILE__, __LINE__, __FUNCTION_NAME))
+#define SANITY_CHECK(expr) \
+ ((expr) \
+ ? (void)(0) \
+ : sanity_check_fn(#expr, __FILE__, __LINE__, __FUNCTION_NAME))
+
+#define sanity_check(expr) SANITY_CHECK(expr)
-#define assert(expr) ASSERT(expr)
void debug_set_exception_handler();
*/
// If peer id is non-zero, it has to be unique.
if(player->peer_id != 0)
- assert(getPlayer(player->peer_id) == NULL);
+ FATAL_ERROR_IF(getPlayer(player->peer_id) != NULL, "Peer id not unique");
// Name has to be unique.
- assert(getPlayer(player->getName()) == NULL);
+ FATAL_ERROR_IF(getPlayer(player->getName()) != NULL, "Player name not unique");
// Add.
m_players.push_back(player);
}
i != loaded_blocks.end(); ++i) {
v3s16 p = *i;
MapBlock *block = m_map->getBlockNoCreateNoEx(p);
- assert(block);
+ assert(block != NULL);
block->refGrab();
}
u16 ServerEnvironment::addActiveObject(ServerActiveObject *object)
{
- assert(object);
+ assert(object); // Pre-condition
m_added_objects++;
u16 id = addActiveObjectRaw(object, true, 0);
return id;
u16 ServerEnvironment::addActiveObjectRaw(ServerActiveObject *object,
bool set_changed, u32 dtime_s)
{
- assert(object);
+ assert(object); // Pre-condition
if(object->getId() == 0){
u16 new_id = getFreeServerActiveObjectId(m_active_objects);
if(new_id == 0)
It is a failure if player is local and there already is a local
player
*/
- assert(!(player->isLocal() == true && getLocalPlayer() != NULL));
+ FATAL_ERROR_IF(player->isLocal() == true && getLocalPlayer() != NULL,
+ "Player is local but there is already a local player");
Environment::addPlayer(player);
}
u16 ClientEnvironment::addActiveObject(ClientActiveObject *object)
{
- assert(object);
+ assert(object); // Pre-condition
if(object->getId() == 0)
{
u16 new_id = getFreeClientActiveObjectId(m_active_objects);
m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED;
}
- assert(m_settings != NULL);
- assert(m_env != NULL);
- assert(m_env->getSkin() != NULL);
+ assert(m_settings != NULL); // pre-condition
+ assert(m_env != NULL); // pre-condition
+ assert(m_env->getSkin() != NULL); // pre-condition
m_currentMode = FM_Simple;
if (font == NULL) {
font = m_env->getSkin()->getFont();
}
- assert(font != NULL);
+ FATAL_ERROR_IF(font == NULL, "Could not get skin font");
return font->getDimension(L"Some unimportant example String").Height;
}
if (font == NULL) {
font = m_env->getSkin()->getFont();
}
- assert(font != NULL);
+ FATAL_ERROR_IF(font == NULL, "Could not get font");
return font->getDimension(text.c_str()).Width;
}
if (font == NULL) {
font = m_env->getSkin()->getFont();
}
- assert(font != NULL);
+ FATAL_ERROR_IF(font == NULL, "Could not get font");
return font->getDimension(L"Some unimportant example String").Height
+ font->getKerningHeight();
// If we did fail to create a font our own make irrlicht find a default one
font = m_env->getSkin()->getFont();
- assert(font);
+ FATAL_ERROR_IF(font == NULL, "Could not create/get font");
u32 text_height = font->getDimension(L"Hello, world!").Height;
infostream << "text_height=" << text_height << std::endl;
/** initialize a font without freetype */
void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode)
{
- assert((mode == FM_Simple) || (mode == FM_SimpleMono));
+ assert(mode == FM_Simple || mode == FM_SimpleMono); // pre-condition
std::string font_path = "";
if (mode == FM_Simple) {
u32 new_id = player->addHud(e);
//if this isn't true our huds aren't consistent
- assert(new_id == id);
+ sanity_check(new_id == id);
delete event.hudadd.pos;
delete event.hudadd.name;
GUIEngine::~GUIEngine()
{
video::IVideoDriver* driver = m_device->getVideoDriver();
- assert(driver != 0);
+ FATAL_ERROR_IF(driver == 0, "Could not get video driver");
if(m_sound_manager != &dummySoundManager){
delete m_sound_manager;
bool tile_image, unsigned int minsize)
{
video::IVideoDriver* driver = m_device->getVideoDriver();
- assert(driver != 0);
+ FATAL_ERROR_IF(driver == 0, "Could not get video driver");
if (m_textures[layer].texture != NULL)
{
m_tooltip_element->setOverrideFont(m_font);
gui::IGUISkin* skin = Environment->getSkin();
- assert(skin != NULL);
+ sanity_check(skin != NULL);
gui::IGUIFont *old_font = skin->getFont();
skin->setFont(m_font);
video::IVideoDriver* driver = Environment->getVideoDriver();
Inventory *inv = m_invmgr->getInventory(m_selected_item->inventoryloc);
- assert(inv);
+ sanity_check(inv);
InventoryList *list = inv->getList(m_selected_item->listname);
- assert(list);
+ sanity_check(list);
ItemStack stack = list->getItem(m_selected_item->i);
stack.count = m_selected_amount;
}
gui::IGUISkin* skin = Environment->getSkin();
- assert(skin != NULL);
+ sanity_check(skin != NULL);
gui::IGUIFont *old_font = skin->getFont();
skin->setFont(m_font);
if (hovered && isMyChild(hovered) &&
hovered->getType() == gui::EGUIET_TAB_CONTROL) {
gui::IGUISkin* skin = Environment->getSkin();
- assert(skin != NULL);
+ sanity_check(skin != NULL);
gui::IGUIFont *old_font = skin->getFont();
skin->setFont(m_font);
bool retval = hovered->OnEvent(event);
break;
default:
//can't happen at all!
- assert("reached a source line that can't ever been reached" == 0);
+ FATAL_ERROR("Reached a source line that can't ever been reached");
break;
}
if (current_keys_pending.key_enter && m_allowclose) {
if(m_selected_item) {
inv_selected = m_invmgr->getInventory(m_selected_item->inventoryloc);
- assert(inv_selected);
- assert(inv_selected->getList(m_selected_item->listname) != NULL);
+ sanity_check(inv_selected);
+ sanity_check(inv_selected->getList(m_selected_item->listname) != NULL);
}
u32 s_count = 0;
// But go on
{
- key_setting *k=NULL;
+ key_setting *k = NULL;
for(size_t i = 0; i < key_settings.size(); i++)
{
if(key_settings.at(i)->id == activeKey)
break;
}
}
- assert(k);
+ FATAL_ERROR_IF(k == NULL, "Key setting not found");
k->key = kp;
const wchar_t *text = wgettext(k->key.name());
k->button->setText(text);
break;
}
}
- assert(k);
+ FATAL_ERROR_IF(k == NULL, "Key setting not found");
resetMenu();
shift_down = false;
}
}
- assert("httpfetch_caller_alloc: ran out of caller IDs" == 0);
+ FATAL_ERROR("httpfetch_caller_alloc: ran out of caller IDs");
return discard;
}
return NULL;
}
- assert(m_all_ongoing.empty());
+ FATAL_ERROR_IF(!m_all_ongoing.empty(), "Expected empty");
while (!StopRequested()) {
BEGIN_DEBUG_EXCEPTION_HANDLER
<<std::endl;
CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT);
- assert(res == CURLE_OK);
+ FATAL_ERROR_IF(res != CURLE_OK, "CURL init failed");
g_httpfetch_thread = new CurlFetchThread(parallel_limit);
}
const ItemStack& InventoryList::getItem(u32 i) const
{
- assert(i < m_size);
+ assert(i < m_size); // Pre-condition
return m_items[i];
}
ItemStack& InventoryList::getItem(u32 i)
{
- assert(i < m_size);
+ assert(i < m_size); // Pre-condition
return m_items[i];
}
void InventoryList::deleteItem(u32 i)
{
- assert(i < m_items.size());
+ assert(i < m_items.size()); // Pre-condition
m_items[i].clear();
}
void remove(u16 n)
{
- assert(count >= n);
+ assert(count >= n); // Pre-condition
count -= n;
if(count == 0)
clear(); // reset name, wear and metadata too
os<<"detached:"<<name;
break;
default:
- assert(0);
+ FATAL_ERROR("Unhandled inventory location type");
}
}
<<name<<"\""<<std::endl;
// This is not thread-safe
- assert(get_current_thread_id() == m_main_thread);
+ sanity_check(get_current_thread_id() == m_main_thread);
// Skip if already in cache
ClientCached *cc = NULL;
verbosestream<<"ItemDefManager: registering \""<<def.name<<"\""<<std::endl;
// Ensure that the "" item (the hand) always has ToolCapabilities
if(def.name == "")
- assert(def.tool_capabilities != NULL);
+ FATAL_ERROR_IF(!def.tool_capabilities, "Hand does not have ToolCapabilities");
if(m_item_definitions.count(def.name) == 0)
m_item_definitions[def.name] = new ItemDefinition(def);
m_name = name;
if (strlen(name) > 8 && strncmp(name, "KEY_KEY_", 8) == 0) {
int chars_read = mbtowc(&Char, name + 8, 1);
- assert (chars_read == 1 && "unexpected multibyte character");
+
+ FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character");
} else
Char = L'\0';
return;
try {
Key = keyname_to_keycode(m_name.c_str());
int chars_read = mbtowc(&Char, name, 1);
- assert (chars_read == 1 && "unexpected multibyte character");
+
+ FATAL_ERROR_IF(chars_read != 1, "Unexpected multibyte character");
return;
} catch (UnknownKeycode &e) {};
}
Key = irr::KEY_KEY_CODES_COUNT;
int mbtowc_ret = mbtowc(&Char, name, 1);
- assert (mbtowc_ret == 1 && "unexpected multibyte character");
+ FATAL_ERROR_IF(mbtowc_ret != 1, "Unexpected multibyte character");
m_name = name[0];
}
f32 d = 0.15*BS;
// This should always apply, otherwise there are glitches
- assert(d > pos_max_d);
+ sanity_check(d > pos_max_d);
// Maximum distance over border for sneaking
f32 sneak_max = BS*0.4;
}
void setCAO(GenericCAO* toset) {
- assert( m_cao == NULL );
+ assert( m_cao == NULL ); // Pre-condition
m_cao = toset;
}
if (!game_configure(&game_params, cmd_args))
return 1;
- assert(game_params.world_path != "");
+ sanity_check(game_params.world_path != "");
infostream << "Using commanded world path ["
<< game_params.world_path << "]" << std::endl;
static bool read_config_file(const Settings &cmd_args)
{
// Path of configuration file in use
- assert(g_settings_path == ""); // Sanity check
+ sanity_check(g_settings_path == ""); // Sanity check
if (cmd_args.exists("config")) {
bool r = g_settings->readConfigFile(cmd_args.get("config").c_str());
<< world_path << "]" << std::endl;
}
- assert(world_path != "");
+ assert(world_path != ""); // Post-condition
game_params->world_path = world_path;
return true;
}
{
SubgameSpec gamespec;
- assert(game_params->world_path != ""); // pre-condition
+ assert(game_params->world_path != ""); // Pre-condition
verbosestream << _("Determining gameid/gamespec") << std::endl;
// If world doesn't exist
}
else
{
- // Invalid lighting bank
- assert(0);
+ assert("Invalid lighting bank" == NULL);
}
/*infostream<<"Bottom for sunlight-propagated block ("
}
catch(InvalidPositionException &e)
{
- assert(0);
+ FATAL_ERROR("Invalid position");
}
}
n.setLight(LIGHTBANK_DAY, 0, ndef);
setNode(p, n);
} else {
- assert(0);
+ FATAL_ERROR("Invalid position");
}
}
v2s16 sectorpos(x, z);
// Sector metadata is loaded from disk if not already loaded.
ServerMapSector *sector = createSector(sectorpos);
- assert(sector);
+ FATAL_ERROR_IF(sector == NULL, "createSector() failed");
(void) sector;
for(s16 y=blockpos_min.Y-extra_borders.Y;
lighting on blocks for them.
*/
ServerMapSector *sector;
- try{
+ try {
sector = (ServerMapSector*)createSector(p2d);
assert(sector->getId() == MAPSECTOR_SERVER);
}
}
else
{
- assert(false);
+ r = -1;
}
- assert(r == 2);
+
+ FATAL_ERROR_IF(r != 2, "getSectorPos()");
v2s16 pos((s16)x, (s16)y);
return pos;
}
<<"what()="<<e.what()
<<std::endl;
// Ignoring. A new one will be generated.
- assert(0);
+ abort();
// TODO: Backup file; name is in fullpath.
}
<<"(ignore_world_load_errors)"<<std::endl;
} else {
throw SerializationError("Invalid block data in database");
- //assert(0);
}
}
}
//bool updateChangedVisibleArea();
// Call these before and after saving of many blocks
- virtual void beginSave() {return;};
- virtual void endSave() {return;};
+ virtual void beginSave() { return; }
+ virtual void endSave() { return; }
- virtual void save(ModifiedState save_level){assert(0);};
+ virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
// Server implements these.
// Client leaves them as no-op.
- virtual bool saveBlock(MapBlock *block) { return false; };
- virtual bool deleteBlock(v3s16 blockpos) { return false; };
+ virtual bool saveBlock(MapBlock *block) { return false; }
+ virtual bool deleteBlock(v3s16 blockpos) { return false; }
/*
Updates usage timers and unloads unused blocks and sectors.
throw SerializationError("ERROR: Not writing dummy block.");
}
- assert(version >= SER_FMT_CLIENT_VER_LOWEST);
+ FATAL_ERROR_IF(version < SER_FMT_CLIENT_VER_LOWEST, "Serialize version error");
// First byte
u8 flags = 0;
}
void unDummify()
{
- assert(isDummy());
+ assert(isDummy()); // Pre-condition
reallocate();
}
void MapgenSinglenode::makeChunk(BlockMakeData *data)
{
+ // Pre-conditions
assert(data->vmanip);
assert(data->nodedef);
assert(data->blockpos_requested.X >= data->blockpos_min.X &&
void MapgenV5::makeChunk(BlockMakeData *data)
{
+ // Pre-conditions
assert(data->vmanip);
assert(data->nodedef);
assert(data->blockpos_requested.X >= data->blockpos_min.X &&
void MapgenV6::makeChunk(BlockMakeData *data)
{
+ // Pre-conditions
assert(data->vmanip);
assert(data->nodedef);
assert(data->blockpos_requested.X >= data->blockpos_min.X &&
void MapgenV7::makeChunk(BlockMakeData *data)
{
+ // Pre-conditions
assert(data->vmanip);
assert(data->nodedef);
assert(data->blockpos_requested.X >= data->blockpos_min.X &&
param1 |= (a_light & 0x0f)<<4;
}
else
- assert(0);
+ assert("Invalid light bank" == NULL);
}
bool MapNode::isLightDayNightEq(INodeDefManager *nodemgr) const
if(!ser_ver_supported(version))
throw VersionMismatchException("ERROR: MapNode format not supported");
- assert(content_width == 2);
- assert(params_width == 2);
+ sanity_check(content_width == 2);
+ sanity_check(params_width == 2);
// Can't do this anymore; we have 16-bit dynamically allocated node IDs
// in memory; conversion just won't work in this direction.
if(!ser_ver_supported(version))
throw VersionMismatchException("ERROR: MapNode format not supported");
- assert(version >= 22);
- assert(content_width == 1 || content_width == 2);
- assert(params_width == 2);
+ if (version < 22
+ || (content_width != 1 && content_width != 2)
+ || params_width != 2)
+ FATAL_ERROR("Deserialize bulk node data error");
// Uncompress or read data
u32 len = nodecount * (content_width + params_width);
MapBlock * MapSector::createBlankBlockNoInsert(s16 y)
{
- assert(getBlockBuffered(y) == NULL);
+ assert(getBlockBuffered(y) == NULL); // Pre-condition
v3s16 blockpos_map(m_pos.X, y, m_pos.Y);
void Schematic::placeStructure(Map *map, v3s16 p, u32 flags, Rotation rot,
bool force_placement, INodeDefManager *ndef)
{
- assert(schemdata != NULL);
+ assert(schemdata != NULL); // Pre-condition
MMVManip *vm = new MMVManip(map);
if (rot == ROTATE_RAND)
void ReliablePacketBuffer::insert(BufferedPacket &p,u16 next_expected)
{
JMutexAutoLock listlock(m_list_mutex);
- assert(p.data.getSize() >= BASE_HEADER_SIZE+3);
+ FATAL_ERROR_IF(p.data.getSize() < BASE_HEADER_SIZE+3, "Invalid data size");
u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
- assert(type == TYPE_RELIABLE);
+ sanity_check(type == TYPE_RELIABLE);
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
- assert(seqnum_in_window(seqnum,next_expected,MAX_RELIABLE_WINDOW_SIZE));
- assert(seqnum != next_expected);
+ sanity_check(seqnum_in_window(seqnum, next_expected, MAX_RELIABLE_WINDOW_SIZE));
+ sanity_check(seqnum != next_expected);
++m_list_size;
- assert(m_list_size <= SEQNUM_MAX+1);
+ sanity_check(m_list_size <= SEQNUM_MAX+1); // FIXME: Handle the error?
// Find the right place for the packet and insert it there
// If list is empty, just add it
throw IncomingDataCorruption("duplicated packet isn't same as original one");
}
- assert(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
- assert(i->data.getSize() == p.data.getSize());
- assert(i->address == p.address);
+ sanity_check(readU16(&(i->data[BASE_HEADER_SIZE+1])) == seqnum);
+ sanity_check(i->data.getSize() == p.data.getSize());
+ sanity_check(i->address == p.address);
/* nothing to do this seems to be a resent packet */
/* for paranoia reason data should be compared */
{
JMutexAutoLock listlock(m_map_mutex);
u32 headersize = BASE_HEADER_SIZE + 7;
- assert(p.data.getSize() >= headersize);
+ FATAL_ERROR_IF(p.data.getSize() < headersize, "Invalid data size");
u8 type = readU8(&p.data[BASE_HEADER_SIZE+0]);
- assert(type == TYPE_SPLIT);
+ sanity_check(type == TYPE_SPLIT);
u16 seqnum = readU16(&p.data[BASE_HEADER_SIZE+1]);
u16 chunk_count = readU16(&p.data[BASE_HEADER_SIZE+3]);
u16 chunk_num = readU16(&p.data[BASE_HEADER_SIZE+5]);
{
{
JMutexAutoLock lock(m_exclusive_access_mutex);
- assert(m_usage > 0);
+ sanity_check(m_usage > 0);
m_usage--;
if (!((m_pending_deletion) && (m_usage == 0)))
- BASE_HEADER_SIZE
- RELIABLE_HEADER_SIZE;
- assert(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
+ sanity_check(c.data.getSize() < MAX_RELIABLE_WINDOW_SIZE*512);
std::list<SharedBuffer<u8> > originals;
u16 split_sequence_number = channels[c.channelnum].readNextSplitSeqNum();
channels[c.channelnum].queued_reliables.push(p);
pcount++;
}
- assert(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
+ sanity_check(channels[c.channelnum].queued_reliables.size() < 0xFFFF);
return true;
}
else {
= channels[c.channelnum].putBackSequenceNumber(
(initial_sequence_number+toadd.size() % (SEQNUM_MAX+1)));
- assert(successfully_put_back_sequence_number);
+ FATAL_ERROR_IF(!successfully_put_back_sequence_number, "error");
}
LOG(dout_con<<m_connection->getDesc()
<< " Windowsize exceeded on reliable sending "
u16 UDPPeer::getNextSplitSequenceNumber(u8 channel)
{
- assert(channel < CHANNEL_COUNT);
+ assert(channel < CHANNEL_COUNT); // Pre-condition
return channels[channel].readNextIncomingSeqNum();
}
void UDPPeer::setNextSplitSequenceNumber(u8 channel, u16 seqnum)
{
- assert(channel < CHANNEL_COUNT);
+ assert(channel < CHANNEL_COUNT); // Pre-condition
channels[channel].setNextSplitSeqNum(seqnum);
}
BufferedPacket toadd,
bool reliable)
{
- assert(channel < CHANNEL_COUNT);
+ assert(channel < CHANNEL_COUNT); // Pre-condition
return channels[channel].incoming_splits.insert(toadd,reliable);
}
LOG(derr_con<<m_connection->getDesc()
<<"WARNING: Going to send a reliable packet"
<<" in outgoing buffer" <<std::endl);
- //assert(0);
}
// Send the packet
LOG(dout_con<<m_connection->getDesc()
<<" INFO: dropped packet for non existent peer_id: "
<< peer_id << std::endl);
- assert(reliable && "trying to send raw packet reliable but no peer found!");
+ FATAL_ERROR_IF(!reliable, "Trying to send raw packet reliable but no peer found!");
return false;
}
Channel *channel = &(dynamic_cast<UDPPeer*>(&peer)->channels[channelnum]);
void ConnectionSendThread::processReliableCommand(ConnectionCommand &c)
{
- assert(c.reliable);
+ assert(c.reliable); // Pre-condition
switch(c.type) {
case CONNCMD_NONE:
case CONNCMD_CONNECT:
case CONNCMD_DISCONNECT:
case CONCMD_ACK:
- assert("Got command that shouldn't be reliable as reliable command" == 0);
+ FATAL_ERROR("Got command that shouldn't be reliable as reliable command");
default:
LOG(dout_con<<m_connection->getDesc()
<<" Invalid reliable command type: " << c.type <<std::endl);
void ConnectionSendThread::processNonReliableCommand(ConnectionCommand &c)
{
- assert(!c.reliable);
+ assert(!c.reliable); // Pre-condition
switch(c.type) {
case CONNCMD_NONE:
sendAsPacket(c.peer_id,c.channelnum,c.data,true);
return;
case CONCMD_CREATE_PEER:
- assert("Got command that should be reliable as unreliable command" == 0);
+ FATAL_ERROR("Got command that should be reliable as unreliable command");
default:
LOG(dout_con<<m_connection->getDesc()
<<" Invalid command type: " << c.type <<std::endl);
void ConnectionSendThread::send(u16 peer_id, u8 channelnum,
SharedBuffer<u8> data)
{
- assert(channelnum < CHANNEL_COUNT);
+ assert(channelnum < CHANNEL_COUNT); // Pre-condition
PeerHelper peer = m_connection->getPeerNoEx(peer_id);
if (!peer)
if (MAX_UDP_PEERS <= 65535 && peer_id >= MAX_UDP_PEERS) {
errorstream << "Something is wrong with peer_id" << std::endl;
- assert(0);
+ FATAL_ERROR("");
}
if (type == TYPE_CONTROL)
if (controltype == CONTROLTYPE_ACK)
{
- assert(channel != 0);
+ FATAL_ERROR_IF(channel == 0, "Invalid channel (0)");
if (packetdata.getSize() < 4)
throw InvalidIncomingDataException
("packetdata.getSize() < 4 (ACK header size)");
}
else if (type == TYPE_RELIABLE)
{
- assert(channel != 0);
+ FATAL_ERROR_IF(channel == 0, "Invalid channel (0)");
// Recursive reliable packets not allowed
if (reliable)
throw InvalidIncomingDataException("Found nested reliable packets");
}
// We should never get here.
- // If you get here, add an exception or a return to some of the
- // above conditionals.
- assert(0);
- throw BaseException("Error in Channel::ProcessPacket()");
+ FATAL_ERROR("Invalid execution point");
}
/*
/* Internal stuff */
void Connection::putEvent(ConnectionEvent &e)
{
- assert(e.type != CONNEVENT_NONE);
+ assert(e.type != CONNEVENT_NONE); // Pre-condition
m_event_queue.push_back(e);
}
}
// Error checking
- assert(node->second->id == peer_id);
+ FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
return PeerHelper(node->second);
}
}
// Error checking
- assert(node->second->id == peer_id);
+ FATAL_ERROR_IF(node->second->id != peer_id, "Invalid peer id");
return PeerHelper(node->second);
}
void Connection::Send(u16 peer_id, u8 channelnum,
NetworkPacket* pkt, bool reliable)
{
- assert(channelnum < CHANNEL_COUNT);
+ assert(channelnum < CHANNEL_COUNT); // Pre-condition
ConnectionCommand c;
{
PeerHelper peer = getPeerNoEx(PEER_ID_SERVER);
- if (!peer) {
- assert("Connection::getLocalStat we couldn't get our own peer? are you serious???" == 0);
- }
+ FATAL_ERROR_IF(!peer, "Connection::getLocalStat we couldn't get our own peer? are you serious???");
float retval = 0.0;
retval += dynamic_cast<UDPPeer*>(&peer)->channels[j].getCurrentLossRateKB();
break;
default:
- assert("Connection::getLocalStat Invalid stat type" == 0);
+ FATAL_ERROR("Connection::getLocalStat Invalid stat type");
}
}
return retval;
void Connection::sendAck(u16 peer_id, u8 channelnum, u16 seqnum)
{
- assert(channelnum < CHANNEL_COUNT);
+ assert(channelnum < CHANNEL_COUNT); // Pre-condition
LOG(dout_con<<getDesc()
<<" Queuing ACK command to peer_id: " << peer_id <<
virtual ~Peer() {
JMutexAutoLock usage_lock(m_exclusive_access_mutex);
- assert(m_usage == 0);
+ FATAL_ERROR_IF(m_usage != 0, "Reference counting failure");
};
// Unique id of the peer
void Trigger();
void setParent(Connection* parent) {
- assert(parent != NULL);
+ assert(parent != NULL); // Pre-condition
m_connection = parent;
}
void * Thread ();
void setParent(Connection* parent) {
- assert(parent != NULL);
+ assert(parent != NULL); // Pre-condition
m_connection = parent;
}
// Mesh update thread must be stopped while
// updating content definitions
- assert(!m_mesh_update_thread.IsRunning());
+ sanity_check(!m_mesh_update_thread.IsRunning());
for (u16 i = 0; i < num_files; i++) {
std::string name, sha1_base64;
// Mesh update thread must be stopped while
// updating content definitions
- assert(!m_mesh_update_thread.IsRunning());
+ sanity_check(!m_mesh_update_thread.IsRunning());
for (u32 i=0; i < num_files; i++) {
std::string name;
// Mesh update thread must be stopped while
// updating content definitions
- assert(!m_mesh_update_thread.IsRunning());
+ sanity_check(!m_mesh_update_thread.IsRunning());
// Decompress node definitions
std::string datastring(pkt->getString(0), pkt->getSize());
// Mesh update thread must be stopped while
// updating content definitions
- assert(!m_mesh_update_thread.IsRunning());
+ sanity_check(!m_mesh_update_thread.IsRunning());
// Decompress item definitions
std::string datastring(pkt->getString(0), pkt->getSize());
// IWritableNodeDefManager
content_t CNodeDefManager::set(const std::string &name, const ContentFeatures &def)
{
+ // Pre-conditions
assert(name != "");
assert(name == def.name);
content_t CNodeDefManager::allocateDummy(const std::string &name)
{
- assert(name != "");
+ assert(name != ""); // Pre-condition
ContentFeatures f;
f.name = name;
return set(name, f);
f->serialize(wrapper_os, protocol_version);
os2<<serializeString(wrapper_os.str());
- assert(count + 1 > count); // must not overflow
+ // must not overflow
+ u16 next = count + 1;
+ FATAL_ERROR_IF(next < count, "Overflow");
count++;
}
writeU16(os, count);
if (max-min > (PSEUDORANDOM_MAX + 1) / 10)
{
//dstream<<"WARNING: PseudoRandom::range: max > 32767"<<std::endl;
- assert(0);
+ assert("Something wrong with random number" == NULL);
}
if(min > max)
{
- assert(0);
- return max;
+ assert("Something wrong with random number" == NULL);
+ //return max;
}
return (next()%(max-min+1))+min;
}
virtual PlayerSAO *getPlayerSAO()
{ return NULL; }
virtual void setPlayerSAO(PlayerSAO *sao)
- { assert(0); }
+ { FATAL_ERROR("FIXME"); }
/*
serialize() writes a bunch of text that can contain
//TODO: Test this code
char buf[BUFSIZ];
uint32_t len = sizeof(buf);
- assert(_NSGetExecutablePath(buf, &len) != -1);
+ FATAL_ERROR_IF(_NSGetExecutablePath(buf, &len) == -1, "");
pathRemoveFile(buf, '/');
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
- assert(sysctl(mib, 4, buf, &len, NULL, 0) != -1);
+ FATAL_ERROR_IF(sysctl(mib, 4, buf, &len, NULL, 0) == -1, "");
pathRemoveFile(buf, '/');
*/
#if defined(_WIN32)
- const DWORD buflen = 1000;
+ const DWORD buflen = 1000; // FIXME: Surely there is a better way to do this
char buf[buflen];
DWORD len;
// Find path of executable and set path_share relative to it
len = GetModuleFileName(GetModuleHandle(NULL), buf, buflen);
- assert(len < buflen);
+ FATAL_ERROR_IF(len >= buflen, "Overlow");
pathRemoveFile(buf, '\\');
// Use ".\bin\.."
// Use "C:\Documents and Settings\user\Application Data\<PROJECT_NAME>"
len = GetEnvironmentVariable("APPDATA", buf, buflen);
- assert(len < buflen);
+ FATAL_ERROR_IF(len >= buflen, "Overlow");
path_user = std::string(buf) + DIR_DELIM + PROJECT_NAME;
/*
if (readlink("/proc/self/exe", buf, BUFSIZ-1) == -1) {
errorstream << "Unable to read bindir "<< std::endl;
#ifndef __ANDROID__
- assert("Unable to read bindir" == 0);
+ FATAL_ERROR("Unable to read bindir");
#endif
} else {
pathRemoveFile(buf, '/');
// computed depending on mode
void script_run_callbacks(lua_State *L, int nargs, RunCallbacksMode mode)
{
- assert(lua_gettop(L) >= nargs + 1);
+ FATAL_ERROR_IF(lua_gettop(L) < nargs + 1, "Not enough arguments");
// Insert error handler
lua_pushcfunction(L, script_error_handler);
if (L != NULL) {
script_error(L);
} else {
- /* As of april 2014 assert is not optimized to nop in release builds
- * therefore this is correct. */
- assert("Can't do a scripterror for this deprecated message, so exit completely!");
+ FATAL_ERROR("Can't do a scripterror for this deprecated message, so exit completely!");
}
}
lua_getfield(L, -1, "async_event_handler");
if (lua_isnil(L, -1)) {
- assert("Async event handler does not exist!" == 0);
+ FATAL_ERROR("Async event handler does not exist!");
}
luaL_checktype(L, -1, LUA_TFUNCTION);
/******************************************************************************/
AsyncWorkerThread::~AsyncWorkerThread()
{
- assert(IsRunning() == false);
+ sanity_check(IsRunning() == false);
}
/******************************************************************************/
#endif
m_luastack = luaL_newstate();
- assert(m_luastack);
+ FATAL_ERROR_IF(!m_luastack, "luaL_newstate() failed");
luaL_openlibs(m_luastack);
scriptIface->realityCheck();
lua_State *L = scriptIface->getStack();
- assert(lua_checkstack(L, 20));
+ sanity_check(lua_checkstack(L, 20));
StackUnroller stack_unroller(L);
lua_pushcfunction(L, script_error_handler);
lua_pushnumber(L, m_id);
lua_gettable(L, -2);
if(lua_isnil(L, -1))
- assert(0);
+ FATAL_ERROR("");
lua_remove(L, -2); // Remove registered_abms
// Call action
// Do it
float timeofday_f = luaL_checknumber(L, 1);
- assert(timeofday_f >= 0.0 && timeofday_f <= 1.0);
+ sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
int timeofday_mh = (int)(timeofday_f * 24000.0);
// This should be set directly in the environment but currently
// such changes aren't immediately sent to the clients, so call
int ModApiMainMenu::l_update_formspec(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
if (engine->m_startgame)
return 0;
int ModApiMainMenu::l_start(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
//update c++ gamedata from lua table
int ModApiMainMenu::l_close(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
engine->m_kill = true;
return 0;
int ModApiMainMenu::l_set_background(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
std::string backgroundlevel(luaL_checkstring(L, 1));
std::string texturename(luaL_checkstring(L, 2));
int ModApiMainMenu::l_set_clouds(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
bool value = lua_toboolean(L,1);
int ModApiMainMenu::l_get_table_index(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
std::wstring tablename(narrow_to_wide(luaL_checkstring(L, 1)));
GUITable *table = engine->m_menu->getTable(tablename);
int ModApiMainMenu::l_show_keys_menu(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
GUIKeyChangeMenu *kmenu
= new GUIKeyChangeMenu( engine->m_device->getGUIEnvironment(),
int ModApiMainMenu::l_set_topleft_text(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
std::string text = "";
int ModApiMainMenu::l_extract_zip(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);(engine != 0);
const char *zipfile = luaL_checkstring(L, 1);
const char *destination = luaL_checkstring(L, 2);
return 1;
}
- assert(fs->getFileArchiveCount() > 0);
+ sanity_check(fs->getFileArchiveCount() > 0);
/**********************************************************************/
/* WARNING this is not threadsafe!! */
int ModApiMainMenu::l_get_mainmenu_path(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
lua_pushstring(L,engine->getScriptDir().c_str());
return 1;
int ModApiMainMenu::l_show_file_open_dialog(lua_State *L)
{
GUIEngine* engine = getGuiEngine(L);
- assert(engine != 0);
+ sanity_check(engine != NULL);
const char *formname= luaL_checkstring(L, 1);
const char *title = luaL_checkstring(L, 2);
const char* serialized_param_raw = luaL_checklstring(L, 2, ¶m_length);
- assert(serialized_func_raw != NULL);
- assert(serialized_param_raw != NULL);
+ sanity_check(serialized_func_raw != NULL);
+ sanity_check(serialized_param_raw != NULL);
std::string serialized_func = std::string(serialized_func_raw, func_length);
std::string serialized_param = std::string(serialized_param_raw, param_length);
}
break;
default:
- assert(0);
+ sanity_check(false); // abort
break;
}
return NULL;
}
break;
default:
- assert(0);
+ sanity_check(false); // abort
break;
}
}
break;
default:
- assert("Invalid peer change event received!" == 0);
+ FATAL_ERROR("Invalid peer change event received!");
break;
}
}
// Put the new preview in
InventoryList *plist = player->inventory.getList("craftpreview");
- assert(plist);
- assert(plist->getSize() >= 1);
+ sanity_check(plist);
+ sanity_check(plist->getSize() >= 1);
plist->changeItem(0, preview);
}
infostream<<"Server creating detached inventory \""<<name<<"\""<<std::endl;
}
Inventory *inv = new Inventory(m_itemdef);
- assert(inv);
+ sanity_check(inv);
m_detached_inventories[name] = inv;
//TODO find a better way to do this
sendDetachedInventory(name,PEER_ID_INEXISTENT);
it = m_settings.find(name);
if (it != m_settings.end() && it->second.is_group) {
os << line << "\n";
- assert(it->second.group != NULL);
+ sanity_check(it->second.group != NULL);
was_modified |= it->second.group->updateConfigObject(is, os,
"}", tab_depth + 1);
} else {
virtual void OnSetConstants(video::IMaterialRendererServices *services, s32 userData)
{
video::IVideoDriver *driver = services->getVideoDriver();
- assert(driver);
+ sanity_check(driver != NULL);
bool is_highlevel = userData;
bool is_highlevel)
{
video::IVideoDriver *driver = services->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
// set inverted world matrix
core::matrix4 invWorld = driver->getTransform(video::ETS_WORLD);
ShaderSource::ShaderSource(IrrlichtDevice *device):
m_device(device)
{
- assert(m_device);
+ assert(m_device); // Pre-condition
m_shader_callback = new ShaderCallback(this, "default");
"name_of_shader=\""<<name_of_shader<<"\", "
"filename=\""<<filename<<"\""<<std::endl;*/
- assert(get_current_thread_id() == m_main_thread);
+ sanity_check(get_current_thread_id() == m_main_thread);
m_sourcecache.insert(name_of_shader, filename, program, true);
}
return shaderinfo;
video::IVideoDriver* driver = device->getVideoDriver();
- assert(driver);
+ sanity_check(driver);
video::IGPUProgrammingServices *gpu = driver->getGPUProgrammingServices();
if(!gpu){
#include <AL/alext.h>
#endif
#include <vorbis/vorbisfile.h>
+#include <assert.h>
#include "log.h"
#include "filesys.h"
#include "util/numeric.h" // myrand()
-#include "debug.h" // assert()
#include "porting.h"
#include <map>
#include <vector>
{
dstream<<"ERROR: StaticObjectList::insert(): "
<<"id already exists"<<std::endl;
- assert(0);
- return;
+ FATAL_ERROR("StaticObjectList::insert()");
}
m_active[id] = obj;
}
void remove(u16 id)
{
- assert(id != 0);
+ assert(id != 0); // Pre-condition
if(m_active.find(id) == m_active.end())
{
dstream<<"WARNING: StaticObjectList::remove(): id="<<id
UASSERT(hand_client.last_id == 1);
UASSERT(hand_server.count == 1);
UASSERT(hand_server.last_id == 2);
-
- //assert(0);
}
};
// Creates a string with the length as the first two bytes
std::string serializeString(const std::string &plain)
{
- //assert(plain.size() <= 65535);
if(plain.size() > 65535)
throw SerializationError("String too long for serializeString");
char buf[2];
// Creates a string with the length as the first two bytes from wide string
std::string serializeWideString(const std::wstring &plain)
{
- //assert(plain.size() <= 65535);
if(plain.size() > 65535)
throw SerializationError("String too long for serializeString");
char buf[2];
}
t++;
}
-
+
*lasts = t;
return s;
}
{
char *endptr;
u64 num;
-
+
if (str[0] == '0' && str[1] == 'x')
num = strtoull(str, &endptr, 16);
else
num = strtoull(str, &endptr, 10);
-
+
if (*endptr)
num = murmur_hash_64_ua(str, (int)strlen(str), 0x1337);
-
+
return num;
}
{
std::replace(str.begin(), str.end(), from, to);
}
-
return;
}
- assert(contains(a));
+ assert(contains(a)); // pre-condition
// Take back area, XY inclusive
{
if (it == m_extrusion_meshes.end()) {
// no viable resolution found; use largest one
it = m_extrusion_meshes.find(MAX_EXTRUSION_MESH_RESOLUTION);
- assert(it != m_extrusion_meshes.end());
+ sanity_check(it != m_extrusion_meshes.end());
}
scene::IMesh *mesh = it->second;
WieldMeshSceneNode::~WieldMeshSceneNode()
{
- assert(g_extrusion_mesh_cache);
+ sanity_check(g_extrusion_mesh_cache);
if (g_extrusion_mesh_cache->drop())
g_extrusion_mesh_cache = NULL;
}