aboutsummaryrefslogtreecommitdiff
path: root/src/terminal_chat_console.cpp
blob: ac06285eb106478d4386e068ede30e6fec1d0bd9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
/*
Minetest
Copyright (C) 2015 est31 <MTest31@outlook.com>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "config.h"
#if USE_CURSES
#include "version.h"
#include "terminal_chat_console.h"
#include "porting.h"
#include "settings.h"
#include "util/numeric.h"
#include "util/string.h"

TerminalChatConsole g_term_console;

// include this last to avoid any conflicts
// (likes to set macros to common names, conflicting various stuff)
#if CURSES_HAVE_NCURSESW_NCURSES_H
#include <ncursesw/ncurses.h>
#elif CURSES_HAVE_NCURSESW_CURSES_H
#include <ncursesw/curses.h>
#elif CURSES_HAVE_CURSES_H
#include <curses.h>
#elif CURSES_HAVE_NCURSES_H
#include <ncurses.h>
#elif CURSES_HAVE_NCURSES_NCURSES_H
#include <ncurses/ncurses.h>
#elif CURSES_HAVE_NCURSES_CURSES_H
#include <ncurses/curses.h>
#endif

// Some functions to make drawing etc position independent
static bool reformat_backend(ChatBackend *backend, int rows, int cols)
{
	if (rows < 2)
		return false;
	backend->reformat(cols, rows - 2);
	return true;
}

static void move_for_backend(int row, int col)
{
	move(row + 1, col);
}

void TerminalChatConsole::initOfCurses()
{
	initscr();
	cbreak(); //raw();
	noecho();
	keypad(stdscr, TRUE);
	nodelay(stdscr, TRUE);
	timeout(100);

	// To make esc not delay up to one second. According to the internet,
	// this is the value vim uses, too.
	set_escdelay(25);

	getmaxyx(stdscr, m_rows, m_cols);
	m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
}

void TerminalChatConsole::deInitOfCurses()
{
	endwin();
}

void *TerminalChatConsole::run()
{
	BEGIN_DEBUG_EXCEPTION_HANDLER

	std::cout << "========================" << std::endl;
	std::cout << "Begin log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	// Make the loggers to stdout/stderr shut up.
	// Go over our own loggers instead.
	LogLevelMask err_mask = g_logger.removeOutput(&stderr_output);
	LogLevelMask out_mask = g_logger.removeOutput(&stdout_output);

	g_logger.addOutput(&m_log_output);

	// Inform the server of our nick
	m_chat_interface->command_queue.push_back(
		new ChatEventNick(CET_NICK_ADD, m_nick));

	{
		// Ensures that curses is deinitialized even on an exception being thrown
		CursesInitHelper helper(this);

		while (!stopRequested()) {

			int ch = getch();
			if (stopRequested())
				break;

			step(ch);
		}
	}

	if (m_kill_requested)
		*m_kill_requested = true;

	g_logger.removeOutput(&m_log_output);
	g_logger.addOutputMasked(&stderr_output, err_mask);
	g_logger.addOutputMasked(&stdout_output, out_mask);

	std::cout << "End log output over terminal"
		<< " (no stdout/stderr backlog during that)" << std::endl;
	std::cout << "========================" << std::endl;

	END_DEBUG_EXCEPTION_HANDLER

	return NULL;
}

void TerminalChatConsole::typeChatMessage(const std::wstring &msg)
{
	// Discard empty line
	if (msg.empty())
		return;

	// Send to server
	m_chat_interface->command_queue.push_back(
		new ChatEventChat(m_nick, msg));

	// Print if its a command (gets eaten by server otherwise)
	if (msg[0] == L'/') {
		m_chat_backend.addMessage(L"", (std::wstring)L"Issued command: " + msg);
	}
}

void TerminalChatConsole::handleInput(int ch, bool &complete_redraw_needed)
{
	// Helpful if you want to collect key codes that aren't documented
	/*if (ch != ERR) {
		m_chat_backend.addMessage(L"",
			(std::wstring)L"Pressed key " + utf8_to_wide(
			std::string(keyname(ch)) + " (code " + itos(ch) + ")"));
		complete_redraw_needed = true;
	}//*/

	// All the key codes below are compatible to xterm
	// Only add new ones if you have tried them there,
	// to ensure compatibility with not just xterm but the wide
	// range of terminals that are compatible to xterm.

	switch (ch) {
		case ERR: // no input
			break;
		case 27: // ESC
			// Toggle ESC mode
			m_esc_mode = !m_esc_mode;
			break;
		case KEY_PPAGE:
			m_chat_backend.scrollPageUp();
			complete_redraw_needed = true;
			break;
		case KEY_NPAGE:
			m_chat_backend.scrollPageDown();
			complete_redraw_needed = true;
			break;
		case KEY_ENTER:
		case '\r':
		case '\n': {
			std::wstring text = m_chat_backend.getPrompt().submit();
			typeChatMessage(text);
			break;
		}
		case KEY_UP:
			m_chat_backend.getPrompt().historyPrev();
			break;
		case KEY_DOWN:
			m_chat_backend.getPrompt().historyNext();
			break;
		case KEY_LEFT:
			// Left pressed
			// move character to the left
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 545:
			// Ctrl-Left pressed
			// move word to the left
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_RIGHT:
			// Right pressed
			// move character to the right
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 560:
			// Ctrl-Right pressed
			// move word to the right
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case KEY_HOME:
			// Home pressed
			// move to beginning of line
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_END:
			// End pressed
			// move to end of line
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_MOVE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_BACKSPACE:
		case '\b':
		case 127:
			// Backspace pressed
			// delete character to the left
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case KEY_DC:
			// Delete pressed
			// delete character to the right
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_CHARACTER);
			break;
		case 519:
			// Ctrl-Delete pressed
			// delete word to the right
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_WORD);
			break;
		case 21:
			// Ctrl-U pressed
			// kill line to left end
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_LEFT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case 11:
			// Ctrl-K pressed
			// kill line to right end
			m_chat_backend.getPrompt().cursorOperation(
				ChatPrompt::CURSOROP_DELETE,
				ChatPrompt::CURSOROP_DIR_RIGHT,
				ChatPrompt::CURSOROP_SCOPE_LINE);
			break;
		case KEY_TAB:
			// Tab pressed
			// Nick completion
			m_chat_backend.getPrompt().nickCompletion(m_nicks, false);
			break;
		default:
			// Add character to the prompt,
			// assuming UTF-8.
			if (IS_UTF8_MULTB_START(ch)) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait += UTF8_MULTB_START_LEN(ch) - 1;
			} else if (m_utf8_bytes_to_wait != 0) {
				m_pending_utf8_bytes.append(1, (char)ch);
				m_utf8_bytes_to_wait--;
				if (m_utf8_bytes_to_wait == 0) {
					std::wstring w = utf8_to_wide(m_pending_utf8_bytes);
					m_pending_utf8_bytes = "";
					// hopefully only one char in the wstring...
					for (size_t i = 0; i < w.size(); i++) {
						m_chat_backend.getPrompt().input(w.c_str()[i]);
					}
				}
			} else if (IS_ASCII_PRINTABLE_CHAR(ch)) {
				m_chat_backend.getPrompt().input(ch);
			} else {
				// Silently ignore characters we don't handle

				//warningstream << "Pressed invalid character '"
				//	<< keyname(ch) << "' (code " << itos(ch) << ")" << std::endl;
			}
			break;
	}
}

