3 Copyright (C) 2010-2011 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #include "clientserver.h"
26 #include "jmutexautolock.h"
28 #include "constants.h"
32 #include "serverobject.h"
35 #include "scriptapi.h"
41 #include "mapgen_v6.h"
44 /////////////////////////////// Emerge Manager ////////////////////////////////
46 EmergeManager::EmergeManager(IGameDef *gamedef, BiomeDefManager *bdef) {
47 //register built-in mapgens
48 registerMapgen("v6", new MapgenFactoryV6());
50 this->biomedef = bdef ? bdef : new BiomeDefManager(gamedef);
53 mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
58 if (g_settings->get("num_emerge_threads").empty()) {
59 int nprocs = porting::getNumberOfProcessors();
60 // leave a proc for the main thread and one for some other misc threads
61 nthreads = (nprocs > 2) ? nprocs - 2 : 1;
63 nthreads = g_settings->getU16("num_emerge_threads");
68 qlimit_total = g_settings->getU16("emergequeue_limit_total");
69 qlimit_diskonly = g_settings->get("emergequeue_limit_diskonly").empty() ?
71 g_settings->getU16("emergequeue_limit_diskonly");
72 qlimit_generate = g_settings->get("emergequeue_limit_generate").empty() ?
74 g_settings->getU16("emergequeue_limit_generate");
76 for (int i = 0; i != nthreads; i++)
77 emergethread.push_back(new EmergeThread((Server *)gamedef, i));
79 infostream << "EmergeManager: using " << nthreads << " threads" << std::endl;
83 EmergeManager::~EmergeManager() {
84 for (unsigned int i = 0; i != emergethread.size(); i++) {
85 emergethread[i]->setRun(false);
86 emergethread[i]->qevent.signal();
87 emergethread[i]->stop();
88 delete emergethread[i];
97 void EmergeManager::initMapgens(MapgenParams *mgparams) {
103 this->params = mgparams;
104 for (unsigned int i = 0; i != emergethread.size(); i++) {
105 mg = createMapgen(params->mg_name, 0, params);
107 infostream << "EmergeManager: falling back to mapgen v6" << std::endl;
109 params = createMapgenParams("v6");
110 mg = createMapgen("v6", 0, params);
112 mapgen.push_back(mg);
117 bool EmergeManager::enqueueBlockEmerge(u16 peer_id, v3s16 p, bool allow_generate) {
118 std::map<v3s16, BlockEmergeData *>::const_iterator iter;
119 BlockEmergeData *bedata;
125 flags |= BLOCK_EMERGE_ALLOWGEN;
128 JMutexAutoLock queuelock(queuemutex);
130 count = blocks_enqueued.size();
131 if (count >= qlimit_total)
134 count = peer_queue_count[peer_id];
135 u16 qlimit_peer = allow_generate ? qlimit_generate : qlimit_diskonly;
136 if (count >= qlimit_peer)
139 iter = blocks_enqueued.find(p);
140 if (iter != blocks_enqueued.end()) {
141 bedata = iter->second;
142 bedata->flags |= flags;
146 bedata = new BlockEmergeData;
147 bedata->flags = flags;
148 bedata->peer_requested = peer_id;
149 blocks_enqueued.insert(std::make_pair(p, bedata));
151 peer_queue_count[peer_id] = count + 1;
153 // insert into the EmergeThread queue with the least items
154 int lowestitems = emergethread[0]->blockqueue.size();
155 for (unsigned int i = 1; i != emergethread.size(); i++) {
156 int nitems = emergethread[i]->blockqueue.size();
157 if (nitems < lowestitems) {
159 lowestitems = nitems;
163 emergethread[idx]->blockqueue.push(p);
165 emergethread[idx]->qevent.signal();
171 int EmergeManager::getGroundLevelAtPoint(v2s16 p) {
172 if (mapgen.size() == 0 || !mapgen[0]) {
173 errorstream << "EmergeManager: getGroundLevelAtPoint() called"
174 " before mapgen initialized" << std::endl;
178 return mapgen[0]->getGroundLevelAtPoint(p);
182 bool EmergeManager::isBlockUnderground(v3s16 blockpos) {
184 v2s16 p = v2s16((blockpos.X * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2,
185 (blockpos.Y * MAP_BLOCKSIZE) + MAP_BLOCKSIZE / 2);
186 int ground_level = getGroundLevelAtPoint(p);
187 return blockpos.Y * (MAP_BLOCKSIZE + 1) <= min(water_level, ground_level);
190 //yuck, but then again, should i bother being accurate?
191 //the height of the nodes in a single block is quite variable
192 return blockpos.Y * (MAP_BLOCKSIZE + 1) <= params->water_level;
196 u32 EmergeManager::getBlockSeed(v3s16 p) {
197 return (u32)(params->seed & 0xFFFFFFFF) +
204 Mapgen *EmergeManager::createMapgen(std::string mgname, int mgid,
205 MapgenParams *mgparams) {
206 std::map<std::string, MapgenFactory *>::const_iterator iter;
207 iter = mglist.find(mgname);
208 if (iter == mglist.end()) {
209 errorstream << "EmergeManager; mapgen " << mgname <<
210 " not registered" << std::endl;
214 MapgenFactory *mgfactory = iter->second;
215 return mgfactory->createMapgen(mgid, mgparams, this);
219 MapgenParams *EmergeManager::createMapgenParams(std::string mgname) {
220 std::map<std::string, MapgenFactory *>::const_iterator iter;
221 iter = mglist.find(mgname);
222 if (iter == mglist.end()) {
223 errorstream << "EmergeManager: mapgen " << mgname <<
224 " not registered" << std::endl;
228 MapgenFactory *mgfactory = iter->second;
229 return mgfactory->createMapgenParams();
233 MapgenParams *EmergeManager::getParamsFromSettings(Settings *settings) {
234 std::string mg_name = settings->get("mg_name");
235 MapgenParams *mgparams = createMapgenParams(mg_name);
237 mgparams->mg_name = mg_name;
238 mgparams->seed = settings->getU64(settings == g_settings ? "fixed_map_seed" : "seed");
239 mgparams->water_level = settings->getS16("water_level");
240 mgparams->chunksize = settings->getS16("chunksize");
241 mgparams->flags = settings->getFlagStr("mg_flags", flagdesc_mapgen);
243 if (!mgparams->readParams(settings)) {
251 void EmergeManager::setParamsToSettings(Settings *settings) {
252 settings->set("mg_name", params->mg_name);
253 settings->setU64("seed", params->seed);
254 settings->setS16("water_level", params->water_level);
255 settings->setS16("chunksize", params->chunksize);
256 settings->setFlagStr("mg_flags", params->flags, flagdesc_mapgen);
258 params->writeParams(settings);
262 void EmergeManager::registerMapgen(std::string mgname, MapgenFactory *mgfactory) {
263 mglist.insert(std::make_pair(mgname, mgfactory));
264 infostream << "EmergeManager: registered mapgen " << mgname << std::endl;
268 ////////////////////////////// Emerge Thread //////////////////////////////////
270 bool EmergeThread::popBlockEmerge(v3s16 *pos, u8 *flags) {
271 std::map<v3s16, BlockEmergeData *>::iterator iter;
272 JMutexAutoLock queuelock(emerge->queuemutex);
274 if (blockqueue.empty())
276 v3s16 p = blockqueue.front();
281 iter = emerge->blocks_enqueued.find(p);
282 if (iter == emerge->blocks_enqueued.end())
283 return false; //uh oh, queue and map out of sync!!
285 BlockEmergeData *bedata = iter->second;
286 *flags = bedata->flags;
288 emerge->peer_queue_count[bedata->peer_requested]--;
291 emerge->blocks_enqueued.erase(iter);
297 bool EmergeThread::getBlockOrStartGen(v3s16 p, MapBlock **b,
298 BlockMakeData *data, bool allow_gen) {
300 //envlock: usually takes <=1ms, sometimes 90ms or ~400ms to acquire
301 JMutexAutoLock envlock(m_server->m_env_mutex);
303 // Load sector if it isn't loaded
304 if (map->getSectorNoGenerateNoEx(p2d) == NULL)
305 map->loadSectorMeta(p2d);
307 // Attempt to load block
308 MapBlock *block = map->getBlockNoCreateNoEx(p);
309 if (!block || block->isDummy() || !block->isGenerated()) {
310 EMERGE_DBG_OUT("not in memory, attempting to load from disk");
311 block = map->loadBlock(p);
314 // If could not load and allowed to generate,
315 // start generation inside this same envlock
316 if (allow_gen && (block == NULL || !block->isGenerated())) {
317 EMERGE_DBG_OUT("generating");
319 return map->initBlockMake(data, p);
327 void *EmergeThread::Thread() {
329 log_register_thread("EmergeThread" + id);
330 DSTACK(__FUNCTION_NAME);
331 BEGIN_DEBUG_EXCEPTION_HANDLER
333 v3s16 last_tried_pos(-32768,-32768,-32768); // For error output
337 map = (ServerMap *)&(m_server->m_env->getMap());
338 emerge = m_server->m_emerge;
339 mapgen = emerge->mapgen[id];
340 enable_mapgen_debug_info = emerge->mapgen_debug_info;
344 if (!popBlockEmerge(&p, &flags)) {
350 if (blockpos_over_limit(p))
353 bool allow_generate = flags & BLOCK_EMERGE_ALLOWGEN;
354 EMERGE_DBG_OUT("p=" PP(p) " allow_generate=" << allow_generate);
357 Try to fetch block from memory or disk.
358 If not found and asked to generate, initialize generator.
361 MapBlock *block = NULL;
362 std::map<v3s16, MapBlock *> modified_blocks;
364 if (getBlockOrStartGen(p, &block, &data, allow_generate)) {
366 ScopeProfiler sp(g_profiler, "EmergeThread: Mapgen::makeChunk", SPT_AVG);
367 TimeTaker t("mapgen::make_block()");
369 mapgen->makeChunk(&data);
371 if (enable_mapgen_debug_info == false)
372 t.stop(true); // Hide output
376 //envlock: usually 0ms, but can take either 30 or 400ms to acquire
377 JMutexAutoLock envlock(m_server->m_env_mutex);
378 ScopeProfiler sp(g_profiler, "EmergeThread: after "
379 "Mapgen::makeChunk (envlock)", SPT_AVG);
381 map->finishBlockMake(&data, modified_blocks);
383 block = map->getBlockNoCreateNoEx(p);
386 Do some post-generate stuff
388 v3s16 minp = data.blockpos_min * MAP_BLOCKSIZE;
389 v3s16 maxp = data.blockpos_max * MAP_BLOCKSIZE +
390 v3s16(1,1,1) * (MAP_BLOCKSIZE - 1);
392 // Ignore map edit events, they will not need to be sent
393 // to anybody because the block hasn't been sent to anybody
394 MapEditEventAreaIgnorer
395 ign(&m_server->m_ignore_map_edit_events_area,
396 VoxelArea(minp, maxp));
397 { // takes about 90ms with -O1 on an e3-1230v2
398 scriptapi_environment_on_generated(m_server->m_lua,
399 minp, maxp, emerge->getBlockSeed(minp));
402 EMERGE_DBG_OUT("ended up with: " << analyze_block(block));
404 m_server->m_env->activateBlock(block, 0);
410 Set sent status of modified blocks on clients
413 // NOTE: Server's clients are also behind the connection mutex
414 //conlock: consistently takes 30-40ms to acquire
415 JMutexAutoLock lock(m_server->m_con_mutex);
416 // Add the originally fetched block to the modified list
418 modified_blocks[p] = block;
420 // Set the modified blocks unsent for all the clients
421 for (std::map<u16, RemoteClient*>::iterator
422 i = m_server->m_clients.begin();
423 i != m_server->m_clients.end(); ++i) {
424 RemoteClient *client = i->second;
425 if (modified_blocks.size() > 0) {
426 // Remove block from sent history
427 client->SetBlocksNotSent(modified_blocks);
431 catch (VersionMismatchException &e) {
432 std::ostringstream err;
433 err << "World data version mismatch in MapBlock "<<PP(last_tried_pos)<<std::endl;
434 err << "----"<<std::endl;
435 err << "\""<<e.what()<<"\""<<std::endl;
436 err << "See debug.txt."<<std::endl;
437 err << "World probably saved by a newer version of Minetest."<<std::endl;
438 m_server->setAsyncFatalError(err.str());
440 catch (SerializationError &e) {
441 std::ostringstream err;
442 err << "Invalid data in MapBlock "<<PP(last_tried_pos)<<std::endl;
443 err << "----"<<std::endl;
444 err << "\""<<e.what()<<"\""<<std::endl;
445 err << "See debug.txt."<<std::endl;
446 err << "You can ignore this using [ignore_world_load_errors = true]."<<std::endl;
447 m_server->setAsyncFatalError(err.str());
450 END_DEBUG_EXCEPTION_HANDLER(errorstream)
451 log_deregister_thread();