aboutsummaryrefslogtreecommitdiff
path: root/src/noise.cpp
blob: 9c2141ce086842618daefbb7283d54580f32d082 (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
/*
Minetest-c55
Copyright (C) 2010-2011 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 General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.

You should have received a copy of the GNU 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 <math.h>
#include "noise.h"
#include <iostream>
#include "debug.h"

#define NOISE_MAGIC_X 1619
#define NOISE_MAGIC_Y 31337
#define NOISE_MAGIC_Z 52591
#define NOISE_MAGIC_SEED 1013

double cos_lookup[16] = {
	1.0,0.9238,0.7071,0.3826,0,-0.3826,-0.7071,-0.9238,
	1.0,-0.9238,-0.7071,-0.3826,0,0.3826,0.7071,0.9238
};

double dotProduct(double vx, double vy, double wx, double wy){
    return vx*wx+vy*wy;
}
 
double easeCurve(double t){
    return 6*pow(t,5)-15*pow(t,4)+10*pow(t,3);
}
 
double linearInterpolation(double x0, double x1, double t){
    return x0+(x1-x0)*t;
}
 
double biLinearInterpolation(double x0y0, double x1y0, double x0y1, double x1y1, double x, double y){
    double tx = easeCurve(x);
    double ty = easeCurve(y);
	/*double tx = x;
	double ty = y;*/
    double u = linearInterpolation(x0y0,x1y0,tx);
    double v = linearInterpolation(x0y1,x1y1,tx);
    return linearInterpolation(u,v,ty);
}

double triLinearInterpolation(
		double v000, double v100, double v010, double v110,
		double v001, double v101, double v011, double v111,
		double x, double y, double z)
{
    /*double tx = easeCurve(x);
    double ty = easeCurve(y);
    double tz = easeCurve(z);*/
    double tx = x;
    double ty = y;
    double tz = z;
	return(
		v000*(1-tx)*(1-ty)*(1-tz) +
		v100*tx*(1-ty)*(1-tz) +
		v010*(1-tx)*ty*(1-tz) +
		v110*tx*ty*(1-tz) +
		v001*(1-tx)*(1-ty)*tz +
		v101*tx*(1-ty)*tz +
		v011*(1-tx)*ty*tz +
		v111*tx*ty*tz
	);
}

double noise2d(int x, int y, int seed)
{
	int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y
			+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
	n = (n>>13)^n;
	n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff;
	return 1.0 - (double)n/1073741824;
}

double noise3d(int x, int y, int z, int seed)
{
	int n = (NOISE_MAGIC_X * x + NOISE_MAGIC_Y * y + NOISE_MAGIC_Z * z
			+ NOISE_MAGIC_SEED * seed) & 0x7fffffff;
	n = (n>>13)^n;
	n = (n * (n*n*60493+19990303) + 1376312589) & 0x7fffffff;
	return 1.0 - (double)n/1073741824;
}

#if 0
double noise2d_gradient(double x, double y, int seed)
{
	// Calculate the integer coordinates
	int x0 = (x > 0.0 ? (int)x : (int)x - 1);
	int y0 = (y > 0.0 ? (int)y : (int)y - 1);
	// Calculate the remaining part of the coordinates
	double xl = x - (double)x0;
	double yl = y - (double)y0;
	// Calculate random cosine lookup table indices for the integer corners.
	// They are looked up as unit vector gradients from the lookup table.
	int n00 = (int)((noise2d(x0, y0, seed)+1)*8);
	int n10 = (int)((noise2d(x0+1, y0, seed)+1)*8);
	int n01 = (int)((noise2d(x0, y0+1, seed)+1)*8);
	int n11 = (int)((noise2d(x0+1, y0+1, seed)+1)*8);
	// Make a dot product for the gradients and the positions, to get the values
	double s = dotProduct(cos_lookup[n00], cos_lookup[(n00+12)%16], xl, yl);
	double u = dotProduct(-cos_lookup[n10], cos_lookup[(n10+12)%16], 1.-xl, yl);
	double v = dotProduct(cos_lookup[n01], -cos_lookup[(n01+12)%16], xl, 1.-yl);
	double w = dotProduct(-cos_lookup[n11], -cos_lookup[(n11+12)%16], 1.-xl, 1.-yl);
	// Interpolate between the values
	return biLinearInterpolation(s,u,v,w,xl,yl);
}
#endif

