summaryrefslogtreecommitdiff
path: root/src/util/thread.h
blob: 73e9beb806f44d8effc6dd8e3a3bec3f82adf23f (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
/*
Minetest
Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.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.
*/

#pragma once

#include "irrlichttypes.h"
#include "threading/thread.h"
#include "threading/mutex_auto_lock.h"
#include "porting.h"
#include "log.h"
#include "container.h"

template<typename T>
class MutexedVariable
{
public:
	MutexedVariable(const T &value):
		m_value(value)
	{}

	T get()
	{
		MutexAutoLock lock(m_mutex);
		return m_value;
	}

	void set(const T &value)
	{
		MutexAutoLock lock(m_mutex);
		m_value = value;
	}

	// You pretty surely want to grab the lock when accessing this
	T m_value;
private:
	std::mutex m_mutex;
};

/*
	A single worker thread - multiple client threads queue framework.
*/
template<typename Key, typename T, typename Caller, typename CallerData>
class GetResult {
public:
	Key key;
	T item;
	std::pair<Caller, CallerData> caller;
};

template<typename Key, typename T, typename Caller, typename CallerData>
class ResultQueue : public MutexedQueue<GetResult<Key, T, Caller, CallerData> > {
};

template<typename Caller, typename Data, typename Key, typename T>
class CallerInfo {
public:
	Caller caller;
	Data data;
	ResultQueue<Key, T, Caller, Data> *dest;
};

template<typename Key, typename T, typename Caller, typename CallerData>
class GetRequest {
public:
	GetRequest() = default;
	~GetRequest() = default;

	GetRequest(const Key &a_key): key(a_key)
	{
	}

	Key key;
	std::list<CallerInfo<Caller, CallerData, Key, T> > callers;
};

/**
 * Notes for RequestQueue usage
 * @param Key unique key to identify a request for a specific resource
 * @param T ?
 * @param Caller unique id of calling thread
 * @param CallerData data passed back to caller
 */
template<typename Key, typename T, typename Caller, typename CallerData>
class RequestQueue {
public:
	bool empty()
	{
		return m_queue.empty();
	}

	void add(const Key &key, Caller caller, CallerData callerdata,
		ResultQueue<Key, T, Caller, CallerData> *dest)
	{
		typename std::deque<GetRequest<Key, T, Caller, CallerData> >::iterator i;
		typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator j;

		{
			MutexAutoLock lock(m_queue.getMutex());

			/*
				If the caller is already on the list, only update CallerData
			*/
			for (i = m_queue.getQueue().begin(); i != m_queue.getQueue().end(); ++i) {
				GetRequest<Key, T, Caller, CallerData> &request = *i;
				if (request.key != key)
					continue;

				for (j = request.callers.begin(); j != request.callers.end(); ++j) {
					CallerInfo<Caller, CallerData, Key, T> &ca = *j;
					if (ca.caller == caller) {
						ca.data = callerdata;
						return;
					}
				}

				CallerInfo<Caller, CallerData, Key, T> ca;
				ca.caller = caller;
				ca.data = callerdata;
				ca.dest = dest;
				request.callers.push_back(ca);
				return;
			}
		}

		/*
			Else add a new request to the queue
		*/

		GetRequest<Key, T, Caller, CallerData> request;
		request.key = key;
		CallerInfo<Caller, CallerData, Key, T> ca;
		ca.caller = caller;
		ca.data = callerdata;
		ca.dest = dest;
		request.callers.push_back(ca);

		m_queue.push_back(request);
	}

	GetRequest<Key, T, Caller, CallerData> pop(unsigned int timeout_ms)
	{
		return m_queue.pop_front(timeout_ms);
	}

	GetRequest<Key, T, Caller, CallerData> pop()
	{
		return m_queue.pop_frontNoEx();
	}

	void pushResult(GetRequest<Key, T, Caller, CallerData> req, T res)
	{
		for (typename std::list<CallerInfo<Caller, CallerData, Key, T> >::iterator
				i = req.callers.begin();
				i != req.callers.end(); ++i) {
			CallerInfo<Caller, CallerData, Key, T> &ca = *i;

			GetResult<Key,T,Caller,CallerData> result;

			result.key = req.key;
			result.item = res;
			result.caller.first = ca.caller;
			result.caller.second = ca.data;

			ca.dest->push_back(result);
		}
	}

private:
	MutexedQueue<GetRequest<Key, T, Caller, CallerData> > m_queue;
};

class UpdateThread : public Thread
{
public:
	UpdateThread(const std::string &name) : Thread(name + "Update") {}
	~UpdateThread() = default;

	void deferUpdate() { m_update_sem.post(); }

	void stop()
	{
		Thread::stop();

		// give us a nudge
		m_update_sem.post();
	}

	void *run()
	{
		BEGIN_DEBUG_EXCEPTION_HANDLER

		while (!stopRequested()) {
			m_update_sem.wait();
			// Set semaphore to 0
			while (m_update_sem.wait(0));

			if (stopRequested()) break;

			doUpdate();
		}

		END_DEBUG_EXCEPTION_HANDLER

		return NULL;
	}

protected:
	virtual void doUpdate() = 0;

private:
	Semaphore m_update_sem;
};
1) return 0; nmin.Y = actual_ymin; nmax.Y = actual_ymax; generate(mg->vm, mg->seed, blockseed, nmin, nmax, mg->biomemap); return 1; } void Ore::cloneTo(Ore *def) const { ObjDef::cloneTo(def); NodeResolver::cloneTo(def); def->c_ore = c_ore; def->c_wherein = c_wherein; def->clust_scarcity = clust_scarcity; def->clust_num_ores = clust_num_ores; def->clust_size = clust_size; def->y_min = y_min; def->y_max = y_max; def->ore_param2 = ore_param2; def->flags = flags; def->nthresh = nthresh; def->np = np; def->noise = nullptr; // cannot be shared! so created on demand def->biomes = biomes; } /////////////////////////////////////////////////////////////////////////////// ObjDef *OreScatter::clone() const { auto def = new OreScatter(); Ore::cloneTo(def); return def; } void OreScatter::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed); MapNode n_ore(c_ore, 0, ore_param2); u32 sizex = (nmax.X - nmin.X + 1); u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * (nmax.Z - nmin.Z + 1); u32 csize = clust_size; u32 cvolume = csize * csize * csize; u32 nclusters = volume / clust_scarcity; for (u32 i = 0; i != nclusters; i++) { int x0 = pr.range(nmin.X, nmax.X - csize + 1); int y0 = pr.range(nmin.Y, nmax.Y - csize + 1); int z0 = pr.range(nmin.Z, nmax.Z - csize + 1); if ((flags & OREFLAG_USE_NOISE) && (NoisePerlin3D(&np, x0, y0, z0, mapseed) < nthresh)) continue; if (biomemap && !biomes.empty()) { u32 index = sizex * (z0 - nmin.Z) + (x0 - nmin.X); auto it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } for (u32 z1 = 0; z1 != csize; z1++) for (u32 y1 = 0; y1 != csize; y1++) for (u32 x1 = 0; x1 != csize; x1++) { if (pr.range(1, cvolume) > clust_num_ores) continue; u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// ObjDef *OreSheet::clone() const { auto def = new OreSheet(); Ore::cloneTo(def); def->column_height_max = column_height_max; def->column_height_min = column_height_min; def->column_midpoint_factor = column_midpoint_factor; return def; } void OreSheet::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); u16 max_height = column_height_max; int y_start_min = nmin.Y + max_height; int y_start_max = nmax.Y - max_height; int y_start = y_start_min < y_start_max ? pr.range(y_start_min, y_start_max) : (y_start_min + y_start_max) / 2; if (!noise) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise = new Noise(&np, 0, sx, sz); } noise->seed = mapseed + y_start; noise->perlinMap2D(nmin.X, nmin.Z); size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++, index++) { float noiseval = noise->result[index]; if (noiseval < nthresh) continue; if (biomemap && !biomes.empty()) { auto it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } u16 height = pr.range(column_height_min, column_height_max); int ymidpoint = y_start + noiseval; int y0 = MYMAX(nmin.Y, ymidpoint - height * (1 - column_midpoint_factor)); int y1 = MYMIN(nmax.Y, y0 + height - 1); for (int y = y0; y <= y1; y++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// OrePuff::~OrePuff() { delete noise_puff_top; delete noise_puff_bottom; } ObjDef *OrePuff::clone() const { auto def = new OrePuff(); Ore::cloneTo(def); def->np_puff_top = np_puff_top; def->np_puff_bottom = np_puff_bottom; def->noise_puff_top = nullptr; // cannot be shared, on-demand def->noise_puff_bottom = nullptr; return def; } void OrePuff::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 4234); MapNode n_ore(c_ore, 0, ore_param2); int y_start = pr.range(nmin.Y, nmax.Y); if (!noise) { int sx = nmax.X - nmin.X + 1; int sz = nmax.Z - nmin.Z + 1; noise = new Noise(&np, 0, sx, sz); noise_puff_top = new Noise(&np_puff_top, 0, sx, sz); noise_puff_bottom = new Noise(&np_puff_bottom, 0, sx, sz); } noise->seed = mapseed + y_start; noise->perlinMap2D(nmin.X, nmin.Z); bool noise_generated = false; size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int x = nmin.X; x <= nmax.X; x++, index++) { float noiseval = noise->result[index]; if (noiseval < nthresh) continue; if (biomemap && !biomes.empty()) { auto it = biomes.find(biomemap[index]); if (it == biomes.end()) continue; } if (!noise_generated) { noise_generated = true; noise_puff_top->perlinMap2D(nmin.X, nmin.Z); noise_puff_bottom->perlinMap2D(nmin.X, nmin.Z); } float ntop = noise_puff_top->result[index]; float nbottom = noise_puff_bottom->result[index]; if (!(flags & OREFLAG_PUFF_CLIFFS)) { float ndiff = noiseval - nthresh; if (ndiff < 1.0f) { ntop *= ndiff; nbottom *= ndiff; } } int ymid = y_start; int y0 = ymid - nbottom; int y1 = ymid + ntop; if ((flags & OREFLAG_PUFF_ADDITIVE) && (y0 > y1)) SWAP(int, y0, y1); for (int y = y0; y <= y1; y++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// ObjDef *OreBlob::clone() const { auto def = new OreBlob(); Ore::cloneTo(def); return def; } void OreBlob::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 2404); MapNode n_ore(c_ore, 0, ore_param2); u32 sizex = (nmax.X - nmin.X + 1); u32 volume = (nmax.X - nmin.X + 1) * (nmax.Y - nmin.Y + 1) * (nmax.Z - nmin.Z + 1); u32 csize = clust_size; u32 nblobs = volume / clust_scarcity; if (!noise) noise = new Noise(&np, mapseed, csize, csize, csize); for (u32 i = 0; i != nblobs; i++) { int x0 = pr.range(nmin.X, nmax.X - csize + 1); int y0 = pr.range(nmin.Y, nmax.Y - csize + 1); int z0 = pr.range(nmin.Z, nmax.Z - csize + 1); if (biomemap && !biomes.empty()) { u32 bmapidx = sizex * (z0 - nmin.Z) + (x0 - nmin.X); auto it = biomes.find(biomemap[bmapidx]); if (it == biomes.end()) continue; } bool noise_generated = false; noise->seed = blockseed + i; size_t index = 0; for (u32 z1 = 0; z1 != csize; z1++) for (u32 y1 = 0; y1 != csize; y1++) for (u32 x1 = 0; x1 != csize; x1++, index++) { u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1); if (!CONTAINS(c_wherein, vm->m_data[i].getContent())) continue; // Lazily generate noise only if there's a chance of ore being placed // This simple optimization makes calls 6x faster on average if (!noise_generated) { noise_generated = true; noise->perlinMap3D(x0, y0, z0); } float noiseval = noise->result[index]; float xdist = (s32)x1 - (s32)csize / 2; float ydist = (s32)y1 - (s32)csize / 2; float zdist = (s32)z1 - (s32)csize / 2; noiseval -= std::sqrt(xdist * xdist + ydist * ydist + zdist * zdist) / csize; if (noiseval < nthresh) continue; vm->m_data[i] = n_ore; } } } /////////////////////////////////////////////////////////////////////////////// OreVein::~OreVein() { delete noise2; } ObjDef *OreVein::clone() const { auto def = new OreVein(); Ore::cloneTo(def); def->random_factor = random_factor; def->noise2 = nullptr; // cannot be shared, on-demand def->sizey_prev = sizey_prev; return def; } void OreVein::generate(MMVManip *vm, int mapseed, u32 blockseed, v3s16 nmin, v3s16 nmax, biome_t *biomemap) { PcgRandom pr(blockseed + 520); MapNode n_ore(c_ore, 0, ore_param2); int sizex = nmax.X - nmin.X + 1; int sizey = nmax.Y - nmin.Y + 1; // Because this ore uses 3D noise the perlinmap Y size can be different in // different mapchunks due to ore Y limits. So recreate the noise objects // if Y size has changed. // Because these noise objects are created multiple times for this ore type // it is necessary to 'delete' them here. if (!noise || sizey != sizey_prev) { delete noise; delete noise2; int sizez = nmax.Z - nmin.Z + 1; noise = new Noise(&np, mapseed, sizex, sizey, sizez); noise2 = new Noise(&np, mapseed + 436, sizex, sizey, sizez); sizey_prev = sizey; } bool noise_generated = false; size_t index = 0; for (int z = nmin.Z; z <= nmax.Z; z++) for (int y = nmin.Y; y <= nmax.Y; y++) for (int x = nmin.X; x <= nmax.X; x++, index++) { u32 i = vm->m_area.index(x, y, z); if (!vm->m_area.contains(i)) continue; if (!CONTAINS(c_wherein, vm->m_data[i].getContent()))