void TerminalChatConsole::step(int ch)
{
	bool complete_redraw_needed = false;

	// empty queues
	while (!m_chat_interface->outgoing_queue.empty()) {
		ChatEvent *evt = m_chat_interface->outgoing_queue.pop_frontNoEx();
		switch (evt->type) {
			case CET_NICK_REMOVE:
				m_nicks.remove(((ChatEventNick *)evt)->nick);
				break;
			case CET_NICK_ADD:
				m_nicks.push_back(((ChatEventNick *)evt)->nick);
				break;
			case CET_CHAT:
				complete_redraw_needed = true;
				// This is only used for direct replies from commands
				// or for lua's print() functionality
				m_chat_backend.addMessage(L"", ((ChatEventChat *)evt)->evt_msg);
				break;
			case CET_TIME_INFO:
				ChatEventTimeInfo *tevt = (ChatEventTimeInfo *)evt;
				m_game_time = tevt->game_time;
				m_time_of_day = tevt->time;
		};
		delete evt;
	}
	while (!m_log_output.queue.empty()) {
		complete_redraw_needed = true;
		std::pair<LogLevel, std::string> p = m_log_output.queue.pop_frontNoEx();
		if (p.first > m_log_level)
			continue;

		m_chat_backend.addMessage(
			utf8_to_wide(Logger::getLevelLabel(p.first)),
			utf8_to_wide(p.second));
	}

	// handle input
	if (!m_esc_mode) {
		handleInput(ch, complete_redraw_needed);
	} else {
		switch (ch) {
			case ERR: // no input
				break;
			case 27: // ESC
				// Toggle ESC mode
				m_esc_mode = !m_esc_mode;
				break;
			case 'L':
				m_log_level--;
				m_log_level = MYMAX(m_log_level, LL_NONE + 1); // LL_NONE isn't accessible
				break;
			case 'l':
				m_log_level++;
				m_log_level = MYMIN(m_log_level, LL_MAX - 1);
				break;
		}
	}

	// was there a resize?
	int xn, yn;
	getmaxyx(stdscr, yn, xn);
	if (xn != m_cols || yn != m_rows) {
		m_cols = xn;
		m_rows = yn;
		m_can_draw_text = reformat_backend(&m_chat_backend, m_rows, m_cols);
		complete_redraw_needed = true;
	}

	// draw title
	move(0, 0);
	clrtoeol();
	addstr(PROJECT_NAME_C);
	addstr(" ");
	addstr(g_version_hash);

	u32 minutes = m_time_of_day % 1000;
	u32 hours = m_time_of_day / 1000;
	minutes = (float)minutes / 1000 * 60;

	if (m_game_time)
		printw(" | Game %d Time of day %02d:%02d ",
			m_game_time, hours, minutes);

	// draw text
	if (complete_redraw_needed && m_can_draw_text)
		draw_text();

	// draw prompt
	if (!m_esc_mode) {
		// normal prompt
		ChatPrompt& prompt = m_chat_backend.getPrompt();
		std::string prompt_text = wide_to_utf8(prompt.getVisiblePortion());
		move(m_rows - 1, 0);
		clrtoeol();
		addstr(prompt_text.c_str());
		// Draw cursor
		s32 cursor_pos = prompt.getVisibleCursorPosition();
		if (cursor_pos >= 0) {
			move(m_rows - 1, cursor_pos);
		}
	} else {
		// esc prompt
		move(m_rows - 1, 0);
		clrtoeol();
		printw("[ESC] Toggle ESC mode |"
			" [CTRL+C] Shut down |"
			" (L) in-, (l) decrease loglevel %s",
			Logger::getLevelLabel((LogLevel) m_log_level).c_str());
	}

	refresh();
}