#if 1
double noise2d_gradient(double x, double y, int seed)
{
	// Calculate the integer coordinates
	int x0 = (x > 0.0 ? (int)x : (int)x - 1);
	int y0 = (y > 0.0 ? (int)y : (int)y - 1);
	// Calculate the remaining part of the coordinates
	double xl = x - (double)x0;
	double yl = y - (double)y0;
	// Get values for corners of cube
	double v00 = noise2d(x0, y0, seed);
	double v10 = noise2d(x0+1, y0, seed);
	double v01 = noise2d(x0, y0+1, seed);
	double v11 = noise2d(x0+1, y0+1, seed);
	// Interpolate
	return biLinearInterpolation(v00,v10,v01,v11,xl,yl);
}
#endif

double noise3d_gradient(double x, double y, double z, int seed)
{
	// Calculate the integer coordinates
	int x0 = (x > 0.0 ? (int)x : (int)x - 1);
	int y0 = (y > 0.0 ? (int)y : (int)y - 1);
	int z0 = (z > 0.0 ? (int)z : (int)z - 1);
	// Calculate the remaining part of the coordinates
	double xl = x - (double)x0;
	double yl = y - (double)y0;
	double zl = z - (double)z0;
	// Get values for corners of cube
	double v000 = noise3d(x0, y0, z0, seed);
	double v100 = noise3d(x0+1, y0, z0, seed);
	double v010 = noise3d(x0, y0+1, z0, seed);
	double v110 = noise3d(x0+1, y0+1, z0, seed);
	double v001 = noise3d(x0, y0, z0+1, seed);
	double v101 = noise3d(x0+1, y0, z0+1, seed);
	double v011 = noise3d(x0, y0+1, z0+1, seed);
	double v111 = noise3d(x0+1, y0+1, z0+1, seed);
	// Interpolate
	return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl);
}

double noise2d_perlin(double x, double y, int seed,
		int octaves, double persistence)
{
	double a = 0;
	double f = 1.0;
	double g = 1.0;
	for(int i=0; i<octaves; i++)
	{
		a += g * noise2d_gradient(x*f, y*f, seed+i);
		f *= 2.0;
		g *= persistence;
	}
	return a;
}

double noise2d_perlin_abs(double x, double y, int seed,
		int octaves, double persistence)
{
	double a = 0;
	double f = 1.0;
	double g = 1.0;
	for(int i=0; i<octaves; i++)
	{
		a += g * fabs(noise2d_gradient(x*f, y*f, seed+i));
		f *= 2.0;
		g *= persistence;
	}
	return a;
}

double noise3d_perlin(double x, double y, double z, int seed,
		int octaves, double persistence)
{
	double a = 0;
	double f = 1.0;
	double g = 1.0;
	for(int i=0; i<octaves; i++)
	{
		a += g * noise3d_gradient(x*f, y*f, z*f, seed+i);
		f *= 2.0;
		g *= persistence;
	}
	return a;
}

double noise3d_perlin_abs(double x, double y, double z, int seed,
		int octaves, double persistence)
{
	double a = 0;
	double f = 1.0;
	double g = 1.0;
	for(int i=0; i<octaves; i++)
	{
		a += g * fabs(noise3d_gradient(x*f, y*f, z*f, seed+i));
		f *= 2.0;
		g *= persistence;
	}
	return a;
}

// -1->0, 0->1, 1->0
double contour(double v)
{
	v = fabs(v);
	if(v >= 1.0)
		return 0.0;
	return (1.0-v);
}

