General code cleanups/maintenance

This commit is contained in:
sfan5 2022-02-09 22:46:07 +01:00
parent b491dd375a
commit e4bf375ac7
17 changed files with 137 additions and 148 deletions

@ -26,11 +26,10 @@ static inline int color2int(const Color &c)
static inline Color int2color(int c)
{
Color c2;
u8 a;
c2.b = c & 0xff;
c2.g = (c >> 8) & 0xff;
c2.r = (c >> 16) & 0xff;
a = (c >> 24) & 0xff;
u8 a = (c >> 24) & 0xff;
c2.a = 255 - (a*255 / gdAlphaMax);
return c2;
}
@ -55,7 +54,7 @@ static inline void check_bounds(int x, int y, int width, int height)
Image::Image(int width, int height) :
m_width(width), m_height(height), m_image(NULL)
m_width(width), m_height(height), m_image(nullptr)
{
SIZECHECK(0, 0);
m_image = gdImageCreateTrueColor(m_width, m_height);

@ -22,14 +22,14 @@ PlayerAttributes::PlayerAttributes(const std::string &worldDir)
else if (backend == "sqlite3")
readSqlite(worldDir + "players.sqlite");
else
throw std::runtime_error(((std::string) "Unknown player backend: ") + backend);
throw std::runtime_error(std::string("Unknown player backend: ") + backend);
}
void PlayerAttributes::readFiles(const std::string &playersPath)
{
DIR *dir;
dir = opendir (playersPath.c_str());
if (dir == NULL)
if (!dir)
return;
struct dirent *ent;
@ -37,9 +37,8 @@ void PlayerAttributes::readFiles(const std::string &playersPath)
if (ent->d_name[0] == '.')
continue;
std::string path = playersPath + PATH_SEPARATOR + ent->d_name;
std::ifstream in(path);
if(!in.good())
std::ifstream in(playersPath + PATH_SEPARATOR + ent->d_name);
if (!in.good())
continue;
std::string name, position;
@ -57,16 +56,17 @@ void PlayerAttributes::readFiles(const std::string &playersPath)
iss >> tmp; // ','
iss >> player.z;
iss >> tmp; // ')'
if(tmp != ')')
if (tmp != ')')
continue;
player.name = name;
player.x /= 10.0;
player.y /= 10.0;
player.z /= 10.0;
player.x /= 10.0f;
player.y /= 10.0f;
player.z /= 10.0f;
m_players.push_back(player);
}
closedir(dir);
}
@ -101,14 +101,14 @@ void PlayerAttributes::readSqlite(const std::string &db_name)
Player player;
const unsigned char *name_ = sqlite3_column_text(stmt_get_player_pos, 0);
player.name = std::string(reinterpret_cast<const char*>(name_));
player.name = reinterpret_cast<const char*>(name_);
player.x = sqlite3_column_double(stmt_get_player_pos, 1);
player.y = sqlite3_column_double(stmt_get_player_pos, 2);
player.z = sqlite3_column_double(stmt_get_player_pos, 3);
player.x /= 10.0;
player.y /= 10.0;
player.z /= 10.0;
player.x /= 10.0f;
player.y /= 10.0f;
player.z /= 10.0f;
m_players.push_back(player);
}