void TerminalChatConsole::draw_text()
{
	ChatBuffer& buf = m_chat_backend.getConsoleBuffer();
	for (u32 row = 0; row < buf.getRows(); row++) {
		move_for_backend(row, 0);
		clrtoeol();
		const ChatFormattedLine& line = buf.getFormattedLine(row);
		if (line.fragments.empty())
			continue;
		for (u32 i = 0; i < line.fragments.size(); ++i) {
			const ChatFormattedFragment& fragment = line.fragments[i];
			addstr(wide_to_utf8(fragment.text).c_str());
		}
	}
}

void TerminalChatConsole::stopAndWaitforThread()
{
	clearKillStatus();
	stop();
	wait();
}

#endif
pt">= 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++) { float noiseval = noise->result[index++]; if (noiseval < nthresh) continue; int height = max_height * (1. / pr.range(1, 3)); int y0 = y_start + np->scale * noiseval; //pr.range(1, 3) - 1; int y1 = y0 + height; for (int y = y0; y != y1; y++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; for (size_t ii = 0; ii < wherein.size(); ii++) if (vm->m_data[i].getContent() == wherein[ii]) vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// Decoration *createDecoration(DecorationType type) { switch (type) { case DECO_SIMPLE: return new DecoSimple; case DECO_SCHEMATIC: return new DecoSchematic; //case DECO_LSYSTEM: // return new DecoLSystem; default: return NULL; } } Decoration::Decoration() { mapseed = 0; np = NULL; fill_ratio = 0; sidelen = 1; } Decoration::~Decoration() { delete np; } void Decoration::resolveNodeNames(INodeDefManager *ndef) { this->ndef = ndef; if (c_place_on == CONTENT_IGNORE) c_place_on = ndef->getId(place_on_name); } void Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { PseudoRandom ps(blockseed + 53); int carea_size = nmax.X - nmin.X + 1; // Divide area into parts if (carea_size % sidelen) { errorstream << "Decoration::placeDeco: chunk size is not divisible by " "sidelen; setting sidelen to " << carea_size << std::endl; sidelen = carea_size; } s16 divlen = carea_size / sidelen; int area = sidelen * sidelen; for (s16 z0 = 0; z0 < divlen; z0++) for (s16 x0 = 0; x0 < divlen; x0++) { v2s16 p2d_center( // Center position of part of division nmin.X + sidelen / 2 + sidelen * x0, nmin.Z + sidelen / 2 + sidelen * z0 ); v2s16 p2d_min( // Minimum edge of part of division nmin.X + sidelen * x0, nmin.Z + sidelen * z0 ); v2s16 p2d_max( // Maximum edge of part of division nmin.X + sidelen + sidelen * x0 - 1, nmin.Z + sidelen + sidelen * z0 - 1 ); // Amount of decorations float nval = np ? NoisePerlin2D(np, p2d_center.X, p2d_center.Y, mapseed) : fill_ratio; u32 deco_count = area * MYMAX(nval, 0.f); for (u32 i = 0; i < deco_count; i++) { s16 x = ps.range(p2d_min.X, p2d_max.X); s16 z = ps.range(p2d_min.Y, p2d_max.Y); int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X); s16 y = mg->heightmap ? mg->heightmap[mapindex] : mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y); if (y < nmin.Y || y > nmax.Y) continue; int height = getHeight(); int max_y = nmax.Y;// + MAP_BLOCKSIZE - 1; if (y + 1 + height > max_y) { continue; #if 0 printf("Decoration at (%d %d %d) cut off\n", x, y, z); //add to queue JMutexAutoLock cutofflock(cutoff_mutex); cutoffs.push_back(CutoffData(x, y, z, height)); #endif } if (mg->biomemap) { std::set<u8>::iterator iter; if (biomes.size()) { iter = biomes.find(mg->biomemap[mapindex]); if (iter == biomes.end()) continue; } } generate(mg, &ps, max_y, v3s16(x, y, z)); } } } #if 0 void Decoration::placeCutoffs(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) { PseudoRandom pr(blockseed + 53); std::vector<CutoffData> handled_cutoffs; // Copy over the cutoffs we're interested in so we don't needlessly hold a lock { JMutexAutoLock cutofflock(cutoff_mutex); for (std::list<CutoffData>::iterator i = cutoffs.begin(); i != cutoffs.end(); ++i) { CutoffData cutoff = *i; v3s16 p = cutoff.p; s16 height = cutoff.height; if (p.X < nmin.X || p.X > nmax.X || p.Z < nmin.Z || p.Z > nmax.Z) continue; if (p.Y + height < nmin.Y || p.Y > nmax.Y) continue; handled_cutoffs.push_back(cutoff); } } // Generate the cutoffs for (size_t i = 0; i != handled_cutoffs.size(); i++) { v3s16 p = handled_cutoffs[i].p; s16 height = handled_cutoffs[i].height; if (p.Y + height > nmax.Y) { //printf("Decoration at (%d %d %d) cut off again!\n", p.X, p.Y, p.Z); cuttoffs.push_back(v3s16(p.X, p.Y, p.Z)); } generate(mg, &pr, nmax.Y, nmin.Y - p.Y, v3s16(p.X, nmin.Y, p.Z)); } // Remove cutoffs that were handled from the cutoff list { JMutexAutoLock cutofflock(cutoff_mutex); for (std::list<CutoffData>::iterator i = cutoffs.begin(); i != cutoffs.end(); ++i) { for (size_t j = 0; j != handled_cutoffs.size(); j++) { CutoffData coff = *i; if (coff.p == handled_cutoffs[j].p) i = cutoffs.erase(i); } } } } #endif /////////////////////////////////////////////////////////////////////////////// void DecoSimple::resolveNodeNames(INodeDefManager *ndef) { Decoration::resolveNodeNames(ndef); if (c_deco == CONTENT_IGNORE && !decolist_names.size()) { c_deco = ndef->getId(deco_name); if (c_deco == CONTENT_IGNORE) { errorstream << "DecoSimple::resolveNodeNames: decoration node '" << deco_name << "' not defined" << std::endl; c_deco = CONTENT_AIR; } } if (c_spawnby == CONTENT_IGNORE) { c_spawnby = ndef->getId(spawnby_name); if (c_spawnby == CONTENT_IGNORE) { errorstream << "DecoSimple::resolveNodeNames: spawnby node '" << spawnby_name << "' not defined" << std::endl; nspawnby = -1; c_spawnby = CONTENT_AIR; } } if (c_decolist.size()) return; for (size_t i = 0; i != decolist_names.size(); i++) { content_t c = ndef->getId(decolist_names[i]); if (c == CONTENT_IGNORE) { errorstream << "DecoSimple::resolveNodeNames: decolist node '" << decolist_names[i] << "' not defined" << std::endl; c = CONTENT_AIR; } c_decolist.push_back(c); } } void DecoSimple::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) { ManualMapVoxelManipulator *vm = mg->vm; u32 vi = vm->m_area.index(p); if (vm->m_data[vi].getContent() != c_place_on && c_place_on != CONTENT_IGNORE) return; if (nspawnby != -1) { int nneighs = 0; v3s16 dirs[8] = { // a Moore neighborhood v3s16( 0, 0, 1), v3s16( 0, 0, -1), v3s16( 1, 0, 0), v3s16(-1, 0, 0), v3s16( 1, 0, 1), v3s16(-1, 0, 1), v3s16(-1, 0, -1), v3s16( 1, 0, -1) }; for (int i = 0; i != 8; i++) { u32 index = vm->m_area.index(p + dirs[i]); if (vm->m_area.contains(index) && vm->m_data[index].getContent() == c_spawnby) nneighs++; } if (nneighs < nspawnby) return; } size_t ndecos = c_decolist.size(); content_t c_place = ndecos ? c_decolist[pr->range(0, ndecos - 1)] : c_deco; s16 height = (deco_height_max > 0) ? pr->range(deco_height, deco_height_max) : deco_height; height = MYMIN(height, max_y - p.Y); v3s16 em = vm->m_area.getExtent(); for (int i = 0; i < height; i++) { vm->m_area.add_y(em, vi, 1); content_t c = vm->m_data[vi].getContent(); if (c != CONTENT_AIR && c != CONTENT_IGNORE) break; vm->m_data[vi] = MapNode(c_place); } } int DecoSimple::getHeight() { return (deco_height_max > 0) ? deco_height_max : deco_height; } std::string DecoSimple::getName() { return deco_name; } /////////////////////////////////////////////////////////////////////////////// DecoSchematic::DecoSchematic() { node_names = NULL; schematic = NULL; flags = 0; size = v3s16(0, 0, 0); } DecoSchematic::~DecoSchematic() { delete node_names; delete []schematic; } void DecoSchematic::resolveNodeNames(INodeDefManager *ndef) { Decoration::resolveNodeNames(ndef); if (filename.empty()) return; if (!node_names) { errorstream << "DecoSchematic::resolveNodeNames: node name list was " "not created" << std::endl; return; } for (size_t i = 0; i != node_names->size(); i++) { std::string name = node_names->at(i); std::map<std::string, std::string>::iterator it; it = replacements.find(name); if (it != replacements.end()) name = it->second; content_t c = ndef->getId(name); if (c == CONTENT_IGNORE) { errorstream << "DecoSchematic::resolveNodeNames: node '" << name << "' not defined" << std::endl; c = CONTENT_AIR; } c_nodes.push_back(c); } for (int i = 0; i != size.X * size.Y * size.Z; i++) schematic[i].setContent(c_nodes[schematic[i].getContent()]); delete node_names; node_names = NULL; } void DecoSchematic::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) { ManualMapVoxelManipulator *vm = mg->vm; if (flags & DECO_PLACE_CENTER_X) p.X -= (size.X + 1) / 2; if (flags & DECO_PLACE_CENTER_Y) p.Y -= (size.Y + 1) / 2; if (flags & DECO_PLACE_CENTER_Z) p.Z -= (size.Z + 1) / 2; u32 vi = vm->m_area.index(p); if (vm->m_data[vi].getContent() != c_place_on && c_place_on != CONTENT_IGNORE) return; Rotation rot = (rotation == ROTATE_RAND) ? (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation; blitToVManip(p, vm, rot, false); } int DecoSchematic::getHeight() { return size.Y; } std::string DecoSchematic::getName() { return filename; } void DecoSchematic::blitToVManip(v3s16 p, ManualMapVoxelManipulator *vm, Rotation rot, bool force_placement) { int xstride = 1; int ystride = size.X; int zstride = size.X * size.Y; s16 sx = size.X; s16 sy = size.Y; s16 sz = size.Z; int i_start, i_step_x, i_step_z; switch (rot) { case ROTATE_90: i_start = sx - 1; i_step_x = zstride; i_step_z = -xstride; SWAP(s16, sx, sz); break; case ROTATE_180: i_start = zstride * (sz - 1) + sx - 1; i_step_x = -xstride; i_step_z = -zstride; break; case ROTATE_270: i_start = zstride * (sz - 1); i_step_x = -zstride; i_step_z = xstride; SWAP(s16, sx, sz); break; default: i_start = 0; i_step_x = xstride; i_step_z = zstride; } for (s16 z = 0; z != sz; z++) for (s16 y = 0; y != sy; y++) { u32 i = z * i_step_z + y * ystride + i_start; for (s16 x = 0; x != sx; x++, i += i_step_x) { u32 vi = vm->m_area.index(p.X + x, p.Y + y, p.Z + z); if (!vm->m_area.contains(vi)) continue; if (schematic[i].getContent() == CONTENT_IGNORE) continue; if (schematic[i].param1 == MTSCHEM_PROB_NEVER) continue; if (!force_placement) { content_t c = vm->m_data[vi].getContent(); if (c != CONTENT_AIR && c != CONTENT_IGNORE) continue; } if (schematic[i].param1 != MTSCHEM_PROB_ALWAYS && myrand_range(1, 255) > schematic[i].param1) continue; vm->m_data[vi] = schematic[i]; vm->m_data[vi].param1 = 0; if (rot) vm->m_data[vi].rotateAlongYAxis(ndef, rot); } } } void DecoSchematic::placeStructure(Map *map, v3s16 p) { assert(schematic != NULL); ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map); Rotation rot = (rotation == ROTATE_RAND) ? (Rotation)myrand_range(ROTATE_0, ROTATE_270) : rotation; v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ? v3s16(size.Z, size.Y, size.X) : size; if (flags & DECO_PLACE_CENTER_X) p.X -= (s.X + 1) / 2; if (flags & DECO_PLACE_CENTER_Y) p.Y -= (s.Y + 1) / 2; if (flags & DECO_PLACE_CENTER_Z) p.Z -= (s.Z + 1) / 2; v3s16 bp1 = getNodeBlockPos(p); v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1)); vm->initialEmerge(bp1, bp2); blitToVManip(p, vm, rot, true); std::map<v3s16, MapBlock *> lighting_modified_blocks; std::map<v3s16, MapBlock *> modified_blocks; vm->blitBackAll(&modified_blocks); // TODO: Optimize this by using Mapgen::calcLighting() instead lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end()); map->updateLighting(lighting_modified_blocks, modified_blocks); MapEditEvent event; event.type = MEET_OTHER; for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin(); it != modified_blocks.end(); ++it) event.modified_blocks.insert(it->first); map->dispatchEvent(&event); } bool DecoSchematic::loadSchematicFile() { content_t cignore = CONTENT_IGNORE; bool have_cignore = false; std::ifstream is(filename.c_str(), std::ios_base::binary); u32 signature = readU32(is); if (signature != MTSCHEM_FILE_SIGNATURE) { errorstream << "loadSchematicFile: invalid schematic " "file" << std::endl; return false; } u16 version = readU16(is); if (version > 2) { errorstream << "loadSchematicFile: unsupported schematic " "file version" << std::endl; return false; } size = readV3S16(is); int nodecount = size.X * size.Y * size.Z; u16 nidmapcount = readU16(is); node_names = new std::vector<std::string>; for (int i = 0; i != nidmapcount; i++) { std::string name = deSerializeString(is); if (name == "ignore") { name = "air"; cignore = i; have_cignore = true; } node_names->push_back(name); } delete schematic; schematic = new MapNode[nodecount]; MapNode::deSerializeBulk(is, SER_FMT_VER_HIGHEST_READ, schematic, nodecount, 2, 2, true); if (version == 1) { // fix up the probability values for (int i = 0; i != nodecount; i++) { if (schematic[i].param1 == 0) schematic[i].param1 = MTSCHEM_PROB_ALWAYS; if (have_cignore && schematic[i].getContent() == cignore) schematic[i].param1 = MTSCHEM_PROB_NEVER; } } return true; } /* Minetest Schematic File Format All values are stored in big-endian byte order. [u32] signature: 'MTSM' [u16] version: 2 [u16] size X [u16] size Y [u16] size Z [Name-ID table] Name ID Mapping Table [u16] name-id count For each name-id mapping: [u16] name length [u8[]] name ZLib deflated { For each node in schematic: (for z, y, x) [u16] content For each node in schematic: [u8] probability of occurance (param1) For each node in schematic: [u8] param2 } Version changes: 1 - Initial version 2 - Fixed messy never/always place; 0 probability is now never, 0xFF is always */ void DecoSchematic::saveSchematicFile(INodeDefManager *ndef) { std::ostringstream ss(std::ios_base::binary); writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature writeU16(ss, 2); // version writeV3S16(ss, size); // schematic size std::vector<content_t> usednodes; int nodecount = size.X * size.Y * size.Z; build_nnlist_and_update_ids(schematic, nodecount, &usednodes); u16 numids = usednodes.size(); writeU16(ss, numids); // name count for (int i = 0; i != numids; i++) ss << serializeString(ndef->get(usednodes[i]).name); // node names // compressed bulk node data MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schematic, nodecount, 2, 2, true); fs::safeWriteToFile(filename, ss.str()); } void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount, std::vector<content_t> *usednodes) { std::map<content_t, content_t> nodeidmap; content_t numids = 0; for (u32 i = 0; i != nodecount; i++) { content_t id; content_t c = nodes[i].getContent(); std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c); if (it == nodeidmap.end()) { id = numids; numids++; usednodes->push_back(c); nodeidmap.insert(std::make_pair(c, id)); } else { id = it->second; } nodes[i].setContent(id); } } bool DecoSchematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) { ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map); v3s16 bp1 = getNodeBlockPos(p1); v3s16 bp2 = getNodeBlockPos(p2); vm->initialEmerge(bp1, bp2); size = p2 - p1 + 1; schematic = new MapNode[size.X * size.Y * size.Z]; u32 i = 0; for (s16 z = p1.Z; z <= p2.Z; z++) for (s16 y = p1.Y; y <= p2.Y; y++) { u32 vi = vm->m_area.index(p1.X, y, z); for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) { schematic[i] = vm->m_data[vi]; schematic[i].param1 = MTSCHEM_PROB_ALWAYS; } } delete vm; return true; } void DecoSchematic::applyProbabilities(std::vector<std::pair<v3s16, u8> > *plist, v3s16 p0) { for (size_t i = 0; i != plist->size(); i++) { v3s16 p = (*plist)[i].first - p0; int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X; if (index < size.Z * size.Y * size.X) { u8 prob = (*plist)[i].second; schematic[index].param1 = prob; // trim unnecessary node names from schematic if (prob == MTSCHEM_PROB_NEVER) schematic[index].setContent(CONTENT_AIR); } } } /////////////////////////////////////////////////////////////////////////////// Mapgen::Mapgen() { seed = 0; water_level = 0; generating = false; id = -1; vm = NULL; ndef = NULL; heightmap = NULL; biomemap = NULL; } // Returns Y one under area minimum if not found s16 Mapgen::findGroundLevelFull(v2s16 p2d) { v3s16 em = vm->m_area.getExtent(); s16 y_nodes_max = vm->m_area.MaxEdge.Y; s16 y_nodes_min = vm->m_area.MinEdge.Y; u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y); s16 y; for (y = y_nodes_max; y >= y_nodes_min; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).walkable) break; vm->m_area.add_y(em, i, -1); } return (y >= y_nodes_min) ? y : y_nodes_min - 1; } s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) { v3s16 em = vm->m_area.getExtent(); u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y); s16 y; for (y = ymax; y >= ymin; y--) { MapNode &n = vm->m_data[i]; if (ndef->get(n).walkable) break; vm->m_area.add_y(em, i, -1); } return y; } void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) { if (!heightmap) return; //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO); int index = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 x = nmin.X; x <= nmax.X; x++, index++) { s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y); // if the values found are out of range, trust the old heightmap if (y == nmax.Y && heightmap[index] > nmax.Y) continue; if (y == nmin.Y - 1 && heightmap[index] < nmin.Y) continue; heightmap[index] = y; } } //printf("updateHeightmap: %dus\n", t.stop()); } void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax) { bool isliquid, wasliquid, rare; v3s16 em = vm->m_area.getExtent(); rare = g_settings->getBool("liquid_finite"); int rarecnt = 0; for (s16 z = nmin.Z; z <= nmax.Z; z++) { for (s16 x = nmin.X; x <= nmax.X; x++) { wasliquid = true; u32 i = vm->m_area.index(x, nmax.Y, z); for (s16 y = nmax.Y; y >= nmin.Y; y--) { isliquid = ndef->get(vm->m_data[i]).isLiquid(); // there was a change between liquid and nonliquid, add to queue. no need to add every with liquid_finite if (isliquid != wasliquid && (!rare || !(rarecnt++ % 36))) trans_liquid->push_back(v3s16(x, y, z)); wasliquid = isliquid; vm->m_area.add_y(em, i, -1); } } } } void Mapgen::setLighting(v3s16 nmin, v3s16 nmax, u8 light) { ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG); VoxelArea a(nmin, nmax); for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { u32 i = vm->m_area.index(a.MinEdge.X, y, z); for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) vm->m_data[i].param1 = light; } } } void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light) { if (light <= 1 || !a.contains(p)) return; u32 vi = vm->m_area.index(p); MapNode &nn = vm->m_data[vi]; light--; // should probably compare masked, but doesn't seem to make a difference if (light <= nn.param1 || !ndef->get(nn).light_propagates) return; nn.param1 = light; lightSpread(a, p + v3s16(0, 0, 1), light); lightSpread(a, p + v3s16(0, 1, 0), light); lightSpread(a, p + v3s16(1, 0, 0), light); lightSpread(a, p - v3s16(0, 0, 1), light); lightSpread(a, p - v3s16(0, 1, 0), light); lightSpread(a, p - v3s16(1, 0, 0), light); } void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax) { VoxelArea a(nmin, nmax); bool block_is_underground = (water_level >= nmax.Y); ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG); //TimeTaker t("updateLighting"); // first, send vertical rays of sunshine downward v3s16 em = vm->m_area.getExtent(); for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) { // see if we can get a light value from the overtop u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z); if (vm->m_data[i].getContent() == CONTENT_IGNORE) { if (block_is_underground) continue; } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN) { continue; } vm->m_area.add_y(em, i, -1); for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) { MapNode &n = vm->m_data[i]; if (!ndef->get(n).sunlight_propagates) break; n.param1 = LIGHT_SUN; vm->m_area.add_y(em, i, -1); } } } // now spread the sunlight and light up any sources for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) { for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) { u32 i = vm->m_area.index(a.MinEdge.X, y, z); for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) { MapNode &n = vm->m_data[i]; if (n.getContent() == CONTENT_IGNORE || !ndef->get(n).light_propagates) continue; u8 light_produced = ndef->get(n).light_source & 0x0F; if (light_produced) n.param1 = light_produced; u8 light = n.param1 & 0x0F; if (light) { lightSpread(a, v3s16(x, y, z + 1), light - 1); lightSpread(a, v3s16(x, y + 1, z ), light - 1); lightSpread(a, v3s16(x + 1, y, z ), light - 1); lightSpread(a, v3s16(x, y, z - 1), light - 1); lightSpread(a, v3s16(x, y - 1, z ), light - 1); lightSpread(a, v3s16(x - 1, y, z ), light - 1); } } } } //printf("updateLighting: %dms\n", t.stop()); } void Mapgen::calcLightingOld(v3s16 nmin, v3s16 nmax) { enum LightBank banks[2] = {LIGHTBANK_DAY, LIGHTBANK_NIGHT}; VoxelArea a(nmin, nmax); bool block_is_underground = (water_level > nmax.Y); bool sunlight = !block_is_underground; ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG); for (int i = 0; i < 2; i++) { enum LightBank bank = banks[i]; std::set<v3s16> light_sources; std::map<v3s16, u8> unlight_from; voxalgo::clearLightAndCollectSources(*vm, a, bank, ndef, light_sources, unlight_from); voxalgo::propagateSunlight(*vm, a, sunlight, light_sources, ndef); vm->unspreadLight(bank, unlight_from, light_sources, ndef); vm->spreadLight(bank, light_sources, ndef); } } //////////////////////// Mapgen V6 parameter read/write bool MapgenV6Params::readParams(Settings *settings) { freq_desert = settings->getFloat("mgv6_freq_desert"); freq_beach = settings->getFloat("mgv6_freq_beach"); bool success = settings->getNoiseParams("mgv6_np_terrain_base", np_terrain_base) && settings->getNoiseParams("mgv6_np_terrain_higher", np_terrain_higher) && settings->getNoiseParams("mgv6_np_steepness", np_steepness) && settings->getNoiseParams("mgv6_np_height_select", np_height_select) && settings->getNoiseParams("mgv6_np_mud", np_mud) && settings->getNoiseParams("mgv6_np_beach", np_beach) && settings->getNoiseParams("mgv6_np_biome", np_biome) && settings->getNoiseParams("mgv6_np_cave", np_cave) && settings->getNoiseParams("mgv6_np_humidity", np_humidity) && settings->getNoiseParams("mgv6_np_trees", np_trees) && settings->getNoiseParams("mgv6_np_apple_trees", np_apple_trees); return success; } void MapgenV6Params::writeParams(Settings *settings) { settings->setFloat("mgv6_freq_desert", freq_desert); settings->setFloat("mgv6_freq_beach", freq_beach); settings->setNoiseParams("mgv6_np_terrain_base", np_terrain_base); settings->setNoiseParams("mgv6_np_terrain_higher", np_terrain_higher); settings->setNoiseParams("mgv6_np_steepness", np_steepness); settings->setNoiseParams("mgv6_np_height_select", np_height_select); settings->setNoiseParams("mgv6_np_mud", np_mud); settings->setNoiseParams("mgv6_np_beach", np_beach); settings->setNoiseParams("mgv6_np_biome", np_biome); settings->setNoiseParams("mgv6_np_cave", np_cave); settings->setNoiseParams("mgv6_np_humidity", np_humidity); settings->setNoiseParams("mgv6_np_trees", np_trees); settings->setNoiseParams("mgv6_np_apple_trees", np_apple_trees); } bool MapgenV7Params::readParams(Settings *settings) { bool success = settings->getNoiseParams("mgv7_np_terrain_base", np_terrain_base) && settings->getNoiseParams("mgv7_np_terrain_alt", np_terrain_alt) && settings->getNoiseParams("mgv7_np_terrain_persist", np_terrain_persist) && settings->getNoiseParams("mgv7_np_height_select", np_height_select) && settings->getNoiseParams("mgv7_np_filler_depth", np_filler_depth) && settings->getNoiseParams("mgv7_np_mount_height", np_mount_height) && settings->getNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater) && settings->getNoiseParams("mgv7_np_mountain", np_mountain) && settings->getNoiseParams("mgv7_np_ridge", np_ridge); return success; } void MapgenV7Params::writeParams(Settings *settings) { settings->setNoiseParams("mgv7_np_terrain_base", np_terrain_base); settings->setNoiseParams("mgv7_np_terrain_alt", np_terrain_alt); settings->setNoiseParams("mgv7_np_terrain_persist", np_terrain_persist); settings->setNoiseParams("mgv7_np_height_select", np_height_select); settings->setNoiseParams("mgv7_np_filler_depth", np_filler_depth); settings->setNoiseParams("mgv7_np_mount_height", np_mount_height); settings->setNoiseParams("mgv7_np_ridge_uwater", np_ridge_uwater); settings->setNoiseParams("mgv7_np_mountain", np_mountain); settings->setNoiseParams("mgv7_np_ridge", np_ridge); }