double noise3d_param(const NoiseParams &param, double x, double y, double z)
{
	double s = param.pos_scale;
	x /= s;
	y /= s;
	z /= s;

	if(param.type == NOISE_CONSTANT_ONE)
	{
		return 1.0;
	}
	else if(param.type == NOISE_PERLIN)
	{
		return param.noise_scale*noise3d_perlin(x,y,z, param.seed,
				param.octaves,
				param.persistence);
	}
	else if(param.type == NOISE_PERLIN_ABS)
	{
		return param.noise_scale*noise3d_perlin_abs(x,y,z, param.seed,
				param.octaves,
				param.persistence);
	}
	else if(param.type == NOISE_PERLIN_CONTOUR)
	{
		return contour(param.noise_scale*noise3d_perlin(x,y,z,
				param.seed, param.octaves,
				param.persistence));
	}
	else if(param.type == NOISE_PERLIN_CONTOUR_FLIP_YZ)
	{
		return contour(param.noise_scale*noise3d_perlin(x,z,y,
				param.seed, param.octaves,
				param.persistence));
	}
	else assert(0);
}

/*
	NoiseBuffer
*/

NoiseBuffer::NoiseBuffer():
	m_data(NULL)
{
}

NoiseBuffer::~NoiseBuffer()
{
	clear();
}

void NoiseBuffer::clear()
{
	if(m_data)
		delete[] m_data;
	m_data = NULL;
	m_size_x = 0;
	m_size_y = 0;
	m_size_z = 0;
}

void NoiseBuffer::create(const NoiseParams &param,
		double first_x, double first_y, double first_z,
		double last_x, double last_y, double last_z,
		double samplelength_x, double samplelength_y, double samplelength_z)
{
	clear();
	
	m_start_x = first_x - samplelength_x;
	m_start_y = first_y - samplelength_y;
	m_start_z = first_z - samplelength_z;
	m_samplelength_x = samplelength_x;
	m_samplelength_y = samplelength_y;
	m_samplelength_z = samplelength_z;

	m_size_x = (last_x - m_start_x)/samplelength_x + 2;
	m_size_y = (last_y - m_start_y)/samplelength_y + 2;
	m_size_z = (last_z - m_start_z)/samplelength_z + 2;

	m_data = new double[m_size_x*m_size_y*m_size_z];

	for(int x=0; x<m_size_x; x++)
	for(int y=0; y<m_size_y; y++)
	for(int z=0; z<m_size_z; z++)
	{
		double xd = (m_start_x + (double)x*m_samplelength_x);
		double yd = (m_start_y + (double)y*m_samplelength_y);
		double zd = (m_start_z + (double)z*m_samplelength_z);
		double a = noise3d_param(param, xd,yd,zd);
		intSet(x,y,z, a);
	}
}

void NoiseBuffer::multiply(const NoiseParams &param)
{
	assert(m_data != NULL);

	for(int x=0; x<m_size_x; x++)
	for(int y=0; y<m_size_y; y++)
	for(int z=0; z<m_size_z; z++)
	{
		double xd = (m_start_x + (double)x*m_samplelength_x);
		double yd = (m_start_y + (double)y*m_samplelength_y);
		double zd = (m_start_z + (double)z*m_samplelength_z);
		double a = noise3d_param(param, xd,yd,zd);
		intMultiply(x,y,z, a);
	}
}

// Deprecated
void NoiseBuffer::create(int seed, int octaves, double persistence,
		bool abs,
		double first_x, double first_y, double first_z,
		double last_x, double last_y, double last_z,
		double samplelength_x, double samplelength_y, double samplelength_z)
{
	NoiseParams param;
	param.type = abs ? NOISE_PERLIN_ABS : NOISE_PERLIN;
	param.seed = seed;
	param.octaves = octaves;
	param.persistence = persistence;

	create(param, first_x, first_y, first_z,
			last_x, last_y, last_z,
			samplelength_x, samplelength_y, samplelength_z);
}