@ -33,18 +33,6 @@
#define __has_builtin(x) 0
#endif
template<typename T>
static inline T mymax(T a, T b)
{
return (a > b) ? a : b;
}
template<typename T>
static inline T mymin(T a, T b)
{
return (a > b) ? b : a;
}
// saturating multiplication
template<typename T, class = typename std::enable_if<std::is_unsigned<T>::value>::type>
inline T sat_mul(T a, T b)
@ -92,7 +80,7 @@ static int round_multiple_nosign(int n, int f)
return sign * (abs_n + f - (abs_n % f));
}
static inline unsigned int colorSafeBounds (int channel)
static inline unsigned int colorSafeBounds(int channel)
{
return mymin(mymax(channel, 0), 255);
}
@ -267,12 +255,8 @@ void TileGenerator::parseColorsFile(const std::string &fileName)
parseColorsStream(in);
}
void TileGenerator::printGeometry(const std::string &input)
void TileGenerator::printGeometry(const std::string &input_path)
{
std::string input_path = input;
if (input_path.back() != PATH_SEPARATOR)
input_path += PATH_SEPARATOR;
setExhaustiveSearch(EXH_NEVER);
openDb(input_path);
loadBlocks();
@ -284,15 +268,10 @@ void TileGenerator::printGeometry(const std::string &input)
<< std::endl;
closeDatabase();
}
void TileGenerator::dumpBlock(const std::string &input, BlockPos pos)
void TileGenerator::dumpBlock(const std::string &input_path, BlockPos pos)
{
std::string input_path = input;
if (input_path.back() != PATH_SEPARATOR)
input_path += PATH_SEPARATOR;
openDb(input_path);
BlockList list;
@ -309,12 +288,8 @@ void TileGenerator::dumpBlock(const std::string &input, BlockPos pos)
closeDatabase();
}
void TileGenerator::generate(const std::string &input, const std::string &output)
void TileGenerator::generate(const std::string &input_path, const std::string &output)
{
std::string input_path = input;
if (input_path.back() != PATH_SEPARATOR)
input_path += PATH_SEPARATOR;
if (m_dontWriteEmpty) // FIXME: possible too, just needs to be done differently
setExhaustiveSearch(EXH_NEVER);
openDb(input_path);
@ -348,21 +323,19 @@ void TileGenerator::parseColorsStream(std::istream &in)
while (in.good()) {
in.getline(line, sizeof(line));
for(char *p = line; *p; p++) {
if(*p != '#')
for (char *p = line; *p; p++) {
if (*p != '#')
continue;
*p = '\0'; // Cut off at the first #
break;
}
if(strlen(line) == 0)
if(!line[0])
continue;
char name[128 + 1] = {0};
unsigned int r, g, b, a, t;
a = 255;
t = 0;
int items = sscanf(line, "%128s %u %u %u %u %u", name, &r, &g, &b, &a, &t);
if(items < 4) {
char name[200 + 1] = {0};
unsigned int r, g, b, a = 255, t = 0;
int items = sscanf(line, "%200s %u %u %u %u %u", name, &r, &g, &b, &a, &t);
if (items < 4) {
std::cerr << "Failed to parse color entry '" << line << "'" << std::endl;
continue;
}
@ -387,33 +360,37 @@ std::set<std::string> TileGenerator::getSupportedBackends()
return r;
}
void TileGenerator::openDb(const std::string &input)
void TileGenerator::openDb(const std::string &input_path)
{
std::string input = input_path;
if (input.back() != PATH_SEPARATOR)
input += PATH_SEPARATOR;
std::string backend = m_backend;
if (backend == "") {
std::ifstream ifs(input + "/world.mt");
if (backend.empty()) {
std::ifstream ifs(input + "world.mt");
if(!ifs.good())
throw std::runtime_error("Failed to open world.mt");
backend = read_setting_default("backend", ifs, "sqlite3");
ifs.close();
}
if(backend == "sqlite3")
if (backend == "sqlite3")
m_db = new DBSQLite3(input);
#if USE_POSTGRESQL
else if(backend == "postgresql")
else if (backend == "postgresql")
m_db = new DBPostgreSQL(input);
#endif
#if USE_LEVELDB
else if(backend == "leveldb")
else if (backend == "leveldb")
m_db = new DBLevelDB(input);
#endif
#if USE_REDIS
else if(backend == "redis")
else if (backend == "redis")
m_db = new DBRedis(input);
#endif
else
throw std::runtime_error(((std::string) "Unknown map backend: ") + backend);
throw std::runtime_error(std::string("Unknown map backend: ") + backend);
// Determine how we're going to traverse the database (heuristic)
if (m_exhaustiveSearch == EXH_AUTO) {
@ -494,7 +471,6 @@ void TileGenerator::createImage()
if(!m_drawScale)
m_scales = 0;
// If a geometry is explicitly set, set the bounding box to the requested geometry
// instead of cropping to the content. This way we will always output a full tile
// of the correct size.
@ -861,12 +837,12 @@ void TileGenerator::writeImage(const std::string &output)
{
m_image->save(output);
delete m_image;
m_image = NULL;
m_image = nullptr;
}
void TileGenerator::printUnknown()
{
if (m_unknownNodes.size() == 0)
if (m_unknownNodes.empty())
return;
std::cerr << "Unknown nodes:" << std::endl;
for (const auto &node : m_unknownNodes)

@ -2,7 +2,7 @@
#include <stdint.h>
#include "ZlibDecompressor.h"
ZlibDecompressor::ZlibDecompressor(const unsigned char *data, std::size_t size):
ZlibDecompressor::ZlibDecompressor(const u8 *data, size_t size):
m_data(data),
m_seekPos(0),
m_size(size)
@ -13,12 +13,12 @@ ZlibDecompressor::~ZlibDecompressor()
{
}
void ZlibDecompressor::setSeekPos(std::size_t seekPos)
void ZlibDecompressor::setSeekPos(size_t seekPos)
{
m_seekPos = seekPos;
}
std::size_t ZlibDecompressor::seekPos() const
size_t ZlibDecompressor::seekPos() const
{
return m_seekPos;
}
@ -26,7 +26,7 @@ std::size_t ZlibDecompressor::seekPos() const
ustring ZlibDecompressor::decompress()
{
const unsigned char *data = m_data + m_seekPos;
const std::size_t size = m_size - m_seekPos;
const size_t size = m_size - m_seekPos;
ustring buffer;
constexpr size_t BUFSIZE = 128 * 1024;
@ -54,7 +54,7 @@ ustring ZlibDecompressor::decompress()
throw DecompressError();
m_seekPos += strm.next_in - data;
(void)inflateEnd(&strm);
(void) inflateEnd(&strm);
return buffer;
}

@ -5,7 +5,7 @@
static inline int64_t stoi64(const std::string &s)
{
std::stringstream tmp(s);
std::istringstream tmp(s);
int64_t t;
tmp >> t;
return t;

@ -11,8 +11,8 @@
DBPostgreSQL::DBPostgreSQL(const std::string &mapdir)
{
std::ifstream ifs((mapdir + "/world.mt").c_str());
if(!ifs.good())
std::ifstream ifs(mapdir + "world.mt");
if (!ifs.good())
throw std::runtime_error("Failed to read world.mt");
std::string connect_string = read_setting("pgsql_connection", ifs);
ifs.close();

@ -20,7 +20,6 @@ static inline int64_t stoi64(const std::string &s)
return t;
}
static inline std::string i64tos(int64_t i)
{
std::ostringstream os;
@ -28,10 +27,11 @@ static inline std::string i64tos(int64_t i)
return os.str();
}
DBRedis::DBRedis(const std::string &mapdir)
{
std::ifstream ifs((mapdir + "/world.mt").c_str());
if(!ifs.good())
std::ifstream ifs(mapdir + "world.mt");
if (!ifs.good())
throw std::runtime_error("Failed to read world.mt");
std::string tmp;
@ -40,12 +40,16 @@ DBRedis::DBRedis(const std::string &mapdir)
hash = read_setting("redis_hash", ifs);
ifs.seekg(0);
const char *addr = tmp.c_str();
int port = stoi64(read_setting_default("redis_port", ifs, "6379"));
ctx = tmp.find('/') != std::string::npos ? redisConnectUnix(addr) : redisConnect(addr, port);
if(!ctx) {
if (tmp.find('/') != std::string::npos) {
ctx = redisConnectUnix(tmp.c_str());
} else {
int port = stoi64(read_setting_default("redis_port", ifs, "6379"));
ctx = redisConnect(tmp.c_str(), port);
}
if (!ctx) {
throw std::runtime_error("Cannot allocate redis context");
} else if(ctx->err) {
} else if (ctx->err) {
std::string err = std::string("Connection error: ") + ctx->errstr;
redisFree(ctx);
throw std::runtime_error(err);
@ -82,8 +86,9 @@ std::vector<BlockPos> DBRedis::getBlockPos(BlockPos min, BlockPos max)
}
const char *DBRedis::replyTypeStr(int type) {
switch(type) {
const char *DBRedis::replyTypeStr(int type)
{
switch (type) {
case REDIS_REPLY_STATUS:
return "REDIS_REPLY_STATUS";
case REDIS_REPLY_ERROR:
@ -97,7 +102,7 @@ const char *DBRedis::replyTypeStr(int type) {
case REDIS_REPLY_ARRAY:
return "REDIS_REPLY_ARRAY";
default:
return "unknown";
return "(unknown)";
}
}
@ -106,12 +111,12 @@ void DBRedis::loadPosCache()
{
redisReply *reply;
reply = (redisReply*) redisCommand(ctx, "HKEYS %s", hash.c_str());
if(!reply)
if (!reply)
throw std::runtime_error("Redis command HKEYS failed");
if(reply->type != REDIS_REPLY_ARRAY)
if (reply->type != REDIS_REPLY_ARRAY)
REPLY_TYPE_ERR(reply, "HKEYS reply");
for(size_t i = 0; i < reply->elements; i++) {
if(reply->element[i]->type != REDIS_REPLY_STRING)
for (size_t i = 0; i < reply->elements; i++) {
if (reply->element[i]->type != REDIS_REPLY_STRING)
REPLY_TYPE_ERR(reply->element[i], "HKEYS subreply");
BlockPos pos = decodeBlockPos(stoi64(reply->element[i]->str));
posCache[pos.z].emplace_back(pos.x, pos.y);
@ -128,25 +133,24 @@ void DBRedis::HMGET(const std::vector<BlockPos> &positions,
argv[0] = "HMGET";
argv[1] = hash.c_str();
std::vector<BlockPos>::const_iterator position = positions.begin();
std::size_t remaining = positions.size();
std::size_t abs_i = 0;
auto position = positions.begin();
size_t remaining = positions.size();
size_t abs_i = 0;
while (remaining > 0) {
const std::size_t batch_size =
(remaining > DB_REDIS_HMGET_NUMFIELDS) ? DB_REDIS_HMGET_NUMFIELDS : remaining;
const size_t batch_size = mymin<size_t>(DB_REDIS_HMGET_NUMFIELDS, remaining);
redisReply *reply;
{
// storage to preserve validity of .c_str()
std::string keys[batch_size];
for (std::size_t i = 0; i < batch_size; ++i) {
for (size_t i = 0; i < batch_size; ++i) {
keys[i] = i64tos(encodeBlockPos(*position++));
argv[i+2] = keys[i].c_str();
}
reply = (redisReply*) redisCommandArgv(ctx, batch_size + 2, argv, NULL);
}
if(!reply)
if (!reply)
throw std::runtime_error("Redis command HMGET failed");
if (reply->type != REDIS_REPLY_ARRAY)
REPLY_TYPE_ERR(reply, "HMGET reply");
@ -154,7 +158,7 @@ void DBRedis::HMGET(const std::vector<BlockPos> &positions,
freeReplyObject(reply);
throw std::runtime_error("HMGET wrong number of elements");
}
for (std::size_t i = 0; i < reply->elements; ++i) {
for (size_t i = 0; i < reply->elements; ++i) {
redisReply *subreply = reply->element[i];
if (subreply->type == REDIS_REPLY_NIL)
continue;
@ -162,10 +166,14 @@ void DBRedis::HMGET(const std::vector<BlockPos> &positions,
REPLY_TYPE_ERR(subreply, "HMGET subreply");
if (subreply->len == 0)
throw std::runtime_error("HMGET empty string");
result(abs_i + i, ustring((const unsigned char *) subreply->str, subreply->len));
result(abs_i + i, ustring(
reinterpret_cast<const unsigned char*>(subreply->str),
subreply->len
));
}
freeReplyObject(reply);
abs_i += reply->elements;
abs_i += batch_size;
remaining -= batch_size;
}
}

@ -151,7 +151,7 @@ void DBSQLite3::getBlocksOnXZ(BlockList &blocks, int16_t x, int16_t z,
* because it's bad for performance. But rather than silently breaking
* do the right thing and load the blocks again. */
#ifndef NDEBUG
std::cout << "Warning: suboptimal access pattern for sqlite3 backend" << std::endl;
std::cerr << "Warning: suboptimal access pattern for sqlite3 backend" << std::endl;
#endif
loadBlockCache(z);
}

@ -2,13 +2,16 @@
#include <climits>
#include <cstdint>
#include "config.h"
#define BLOCK_SIZE 16
struct PixelAttribute {
PixelAttribute(): height(INT16_MIN), thickness(0) {};
PixelAttribute() : height(INT16_MIN), thickness(0) {};
int16_t height;
uint8_t thickness;
inline bool valid_height() {
inline bool valid_height() const {
return height != INT16_MIN;
}
};
@ -18,8 +21,10 @@ class PixelAttributes
public:
PixelAttributes();
virtual ~PixelAttributes();
void setWidth(int width);
void scroll();
inline PixelAttribute &attribute(int z, int x) {
return m_pixelAttributes[z + 1][x + 1];
};

@ -6,7 +6,7 @@
struct Player
{
std::string name;
double x, y, z;
float x, y, z;
};
class PlayerAttributes

@ -4,7 +4,6 @@
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <cstdint>
#include <string>
@ -66,7 +65,6 @@ class TileGenerator
{
private:
typedef std::unordered_map<std::string, ColorEntry> ColorMap;
typedef std::unordered_set<std::string> NameSet;
public:
TileGenerator();
@ -154,7 +152,7 @@ private:
ColorMap m_colorMap;
BitmapThing m_readPixels;
BitmapThing m_readInfo;
NameSet m_unknownNodes;
std::set<std::string> m_unknownNodes;
Color m_color[16][16];
uint8_t m_thickness[16][16];

@ -16,6 +16,5 @@ public:
private:
const u8 *m_data;
size_t m_seekPos;
size_t m_size;
size_t m_seekPos, m_size;
};

@ -4,8 +4,6 @@
#define PATH_SEPARATOR '/'
#endif
#define BLOCK_SIZE 16
#ifdef USE_CMAKE_CONFIG_H
#include "cmake_config.h"
#else

@ -21,7 +21,7 @@ protected:
PGresult *execPrepared(
const char *stmtName, const int paramsNumber,
const void **params,
const int *paramsLengths = NULL, const int *paramsFormats = NULL,
const int *paramsLengths = nullptr, const int *paramsFormats = nullptr,
bool clear = true
);
int pg_binary_to_int(PGresult *res, int row, int col);

@ -1,7 +1,19 @@
#pragma once
#include <string>
#include <fstream>
#include <iostream>
template<typename T>
static inline T mymax(T a, T b)
{
return (a > b) ? a : b;
}
template<typename T>
static inline T mymin(T a, T b)
{
return (a > b) ? b : a;
}
std::string read_setting(const std::string &name, std::istream &is);

@ -57,28 +57,36 @@ static void usage()
printf("\n");
}
static bool file_exists(const std::string &path)
static inline bool file_exists(const std::string &path)
{
std::ifstream ifs(path);
return ifs.is_open();
}
static inline int stoi(const char *s)
{
std::istringstream iss(s);
int ret;
iss >> ret;
return ret;
}
static std::string search_colors(const std::string &worldpath)
{
if(file_exists(worldpath + "/colors.txt"))
if (file_exists(worldpath + "/colors.txt"))
return worldpath + "/colors.txt";
#ifndef _WIN32
char *home = std::getenv("HOME");
if(home) {
std::string check = ((std::string) home) + "/.minetest/colors.txt";
if(file_exists(check))
if (home) {
std::string check = std::string(home) + "/.minetest/colors.txt";
if (file_exists(check))
return check;
}
#endif
constexpr bool sharedir_valid = !(SHAREDIR[0] == '.' || SHAREDIR[0] == '\0');
if(sharedir_valid && file_exists(SHAREDIR "/colors.txt"))
if (sharedir_valid && file_exists(SHAREDIR "/colors.txt"))
return SHAREDIR "/colors.txt";
std::cerr << "Warning: Falling back to using colors.txt from current directory." << std::endl;
@ -171,19 +179,11 @@ int main(int argc, char *argv[])
case 'd':
generator.setBackend(optarg);
break;
case 'a': {
std::istringstream iss(optarg);
int miny;
iss >> miny;
generator.setMinY(miny);
}
case 'a':
generator.setMinY(stoi(optarg));
break;
case 'c': {
std::istringstream iss(optarg);
int maxy;
iss >> maxy;
generator.setMaxY(maxy);
}
case 'c':
generator.setMaxY(stoi(optarg));
break;
case 'g': {
std::istringstream geometry(optarg);
@ -199,23 +199,19 @@ int main(int argc, char *argv[])
break;
case 'f': {
uint flags = 0;
if(strchr(optarg, 't') != NULL)
if (strchr(optarg, 't'))
flags |= SCALE_TOP;
if(strchr(optarg, 'b') != NULL)
if (strchr(optarg, 'b'))
flags |= SCALE_BOTTOM;
if(strchr(optarg, 'l') != NULL)
if (strchr(optarg, 'l'))
flags |= SCALE_LEFT;
if(strchr(optarg, 'r') != NULL)
if (strchr(optarg, 'r'))
flags |= SCALE_RIGHT;
generator.setScales(flags);
}
break;
case 'z': {
std::istringstream iss(optarg);
int zoom;
iss >> zoom;
generator.setZoom(zoom);
}
case 'z':
generator.setZoom(stoi(optarg));
break;
case 'C':
colors = optarg;
@ -224,15 +220,13 @@ int main(int argc, char *argv[])
generator.setDontWriteEmpty(true);
break;
case 'j': {
int mode;
int mode = EXH_AUTO;;
if (!strcmp(optarg, "never"))
mode = EXH_NEVER;
else if (!strcmp(optarg, "y"))
mode = EXH_Y;
else if (!strcmp(optarg, "full"))
mode = EXH_FULL;
else
mode = EXH_AUTO;
generator.setExhaustiveSearch(mode);
}
break;
@ -267,7 +261,7 @@ int main(int argc, char *argv[])
return 0;
}
if(colors == "")
if(colors.empty())
colors = search_colors(input);
generator.parseColorsFile(colors);
generator.generate(input, output);

@ -3,15 +3,15 @@
#include "util.h"
static inline std::string trim(const std::string &s)
static std::string trim(const std::string &s)
{
auto isspace = [] (char c) -> bool { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };
size_t front = 0;
while(isspace(s[front]))
while (isspace(s[front]))
++front;
size_t back = s.size() - 1;
while(back > front && isspace(s[back]))
while (back > front && isspace(s[back]))
--back;
return s.substr(front, back - front + 1);
@ -23,7 +23,7 @@ std::string read_setting(const std::string &name, std::istream &is)
while (is.good()) {
is.getline(linebuf, sizeof(linebuf));
for(char *p = linebuf; *p; p++) {
for (char *p = linebuf; *p; p++) {
if(*p != '#')
continue;
*p = '\0'; // Cut off at the first #