void NoiseBuffer::intSet(int x, int y, int z, double d)
{
	int i = m_size_x*m_size_y*z + m_size_x*y + x;
	assert(i >= 0);
	assert(i < m_size_x*m_size_y*m_size_z);
	m_data[i] = d;
}

void NoiseBuffer::intMultiply(int x, int y, int z, double d)
{
	int i = m_size_x*m_size_y*z + m_size_x*y + x;
	assert(i >= 0);
	assert(i < m_size_x*m_size_y*m_size_z);
	m_data[i] = m_data[i] * d;
}

double NoiseBuffer::intGet(int x, int y, int z)
{
	int i = m_size_x*m_size_y*z + m_size_x*y + x;
	assert(i >= 0);
	assert(i < m_size_x*m_size_y*m_size_z);
	return m_data[i];
}

double NoiseBuffer::get(double x, double y, double z)
{
	x -= m_start_x;
	y -= m_start_y;
	z -= m_start_z;
	x /= m_samplelength_x;
	y /= m_samplelength_y;
	z /= m_samplelength_z;
	// Calculate the integer coordinates
	int x0 = (x > 0.0 ? (int)x : (int)x - 1);
	int y0 = (y > 0.0 ? (int)y : (int)y - 1);
	int z0 = (z > 0.0 ? (int)z : (int)z - 1);
	// Calculate the remaining part of the coordinates
	double xl = x - (double)x0;
	double yl = y - (double)y0;
	double zl = z - (double)z0;
	// Get values for corners of cube
	double v000 = intGet(x0,   y0,   z0);
	double v100 = intGet(x0+1, y0,   z0);
	double v010 = intGet(x0,   y0+1, z0);
	double v110 = intGet(x0+1, y0+1, z0);
	double v001 = intGet(x0,   y0,   z0+1);
	double v101 = intGet(x0+1, y0,   z0+1);
	double v011 = intGet(x0,   y0+1, z0+1);
	double v111 = intGet(x0+1, y0+1, z0+1);
	// Interpolate
	return triLinearInterpolation(v000,v100,v010,v110,v001,v101,v011,v111,xl,yl,zl);
}

/*bool NoiseBuffer::contains(double x, double y, double z)
{
	x -= m_start_x;
	y -= m_start_y;
	z -= m_start_z;
	x /= m_samplelength_x;
	y /= m_samplelength_y;
	z /= m_samplelength_z;
	if(x <= 0.0 || x >= m_size_x)
}*/

ss="hl com"> */ void printCost(PathDirections dir); /** * print type of node as evaluated */ void printType(); /** * print pathlenght for all nodes in search area */ void printPathLen(); /** * print a path * @param path path to show */ void printPath(std::vector<v3s16> path); /** * print y direction for all movements */ void printYdir(); /** * print y direction for moving in a specific direction * @param dir direction to show data */ void printYdir(PathDirections dir); /** * helper function to translate a direction to speaking text * @param dir direction to translate * @return textual name of direction */ std::string dirToName(PathDirections dir); #endif }; /** Helper class for the open list priority queue in the A* pathfinder * to sort the pathfinder nodes by cost. */ class PathfinderCompareHeuristic { private: Pathfinder *myPathfinder; public: PathfinderCompareHeuristic(Pathfinder *pf) { myPathfinder = pf; } bool operator() (v3s16 pos1, v3s16 pos2) { v3s16 ipos1 = myPathfinder->getIndexPos(pos1); v3s16 ipos2 = myPathfinder->getIndexPos(pos2); PathGridnode &g_pos1 = myPathfinder->getIndexElement(ipos1); PathGridnode &g_pos2 = myPathfinder->getIndexElement(ipos2); if (!g_pos1.valid) return false; if (!g_pos2.valid) return false; return g_pos1.estimated_cost > g_pos2.estimated_cost; } }; /******************************************************************************/ /* implementation */ /******************************************************************************/ std::vector<v3s16> get_path(Map* map, const NodeDefManager *ndef, v3s16 source, v3s16 destination, unsigned int searchdistance, unsigned int max_jump, unsigned int max_drop, PathAlgorithm algo) { return Pathfinder(map, ndef).getPath(source, destination, searchdistance, max_jump, max_drop, algo); } /******************************************************************************/ PathCost::PathCost(const PathCost &b) { valid = b.valid; y_change = b.y_change; value = b.value; updated = b.updated; } /******************************************************************************/ PathCost &PathCost::operator= (const PathCost &b) { valid = b.valid; y_change = b.y_change; value = b.value; updated = b.updated; return *this; } /******************************************************************************/ PathGridnode::PathGridnode(const PathGridnode &b) : valid(b.valid), target(b.target), source(b.source), totalcost(b.totalcost), sourcedir(b.sourcedir), pos(b.pos), is_element(b.is_element), type(b.type) { directions[DIR_XP] = b.directions[DIR_XP]; directions[DIR_XM] = b.directions[DIR_XM]; directions[DIR_ZP] = b.directions[DIR_ZP]; directions[DIR_ZM] = b.directions[DIR_ZM]; } /******************************************************************************/ PathGridnode &PathGridnode::operator= (const PathGridnode &b) { valid = b.valid; target = b.target; source = b.source; is_element = b.is_element; totalcost = b.totalcost; sourcedir = b.sourcedir; pos = b.pos; type = b.type; directions[DIR_XP] = b.directions[DIR_XP]; directions[DIR_XM] = b.directions[DIR_XM]; directions[DIR_ZP] = b.directions[DIR_ZP]; directions[DIR_ZM] = b.directions[DIR_ZM]; return *this; } /******************************************************************************/ PathCost PathGridnode::getCost(v3s16 dir) { if (dir.X > 0) { return directions[DIR_XP]; } if (dir.X < 0) { return directions[DIR_XM]; } if (dir.Z > 0) { return directions[DIR_ZP]; } if (dir.Z < 0) { return directions[DIR_ZM]; } PathCost retval; return retval; } /******************************************************************************/ void PathGridnode::setCost(v3s16 dir, const PathCost &cost) { if (dir.X > 0) { directions[DIR_XP] = cost; } if (dir.X < 0) { directions[DIR_XM] = cost; } if (dir.Z > 0) { directions[DIR_ZP] = cost; } if (dir.Z < 0) { directions[DIR_ZM] = cost; } } void GridNodeContainer::initNode(v3s16 ipos, PathGridnode *p_node) { const NodeDefManager *ndef = m_pathf->m_ndef; PathGridnode &elem = *p_node; v3s16 realpos = m_pathf->getRealPos(ipos); MapNode current = m_pathf->m_map->getNode(realpos); MapNode below = m_pathf->m_map->getNode(realpos + v3s16(0, -1, 0)); if ((current.param0 == CONTENT_IGNORE) || (below.param0 == CONTENT_IGNORE)) { DEBUG_OUT("Pathfinder: " << PP(realpos) << " current or below is invalid element" << std::endl); if (current.param0 == CONTENT_IGNORE) { elem.type = 'i'; DEBUG_OUT(PP(ipos) << ": " << 'i' << std::endl); } return; } //don't add anything if it isn't an air node if (ndef->get(current).walkable || !ndef->get(below).walkable) { DEBUG_OUT("Pathfinder: " << PP(realpos) << " not on surface" << std::endl); if (ndef->get(current).walkable) { elem.type = 's'; DEBUG_OUT(PP(ipos) << ": " << 's' << std::endl); } else { elem.type = '-'; DEBUG_OUT(PP(ipos) << ": " << '-' << std::endl); } return; } elem.valid = true; elem.pos = realpos; elem.type = 'g'; DEBUG_OUT(PP(ipos) << ": " << 'a' << std::endl); if (m_pathf->m_prefetch) { elem.directions[DIR_XP] = m_pathf->calcCost(realpos, v3s16( 1, 0, 0)); elem.directions[DIR_XM] = m_pathf->calcCost(realpos, v3s16(-1, 0, 0)); elem.directions[DIR_ZP] = m_pathf->calcCost(realpos, v3s16( 0, 0, 1)); elem.directions[DIR_ZM] = m_pathf->calcCost(realpos, v3s16( 0, 0,-1)); } } ArrayGridNodeContainer::ArrayGridNodeContainer(Pathfinder *pathf, v3s16 dimensions) : m_x_stride(dimensions.Y * dimensions.Z), m_y_stride(dimensions.Z) { m_pathf = pathf; m_nodes_array.resize(dimensions.X * dimensions.Y * dimensions.Z); INFO_TARGET << "Pathfinder ArrayGridNodeContainer constructor." << std::endl; for (int x = 0; x < dimensions.X; x++) { for (int y = 0; y < dimensions.Y; y++) { for (int z= 0; z < dimensions.Z; z++) { v3s16 ipos(x, y, z); initNode(ipos, &access(ipos)); } } } } PathGridnode &ArrayGridNodeContainer::access(v3s16 p) { return m_nodes_array[p.X * m_x_stride + p.Y * m_y_stride + p.Z]; } MapGridNodeContainer::MapGridNodeContainer(Pathfinder *pathf) { m_pathf = pathf; } PathGridnode &MapGridNodeContainer::access(v3s16 p) { std::map<v3s16, PathGridnode>::iterator it = m_nodes.find(p); if (it != m_nodes.end()) { return it->second; } PathGridnode &n = m_nodes[p]; initNode(p, &n); return n; } /******************************************************************************/ std::vector<v3s16> Pathfinder::getPath(v3s16 source, v3s16 destination, unsigned int searchdistance, unsigned int max_jump, unsigned int max_drop, PathAlgorithm algo) { #ifdef PATHFINDER_CALC_TIME timespec ts; clock_gettime(CLOCK_REALTIME, &ts); #endif std::vector<v3s16> retval; //initialization m_maxjump = max_jump; m_maxdrop = max_drop; m_start = source; m_destination = destination; m_min_target_distance = -1; m_prefetch = true; if (algo == PA_PLAIN_NP) { m_prefetch = false; } //calculate boundaries within we're allowed to search int min_x = MYMIN(source.X, destination.X); int max_x = MYMAX(source.X, destination.X); int min_y = MYMIN(source.Y, destination.Y); int max_y = MYMAX(source.Y, destination.Y); int min_z = MYMIN(source.Z, destination.Z); int max_z = MYMAX(source.Z, destination.Z); m_limits.MinEdge.X = min_x - searchdistance; m_limits.MinEdge.Y = min_y - searchdistance; m_limits.MinEdge.Z = min_z - searchdistance; m_limits.MaxEdge.X = max_x + searchdistance; m_limits.MaxEdge.Y = max_y + searchdistance; m_limits.MaxEdge.Z = max_z + searchdistance; v3s16 diff = m_limits.MaxEdge - m_limits.MinEdge; m_max_index_x = diff.X; m_max_index_y = diff.Y; m_max_index_z = diff.Z; delete m_nodes_container; if (diff.getLength() > 5) { m_nodes_container = new MapGridNodeContainer(this); } else { m_nodes_container = new ArrayGridNodeContainer(this, diff); } #ifdef PATHFINDER_DEBUG printType(); printCost(); printYdir(); #endif //fail if source or destination is walkable MapNode node_at_pos = m_map->getNode(destination); if (m_ndef->get(node_at_pos).walkable) { VERBOSE_TARGET << "Destination is walkable. " << "Pos: " << PP(destination) << std::endl; return retval; } node_at_pos = m_map->getNode(source); if (m_ndef->get(node_at_pos).walkable) { VERBOSE_TARGET << "Source is walkable. " << "Pos: " << PP(source) << std::endl; return retval; } //If source pos is hovering above air, drop //to the first walkable node (up to m_maxdrop). //All algorithms expect the source pos to be *directly* above //a walkable node. v3s16 true_source = v3s16(source); source = walkDownwards(source, m_maxdrop); //If destination pos is hovering above air, go downwards //to the first walkable node (up to m_maxjump). //This means a hovering destination pos could be reached //by a final upwards jump. v3s16 true_destination = v3s16(destination); destination = walkDownwards(destination, m_maxjump); //validate and mark start and end pos v3s16 StartIndex = getIndexPos(source); v3s16 EndIndex = getIndexPos(destination); PathGridnode &startpos = getIndexElement(StartIndex); PathGridnode &endpos = getIndexElement(EndIndex); if (!startpos.valid) { VERBOSE_TARGET << "Invalid startpos " << "Index: " << PP(StartIndex) << "Realpos: " << PP(getRealPos(StartIndex)) << std::endl; return retval; } if (!endpos.valid) { VERBOSE_TARGET << "Invalid stoppos " << "Index: " << PP(EndIndex) << "Realpos: " << PP(getRealPos(EndIndex)) << std::endl; return retval; } endpos.target = true; startpos.source = true; startpos.totalcost = 0; bool update_cost_retval = false; //calculate node costs switch (algo) { case PA_DIJKSTRA: update_cost_retval = updateAllCosts(StartIndex, v3s16(0, 0, 0), 0, 0); break; case PA_PLAIN_NP: case PA_PLAIN: update_cost_retval = updateCostHeuristic(StartIndex, EndIndex); break; default: ERROR_TARGET << "Missing PathAlgorithm" << std::endl; break; } if (update_cost_retval) { #ifdef PATHFINDER_DEBUG std::cout << "Path to target found!" << std::endl; printPathLen(); #endif //find path std::vector<v3s16> index_path; buildPath(index_path, EndIndex); //Now we have a path of index positions, //and it's in reverse. //The "true" start or end position might be missing //since those have been given special treatment. #ifdef PATHFINDER_DEBUG std::cout << "Index path:" << std::endl; printPath(index_path); #endif //from here we'll make the final changes to the path std::vector<v3s16> full_path; //calculate required size int full_path_size = index_path.size(); if (source != true_source) { full_path_size++; } if (destination != true_destination) { full_path_size++; } full_path.reserve(full_path_size); //manually add true_source to start of path, if needed if (source != true_source) { full_path.push_back(true_source); } //convert all index positions to "normal" positions and insert //them into full_path in reverse std::vector<v3s16>::reverse_iterator rit = index_path.rbegin(); for (; rit != index_path.rend(); ++rit) { full_path.push_back(getIndexElement(*rit).pos); } //manually add true_destination to end of path, if needed if (destination != true_destination) { full_path.push_back(true_destination); } //Done! We now have a complete path of normal positions. #ifdef PATHFINDER_DEBUG std::cout << "Full path:" << std::endl; printPath(full_path); #endif #ifdef PATHFINDER_CALC_TIME timespec ts2; clock_gettime(CLOCK_REALTIME, &ts2); int ms = (ts2.tv_nsec - ts.tv_nsec)/(1000*1000); int us = ((ts2.tv_nsec - ts.tv_nsec) - (ms*1000*1000))/1000; int ns = ((ts2.tv_nsec - ts.tv_nsec) - ( (ms*1000*1000) + (us*1000))); std::cout << "Calculating path took: " << (ts2.tv_sec - ts.tv_sec) << "s " << ms << "ms " << us << "us " << ns << "ns " << std::endl; #endif return full_path; } else { #ifdef PATHFINDER_DEBUG printPathLen(); #endif INFO_TARGET << "No path found" << std::endl; } //return return retval; } Pathfinder::~Pathfinder() { delete m_nodes_container; } /******************************************************************************/ v3s16 Pathfinder::getRealPos(v3s16 ipos) { return m_limits.MinEdge + ipos; } /******************************************************************************/ PathCost Pathfinder::calcCost(v3s16 pos, v3s16 dir) { PathCost retval; retval.updated = true; v3s16 pos2 = pos + dir; //check limits if (!m_limits.isPointInside(pos2)) { DEBUG_OUT("Pathfinder: " << PP(pos2) << " no cost -> out of limits" << std::endl); return retval; } MapNode node_at_pos2 = m_map->getNode(pos2); //did we get information about node? if (node_at_pos2.param0 == CONTENT_IGNORE ) { VERBOSE_TARGET << "Pathfinder: (1) area at pos: " << PP(pos2) << " not loaded"; return retval; } if (!m_ndef->get(node_at_pos2).walkable) { MapNode node_below_pos2 = m_map->getNode(pos2 + v3s16(0, -1, 0)); //did we get information about node? if (node_below_pos2.param0 == CONTENT_IGNORE ) { VERBOSE_TARGET << "Pathfinder: (2) area at pos: " << PP((pos2 + v3s16(0, -1, 0))) << " not loaded"; return retval; } //test if the same-height neighbor is suitable if (m_ndef->get(node_below_pos2).walkable) { //SUCCESS! retval.valid = true; retval.value = 1; retval.y_change = 0; DEBUG_OUT("Pathfinder: "<< PP(pos) << " cost same height found" << std::endl); } else { //test if we can fall a couple of nodes (m_maxdrop) v3s16 testpos = pos2 + v3s16(0, -1, 0); MapNode node_at_pos = m_map->getNode(testpos); while ((node_at_pos.param0 != CONTENT_IGNORE) && (!m_ndef->get(node_at_pos).walkable) && (testpos.Y > m_limits.MinEdge.Y)) { testpos += v3s16(0, -1, 0); node_at_pos = m_map->getNode(testpos); } //did we find surface? if ((testpos.Y >= m_limits.MinEdge.Y) && (node_at_pos.param0 != CONTENT_IGNORE) && (m_ndef->get(node_at_pos).walkable)) { if ((pos2.Y - testpos.Y - 1) <= m_maxdrop) { //SUCCESS! retval.valid = true; retval.value = 2; //difference of y-pos +1 (target node is ABOVE solid node) retval.y_change = ((testpos.Y - pos2.Y) +1); DEBUG_OUT("Pathfinder cost below height found" << std::endl); } else { INFO_TARGET << "Pathfinder:" " distance to surface below too big: " << (testpos.Y - pos2.Y) << " max: " << m_maxdrop << std::endl; } } else { DEBUG_OUT("Pathfinder: no surface below found" << std::endl); } } } else { //test if we can jump upwards (m_maxjump) v3s16 targetpos = pos2; // position for jump target v3s16 jumppos = pos; // position for checking if jumping space is free MapNode node_target = m_map->getNode(targetpos); MapNode node_jump = m_map->getNode(jumppos); bool headbanger = false; // true if anything blocks jumppath while ((node_target.param0 != CONTENT_IGNORE) && (m_ndef->get(node_target).walkable) && (targetpos.Y < m_limits.MaxEdge.Y)) { //if the jump would hit any solid node, discard if ((node_jump.param0 == CONTENT_IGNORE) || (m_ndef->get(node_jump).walkable)) { headbanger = true; break; } targetpos += v3s16(0, 1, 0); jumppos += v3s16(0, 1, 0); node_target = m_map->getNode(targetpos); node_jump = m_map->getNode(jumppos); } //check headbanger one last time if ((node_jump.param0 == CONTENT_IGNORE) || (m_ndef->get(node_jump).walkable)) { headbanger = true; } //did we find surface without banging our head? if ((!headbanger) && (targetpos.Y <= m_limits.MaxEdge.Y) && (!m_ndef->get(node_target).walkable)) { if (targetpos.Y - pos2.Y <= m_maxjump) { //SUCCESS! retval.valid = true; retval.value = 2; retval.y_change = (targetpos.Y - pos2.Y); DEBUG_OUT("Pathfinder cost above found" << std::endl); } else { DEBUG_OUT("Pathfinder: distance to surface above too big: " << (targetpos.Y - pos2.Y) << " max: " << m_maxjump << std::endl); } } else { DEBUG_OUT("Pathfinder: no surface above found" << std::endl); } } return retval; }