aboutsummaryrefslogtreecommitdiff
path: root/src/servercommand.cpp
blob: d971b18a04c34d103a1a26d104b4e8bceecfea28 (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
/*
Part of Minetest-c55
Copyright (C) 2010-11 celeron55, Perttu Ahola <celeron55@gmail.com>
Copyright (C) 2011 Ciaran Gultnieks <ciaran@ciarang.com>

Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/

#include "servercommand.h"
#include "utility.h"
#include "settings.h"
#include "main.h" // For g_settings

#define PP(x) "("<<(x).X<<","<<(x).Y<<","<<(x).Z<<")"

void cmd_status(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	os<<ctx->server->getStatusString();
}

void cmd_me(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	std::wstring name = narrow_to_wide(ctx->player->getName());
	os << L"* " << name << L" " << ctx->paramstring;
	ctx->flags |= SEND_TO_OTHERS | SEND_NO_PREFIX;
}

void cmd_privs(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if(ctx->parms.size() == 1)
	{
		// Show our own real privs, without any adjustments
		// made for admin status
		os<<L"-!- " + narrow_to_wide(privsToString(
				ctx->server->getPlayerAuthPrivs(ctx->player->getName())));
		return;
	}

	if((ctx->privs & PRIV_PRIVS) == 0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}
		
	Player *tp = ctx->env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str());
	if(tp == NULL)
	{
		os<<L"-!- No such player";
		return;
	}
	
	os<<L"-!- " + narrow_to_wide(privsToString(ctx->server->getPlayerAuthPrivs(tp->getName())));
}

void cmd_grantrevoke(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if(ctx->parms.size() != 3)
	{
		os<<L"-!- Missing parameter";
		return;
	}

	if((ctx->privs & PRIV_PRIVS) == 0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	u64 newprivs = stringToPrivs(wide_to_narrow(ctx->parms[2]));
	if(newprivs == PRIV_INVALID)
	{
		os<<L"-!- Invalid privileges specified";
		return;
	}

	Player *tp = ctx->env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str());
	if(tp == NULL)
	{
		os<<L"-!- No such player";
		return;
	}
	
	std::string playername = wide_to_narrow(ctx->parms[1]);
	u64 privs = ctx->server->getPlayerAuthPrivs(playername);

	if(ctx->parms[0] == L"grant"){
		privs |= newprivs;
		actionstream<<ctx->player->getName()<<" grants "
				<<wide_to_narrow(ctx->parms[2])<<" to "
				<<playername<<std::endl;

		std::wstring msg;
		msg += narrow_to_wide(ctx->player->getName());
		msg += L" granted you the privilege \"";
		msg += ctx->parms[2];
		msg += L"\"";
		ctx->server->notifyPlayer(playername.c_str(), msg);
	} else {
		privs &= ~newprivs;
		actionstream<<ctx->player->getName()<<" revokes "
				<<wide_to_narrow(ctx->parms[2])<<" from "
				<<playername<<std::endl;

		std::wstring msg;
		msg += narrow_to_wide(ctx->player->getName());
		msg += L" revoked from you the privilege \"";
		msg += ctx->parms[2];
		msg += L"\"";
		ctx->server->notifyPlayer(playername.c_str(), msg);
	}
	
	ctx->server->setPlayerAuthPrivs(playername, privs);
	
	os<<L"-!- Privileges change to ";
	os<<narrow_to_wide(privsToString(privs));
}

void cmd_time(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if(ctx->parms.size() != 2)
	{
		os<<L"-!- Missing parameter";
		return;
	}

	if((ctx->privs & PRIV_SETTIME) ==0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	u32 time = stoi(wide_to_narrow(ctx->parms[1]));
	ctx->server->setTimeOfDay(time);
	os<<L"-!- time_of_day changed.";

	actionstream<<ctx->player->getName()<<" sets time "
			<<time<<std::endl;
}

void cmd_shutdown(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_SERVER) ==0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	actionstream<<ctx->player->getName()
			<<" shuts down server"<<std::endl;

	ctx->server->requestShutdown();
					
	os<<L"*** Server shutting down (operator request)";
	ctx->flags |= SEND_TO_OTHERS;
}

void cmd_setting(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_SERVER) ==0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	/*std::string confline = wide_to_narrow(
			ctx->parms[1] + L" = " + ctx->params[2]);*/

	std::string confline = wide_to_narrow(ctx->paramstring);
	
	actionstream<<ctx->player->getName()
			<<" sets: "<<confline<<std::endl;

	g_settings->parseConfigLine(confline);
	
	ctx->server->saveConfig();

	os<< L"-!- Setting changed and configuration saved.";
}

void cmd_teleport(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_TELEPORT) ==0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	if(ctx->parms.size() != 2)
	{
		os<<L"-!- Missing parameter";
		return;
	}

	std::vector<std::wstring> coords = str_split(ctx->parms[1], L',');
	if(coords.size() != 3)
	{
		os<<L"-!- You can only specify coordinates currently";
		return;
	}

	v3f dest(stoi(coords[0])*10, stoi(coords[1])*10, stoi(coords[2])*10);

	actionstream<<ctx->player->getName()<<" teleports from "
			<<PP(ctx->player->getPosition()/BS)<<" to "
			<<PP(dest/BS)<<std::endl;

	//ctx->player->setPosition(dest);

	// Use the ServerActiveObject interface of ServerRemotePlayer
	ServerRemotePlayer *srp = static_cast<ServerRemotePlayer*>(ctx->player);
	srp->setPos(dest);
	ctx->server->SendMovePlayer(ctx->player);

	os<< L"-!- Teleported.";
}

void cmd_banunban(std::wostringstream &os, ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_BAN) == 0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	if(ctx->parms.size() < 2)
	{
		std::string desc = ctx->server->getBanDescription("");
		os<<L"-!- Ban list: "<<narrow_to_wide(desc);
		return;
	}
	if(ctx->parms[0] == L"ban")
	{
		Player *player = ctx->env->getPlayer(wide_to_narrow(ctx->parms[1]).c_str());

		if(player == NULL)
		{
			os<<L"-!- No such player";
			return;
		}
		
		try{
			Address address = ctx->server->getPeerAddress(player->peer_id);
			std::string ip_string = address.serializeString();
			ctx->server->setIpBanned(ip_string, player->getName());
			os<<L"-!- Banned "<<narrow_to_wide(ip_string)<<L"|"
					<<narrow_to_wide(player->getName());

			actionstream<<ctx->player->getName()<<" bans "
					<<player->getName()<<" / "<<ip_string<<std::endl;
		} catch(con::PeerNotFoundException){
			dstream<<__FUNCTION_NAME<<": peer was not found"<<std::endl;
		}
	}
	else
	{
		std::string ip_or_name = wide_to_narrow(ctx->parms[1]);
		std::string desc = ctx->server->getBanDescription(ip_or_name);
		ctx->server->unsetIpBanned(ip_or_name);
		os<<L"-!- Unbanned "<<narrow_to_wide(desc);

		actionstream<<ctx->player->getName()<<" unbans "
				<<ip_or_name<<std::endl;
	}
}

void cmd_setclearpassword(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_PASSWORD) == 0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	std::string playername;
	std::wstring password;

	if(ctx->parms[0] == L"setpassword")
	{
		if(ctx->parms.size() != 3)
		{
			os<<L"-!- Missing parameter";
			return;
		}

		playername = wide_to_narrow(ctx->parms[1]);
		password = ctx->parms[2];

		actionstream<<ctx->player->getName()<<" sets password of "
			<<playername<<std::endl;
	}
	else
	{
		// clearpassword

		if(ctx->parms.size() != 2)
		{
			os<<L"-!- Missing parameter";
			return;
		}

		playername = wide_to_narrow(ctx->parms[1]);
		password = L"";

		actionstream<<ctx->player->getName()<<" clears password of"
			<<playername<<std::endl;
	}

	ctx->server->setPlayerPassword(playername, password);

	os<<L"-!- Password change for "<<narrow_to_wide(playername)<<" successful";
}

void cmd_clearobjects(std::wostringstream &os,
	ServerCommandContext *ctx)
{
	if((ctx->privs & PRIV_SERVER) ==0)
	{
		os<<L"-!- You don't have permission to do that";
		return;
	}

	actionstream<<ctx->player->getName()
			<<" clears all objects"<<std::endl;
	
	{
		std::wstring msg;
		msg += L"Clearing all objects. This may take long.";
		msg += L" You may experience a timeout. (by ";
		msg += narrow_to_wide(ctx->player->getName());
		msg += L")";
		ctx->server->notifyPlayers(msg);
	}

	ctx->env->clearAllObjects();
					
	actionstream<<"object clearing done"<<std::endl;
	
	os<<L"*** cleared all objects";
	ctx->flags |= SEND_TO_OTHERS;
}


std::wstring processServerCommand(ServerCommandContext *ctx)
{

	std::wostringstream os(std::ios_base::binary);
	ctx->flags = SEND_TO_SENDER;	// Default, unless we change it.

	u64 privs = ctx->privs;

	if(ctx->parms.size() == 0 || ctx->parms[0] == L"help")
	{
		os<<L"-!- Available commands: ";
		os<<L"me status privs";
		if(privs & PRIV_SERVER)
			os<<L" shutdown setting clearobjects";
		if(privs & PRIV_SETTIME)
			os<<L" time";
		if(privs & PRIV_TELEPORT)
			os<<L" teleport";
		if(privs & PRIV_PRIVS)
			os<<L" grant revoke";
		if(privs & PRIV_BAN)
			os<<L" ban unban";
		if(privs & PRIV_PASSWORD)
			os<<L" setpassword clearpassword";
	}
	else if(ctx->parms[0] == L"status")
		cmd_status(os, ctx);
	else if(ctx->parms[0] == L"privs")
		cmd_privs(os, ctx);
	else if(ctx->parms[0] == L"grant" || ctx->parms[0] == L"revoke")
		cmd_grantrevoke(os, ctx);
	else if(ctx->parms[0] == L"time")
		cmd_time(os, ctx);
	else if(ctx->parms[0] == L"shutdown")
		cmd_shutdown(os, ctx);
	else if(ctx->parms[0] == L"setting")
		cmd_setting(os, ctx);
	else if(ctx->parms[0] == L"teleport")
		cmd_teleport(os, ctx);
	else if(ctx->parms[0] == L"ban" || ctx->parms[0] == L"unban")
		cmd_banunban(os, ctx);
	else if(ctx->parms[0] == L"setpassword" || ctx->parms[0] == L"clearpassword")
		cmd_setclearpassword(os, ctx);
	else if(ctx->parms[0] == L"me")
		cmd_me(os, ctx);
	else if(ctx->parms[0] == L"clearobjects")
		cmd_clearobjects(os, ctx);
	else
		os<<L"-!- Invalid command: " + ctx->parms[0];
	
	return os.str();
}


>1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941
/*
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.
*/

#include "tile.h"
#include "debug.h"
#include "main.h" // for g_settings
#include "filesys.h"
#include "settings.h"
#include "mesh.h"
#include <ICameraSceneNode.h>
#include "log.h"
#include "mapnode.h" // For texture atlas making
#include "nodedef.h" // For texture atlas making
#include "gamedef.h"
#include "util/string.h"
#include "util/container.h"
#include "util/thread.h"
#include "util/numeric.h"

/*
	A cache from texture name to texture path
*/
MutexedMap<std::string, std::string> g_texturename_to_path_cache;

/*
	Replaces the filename extension.
	eg:
		std::string image = "a/image.png"
		replace_ext(image, "jpg")
		-> image = "a/image.jpg"
	Returns true on success.
*/
static bool replace_ext(std::string &path, const char *ext)
{
	if(ext == NULL)
		return false;
	// Find place of last dot, fail if \ or / found.
	s32 last_dot_i = -1;
	for(s32 i=path.size()-1; i>=0; i--)
	{
		if(path[i] == '.')
		{
			last_dot_i = i;
			break;
		}
		
		if(path[i] == '\\' || path[i] == '/')
			break;
	}
	// If not found, return an empty string
	if(last_dot_i == -1)
		return false;
	// Else make the new path
	path = path.substr(0, last_dot_i+1) + ext;
	return true;
}

/*
	Find out the full path of an image by trying different filename
	extensions.

	If failed, return "".
*/
std::string getImagePath(std::string path)
{
	// A NULL-ended list of possible image extensions
	const char *extensions[] = {
		"png", "jpg", "bmp", "tga",
		"pcx", "ppm", "psd", "wal", "rgb",
		NULL
	};
	// If there is no extension, add one
	if(removeStringEnd(path, extensions) == "")
		path = path + ".png";
	// Check paths until something is found to exist
	const char **ext = extensions;
	do{
		bool r = replace_ext(path, *ext);
		if(r == false)
			return "";
		if(fs::PathExists(path))
			return path;
	}
	while((++ext) != NULL);
	
	return "";
}

/*
	Gets the path to a texture by first checking if the texture exists
	in texture_path and if not, using the data path.

	Checks all supported extensions by replacing the original extension.

	If not found, returns "".

	Utilizes a thread-safe cache.
*/
std::string getTexturePath(const std::string &filename)
{
	std::string fullpath = "";
	/*
		Check from cache
	*/
	bool incache = g_texturename_to_path_cache.get(filename, &fullpath);
	if(incache)
		return fullpath;
	
	/*
		Check from texture_path
	*/
	std::string texture_path = g_settings->get("texture_path");
	if(texture_path != "")
	{
		std::string testpath = texture_path + DIR_DELIM + filename;
		// Check all filename extensions. Returns "" if not found.
		fullpath = getImagePath(testpath);
	}
	
	/*
		Check from $user/textures/all
	*/
	if(fullpath == "")
	{
		std::string texture_path = porting::path_user + DIR_DELIM
				+ "textures" + DIR_DELIM + "all";
		std::string testpath = texture_path + DIR_DELIM + filename;
		// Check all filename extensions. Returns "" if not found.
		fullpath = getImagePath(testpath);
	}

	/*
		Check from default data directory
	*/
	if(fullpath == "")
	{
		std::string base_path = porting::path_share + DIR_DELIM + "textures"
				+ DIR_DELIM + "base" + DIR_DELIM + "pack";
		std::string testpath = base_path + DIR_DELIM + filename;
		// Check all filename extensions. Returns "" if not found.
		fullpath = getImagePath(testpath);
	}
	
	// Add to cache (also an empty result is cached)
	g_texturename_to_path_cache.set(filename, fullpath);
	
	// Finally return it
	return fullpath;
}

/*
	An internal variant of AtlasPointer with more data.
	(well, more like a wrapper)
*/

struct SourceAtlasPointer
{
	std::string name;
	AtlasPointer a;
	video::IImage *atlas_img; // The source image of the atlas
	// Integer variants of position and size
	v2s32 intpos;
	v2u32 intsize;

	SourceAtlasPointer(
			const std::string &name_,
			AtlasPointer a_=AtlasPointer(0, NULL),
			video::IImage *atlas_img_=NULL,
			v2s32 intpos_=v2s32(0,0),
			v2u32 intsize_=v2u32(0,0)
		):
		name(name_),
		a(a_),
		atlas_img(atlas_img_),
		intpos(intpos_),
		intsize(intsize_)
	{
	}
};

/*
	SourceImageCache: A cache used for storing source images.
*/

class SourceImageCache
{
public:
	~SourceImageCache() {
		for(std::map<std::string, video::IImage*>::iterator iter = m_images.begin();
				iter != m_images.end(); iter++) {
			iter->second->drop();
		}
		m_images.clear();
	}
	void insert(const std::string &name, video::IImage *img,
			bool prefer_local, video::IVideoDriver *driver)
	{
		assert(img);
		// Remove old image
		std::map<std::string, video::IImage*>::iterator n;
		n = m_images.find(name);
		if(n != m_images.end()){
			if(n->second)
				n->second->drop();
		}

		video::IImage* toadd = img;
		bool need_to_grab = true;

		// Try to use local texture instead if asked to
		if(prefer_local){
			std::string path = getTexturePath(name.c_str());
			if(path != ""){
				video::IImage *img2 = driver->createImageFromFile(path.c_str());
				if(img2){
					toadd = img2;
					need_to_grab = false;
				}
			}
		}

		if (need_to_grab)
			toadd->grab();
		m_images[name] = toadd;
	}
	video::IImage* get(const std::string &name)
	{
		std::map<std::string, video::IImage*>::iterator n;
		n = m_images.find(name);
		if(n != m_images.end())
			return n->second;
		return NULL;
	}
	// Primarily fetches from cache, secondarily tries to read from filesystem
	video::IImage* getOrLoad(const std::string &name, IrrlichtDevice *device)
	{
		std::map<std::string, video::IImage*>::iterator n;
		n = m_images.find(name);
		if(n != m_images.end()){
			n->second->grab(); // Grab for caller
			return n->second;
		}
		video::IVideoDriver* driver = device->getVideoDriver();
		std::string path = getTexturePath(name.c_str());
		if(path == ""){
			infostream<<"SourceImageCache::getOrLoad(): No path found for \""
					<<name<<"\""<<std::endl;
			return NULL;
		}
		infostream<<"SourceImageCache::getOrLoad(): Loading path \""<<path
				<<"\""<<std::endl;
		video::IImage *img = driver->createImageFromFile(path.c_str());

		if(img){
			m_images[name] = img;
			img->grab(); // Grab for caller
		}
		return img;
	}
private:
	std::map<std::string, video::IImage*> m_images;
};

/*
	TextureSource
*/

class TextureSource : public IWritableTextureSource
{
public:
	TextureSource(IrrlichtDevice *device);
	virtual ~TextureSource();

	/*
		Example case:
		Now, assume a texture with the id 1 exists, and has the name
		"stone.png^mineral1".
		Then a random thread calls getTextureId for a texture called
		"stone.png^mineral1^crack0".
		...Now, WTF should happen? Well:
		- getTextureId strips off stuff recursively from the end until
		  the remaining part is found, or nothing is left when
		  something is stripped out

		But it is slow to search for textures by names and modify them
		like that?
		- ContentFeatures is made to contain ids for the basic plain
		  textures
		- Crack textures can be slow by themselves, but the framework
		  must be fast.

		Example case #2:
		- Assume a texture with the id 1 exists, and has the name
		  "stone.png^mineral1" and is specified as a part of some atlas.
		- Now getNodeTile() stumbles upon a node which uses
		  texture id 1, and determines that MATERIAL_FLAG_CRACK
		  must be applied to the tile
		- MapBlockMesh::animate() finds the MATERIAL_FLAG_CRACK and
		  has received the current crack level 0 from the client. It
		  finds out the name of the texture with getTextureName(1),
		  appends "^crack0" to it and gets a new texture id with
		  getTextureId("stone.png^mineral1^crack0").

	*/
	
	/*
		Gets a texture id from cache or
		- if main thread, from getTextureIdDirect
		- if other thread, adds to request queue and waits for main thread
	*/
	u32 getTextureId(const std::string &name);
	
	/*
		Example names:
		"stone.png"
		"stone.png^crack2"
		"stone.png^mineral_coal.png"
		"stone.png^mineral_coal.png^crack1"

		- If texture specified by name is found from cache, return the
		  cached id.
		- Otherwise generate the texture, add to cache and return id.
		  Recursion is used to find out the largest found part of the
		  texture and continue based on it.

		The id 0 points to a NULL texture. It is returned in case of error.
	*/
	u32 getTextureIdDirect(const std::string &name);

	// Finds out the name of a cached texture.
	std::string getTextureName(u32 id);

	/*
		If texture specified by the name pointed by the id doesn't
		exist, create it, then return the cached texture.

		Can be called from any thread. If called from some other thread
		and not found in cache, the call is queued to the main thread
		for processing.
	*/
	AtlasPointer getTexture(u32 id);
	
	AtlasPointer getTexture(const std::string &name)
	{
		return getTexture(getTextureId(name));
	}
	
	// Gets a separate texture
	video::ITexture* getTextureRaw(const std::string &name)
	{
		AtlasPointer ap = getTexture(name + "^[forcesingle");
		return ap.atlas;
	}

	// Gets a separate texture atlas pointer
	AtlasPointer getTextureRawAP(const AtlasPointer &ap)
	{
		return getTexture(getTextureName(ap.id) + "^[forcesingle");
	}

	// Returns a pointer to the irrlicht device
	virtual IrrlichtDevice* getDevice()
	{
		return m_device;
	}

	// Update new texture pointer and texture coordinates to an
	// AtlasPointer based on it's texture id
	void updateAP(AtlasPointer &ap);
 
	bool isKnownSourceImage(const std::string &name)
	{
		bool is_known = false;
		bool cache_found = m_source_image_existence.get(name, &is_known);
		if(cache_found)
			return is_known;
		// Not found in cache; find out if a local file exists
		is_known = (getTexturePath(name) != "");
		m_source_image_existence.set(name, is_known);
		return is_known;
	}

	// Processes queued texture requests from other threads.
	// Shall be called from the main thread.
	void processQueue();
	
	// Insert an image into the cache without touching the filesystem.
	// Shall be called from the main thread.
	void insertSourceImage(const std::string &name, video::IImage *img);
	
	// Rebuild images and textures from the current set of source images
	// Shall be called from the main thread.
	void rebuildImagesAndTextures();

	// Build the main texture atlas which contains most of the
	// textures.
	void buildMainAtlas(class IGameDef *gamedef);
	
private:
	
	// The id of the thread that is allowed to use irrlicht directly
	threadid_t m_main_thread;
	// The irrlicht device
	IrrlichtDevice *m_device;
	
	// Cache of source images
	// This should be only accessed from the main thread
	SourceImageCache m_sourcecache;

	// Thread-safe cache of what source images are known (true = known)
	MutexedMap<std::string, bool> m_source_image_existence;

	// A texture id is index in this array.
	// The first position contains a NULL texture.
	std::vector<SourceAtlasPointer> m_atlaspointer_cache;
	// Maps a texture name to an index in the former.
	std::map<std::string, u32> m_name_to_id;
	// The two former containers are behind this mutex
	JMutex m_atlaspointer_cache_mutex;
	
	// Main texture atlas. This is filled at startup and is then not touched.
	video::IImage *m_main_atlas_image;
	video::ITexture *m_main_atlas_texture;

	// Queued texture fetches (to be processed by the main thread)
	RequestQueue<std::string, u32, u8, u8> m_get_texture_queue;
};

IWritableTextureSource* createTextureSource(IrrlichtDevice *device)
{
	return new TextureSource(device);
}

TextureSource::TextureSource(IrrlichtDevice *device):
		m_device(device),
		m_main_atlas_image(NULL),
		m_main_atlas_texture(NULL)
{
	assert(m_device);
	
	m_atlaspointer_cache_mutex.Init();
	
	m_main_thread = get_current_thread_id();
	
	// Add a NULL AtlasPointer as the first index, named ""
	m_atlaspointer_cache.push_back(SourceAtlasPointer(""));
	m_name_to_id[""] = 0;
}

TextureSource::~TextureSource()
{
	video::IVideoDriver* driver = m_device->getVideoDriver();

	unsigned int textures_before = driver->getTextureCount();

	for (std::vector<SourceAtlasPointer>::iterator iter =
			m_atlaspointer_cache.begin();  iter != m_atlaspointer_cache.end();
			iter++)
	{
		video::ITexture *t = driver->getTexture(iter->name.c_str());

		//cleanup texture
		if (t)
			driver->removeTexture(t);

		//cleanup source image
		if (iter->atlas_img)
			iter->atlas_img->drop();
	}
	m_atlaspointer_cache.clear();

	infostream << "~TextureSource() "<< textures_before << "/"
			<< driver->getTextureCount() << std::endl;
}

u32 TextureSource::getTextureId(const std::string &name)
{
	//infostream<<"getTextureId(): \""<<name<<"\""<<std::endl;

	{
		/*
			See if texture already exists
		*/
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);
		std::map<std::string, u32>::iterator n;
		n = m_name_to_id.find(name);
		if(n != m_name_to_id.end())
		{
			return n->second;
		}
	}
	
	/*
		Get texture
	*/
	if(get_current_thread_id() == m_main_thread)
	{
		return getTextureIdDirect(name);
	}
	else
	{
		infostream<<"getTextureId(): Queued: name=\""<<name<<"\""<<std::endl;

		// We're gonna ask the result to be put into here
		ResultQueue<std::string, u32, u8, u8> result_queue;
		
		// Throw a request in
		m_get_texture_queue.add(name, 0, 0, &result_queue);
		
		infostream<<"Waiting for texture from main thread, name=\""
				<<name<<"\""<<std::endl;
		
		try
		{
			// Wait result for a second
			GetResult<std::string, u32, u8, u8>
					result = result_queue.pop_front(1000);
		
			// Check that at least something worked OK
			assert(result.key == name);

			return result.item;
		}
		catch(ItemNotFoundException &e)
		{
			infostream<<"Waiting for texture timed out."<<std::endl;
			return 0;
		}
	}
	
	infostream<<"getTextureId(): Failed"<<std::endl;

	return 0;
}

// Overlay image on top of another image (used for cracks)
void overlay(video::IImage *image, video::IImage *overlay);

// Draw an image on top of an another one, using the alpha channel of the
// source image
static void blit_with_alpha(video::IImage *src, video::IImage *dst,
		v2s32 src_pos, v2s32 dst_pos, v2u32 size);

// Brighten image
void brighten(video::IImage *image);
// Parse a transform name
u32 parseImageTransform(const std::string& s);
// Apply transform to image dimension
core::dimension2d<u32> imageTransformDimension(u32 transform, core::dimension2d<u32> dim);
// Apply transform to image data
void imageTransform(u32 transform, video::IImage *src, video::IImage *dst);

/*
	Generate image based on a string like "stone.png" or "[crack0".
	if baseimg is NULL, it is created. Otherwise stuff is made on it.
*/
bool generate_image(std::string part_of_name, video::IImage *& baseimg,
		IrrlichtDevice *device, SourceImageCache *sourcecache);

/*
	Generates an image from a full string like
	"stone.png^mineral_coal.png^[crack0".

	This is used by buildMainAtlas().
*/
video::IImage* generate_image_from_scratch(std::string name,
		IrrlichtDevice *device, SourceImageCache *sourcecache);

/*
	This method generates all the textures
*/
u32 TextureSource::getTextureIdDirect(const std::string &name)
{
	//infostream<<"getTextureIdDirect(): name=\""<<name<<"\""<<std::endl;

	// Empty name means texture 0
	if(name == "")
	{
		infostream<<"getTextureIdDirect(): name is empty"<<std::endl;
		return 0;
	}
	
	/*
		Calling only allowed from main thread
	*/
	if(get_current_thread_id() != m_main_thread)
	{
		errorstream<<"TextureSource::getTextureIdDirect() "
				"called not from main thread"<<std::endl;
		return 0;
	}

	/*
		See if texture already exists
	*/
	{
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);

		std::map<std::string, u32>::iterator n;
		n = m_name_to_id.find(name);
		if(n != m_name_to_id.end())
		{
			/*infostream<<"getTextureIdDirect(): \""<<name
					<<"\" found in cache"<<std::endl;*/
			return n->second;
		}
	}

	/*infostream<<"getTextureIdDirect(): \""<<name
			<<"\" NOT found in cache. Creating it."<<std::endl;*/
	
	/*
		Get the base image
	*/

	char separator = '^';

	/*
		This is set to the id of the base image.
		If left 0, there is no base image and a completely new image
		is made.
	*/
	u32 base_image_id = 0;
	
	// Find last meta separator in name
	s32 last_separator_position = -1;
	for(s32 i=name.size()-1; i>=0; i--)
	{
		if(name[i] == separator)
		{
			last_separator_position = i;
			break;
		}
	}
	/*
		If separator was found, construct the base name and make the
		base image using a recursive call
	*/
	std::string base_image_name;
	if(last_separator_position != -1)
	{
		// Construct base name
		base_image_name = name.substr(0, last_separator_position);
		/*infostream<<"getTextureIdDirect(): Calling itself recursively"
				" to get base image of \""<<name<<"\" = \""
                <<base_image_name<<"\""<<std::endl;*/
		base_image_id = getTextureIdDirect(base_image_name);
	}
	
	//infostream<<"base_image_id="<<base_image_id<<std::endl;
	
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	video::ITexture *t = NULL;

	/*
		An image will be built from files and then converted into a texture.
	*/
	video::IImage *baseimg = NULL;
	
	// If a base image was found, copy it to baseimg
	if(base_image_id != 0)
	{
		JMutexAutoLock lock(m_atlaspointer_cache_mutex);

		SourceAtlasPointer ap = m_atlaspointer_cache[base_image_id];

		video::IImage *image = ap.atlas_img;
		
		if(image == NULL)
		{
			infostream<<"getTextureIdDirect(): WARNING: NULL image in "
					<<"cache: \""<<base_image_name<<"\""
					<<std::endl;
		}
		else
		{
			core::dimension2d<u32> dim = ap.intsize;

			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);

			core::position2d<s32> pos_to(0,0);
			core::position2d<s32> pos_from = ap.intpos;
			
			image->copyTo(
					baseimg, // target
					v2s32(0,0), // position in target
					core::rect<s32>(pos_from, dim) // from
			);

			/*infostream<<"getTextureIdDirect(): Loaded \""
					<<base_image_name<<"\" from image cache"
					<<std::endl;*/
		}
	}
	
	/*
		Parse out the last part of the name of the image and act
		according to it
	*/

	std::string last_part_of_name = name.substr(last_separator_position+1);
	//infostream<<"last_part_of_name=\""<<last_part_of_name<<"\""<<std::endl;

	// Generate image according to part of name
	if(!generate_image(last_part_of_name, baseimg, m_device, &m_sourcecache))
	{
		errorstream<<"getTextureIdDirect(): "
				"failed to generate \""<<last_part_of_name<<"\""
				<<std::endl;
	}

	// If no resulting image, print a warning
	if(baseimg == NULL)
	{
		errorstream<<"getTextureIdDirect(): baseimg is NULL (attempted to"
				" create texture \""<<name<<"\""<<std::endl;
	}
	
	if(baseimg != NULL)
	{
		// Create texture from resulting image
		t = driver->addTexture(name.c_str(), baseimg);
	}
	
	/*
		Add texture to caches (add NULL textures too)
	*/

	JMutexAutoLock lock(m_atlaspointer_cache_mutex);
	
	u32 id = m_atlaspointer_cache.size();
	AtlasPointer ap(id);
	ap.atlas = t;
	ap.pos = v2f(0,0);
	ap.size = v2f(1,1);
	ap.tiled = 0;
	core::dimension2d<u32> baseimg_dim(0,0);
	if(baseimg)
		baseimg_dim = baseimg->getDimension();
	SourceAtlasPointer nap(name, ap, baseimg, v2s32(0,0), baseimg_dim);
	m_atlaspointer_cache.push_back(nap);
	m_name_to_id[name] = id;

	/*infostream<<"getTextureIdDirect(): "
			<<"Returning id="<<id<<" for name \""<<name<<"\""<<std::endl;*/
	
	return id;
}

std::string TextureSource::getTextureName(u32 id)
{
	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	if(id >= m_atlaspointer_cache.size())
	{
		errorstream<<"TextureSource::getTextureName(): id="<<id
				<<" >= m_atlaspointer_cache.size()="
				<<m_atlaspointer_cache.size()<<std::endl;
		return "";
	}
	
	return m_atlaspointer_cache[id].name;
}


AtlasPointer TextureSource::getTexture(u32 id)
{
	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	if(id >= m_atlaspointer_cache.size())
		return AtlasPointer(0, NULL);
	
	return m_atlaspointer_cache[id].a;
}

void TextureSource::updateAP(AtlasPointer &ap)
{
	AtlasPointer ap2 = getTexture(ap.id);
	ap = ap2;
}

void TextureSource::processQueue()
{
	/*
		Fetch textures
	*/
	if(!m_get_texture_queue.empty())
	{
		GetRequest<std::string, u32, u8, u8>
				request = m_get_texture_queue.pop();

		/*infostream<<"TextureSource::processQueue(): "
				<<"got texture request with "
				<<"name=\""<<request.key<<"\""
				<<std::endl;*/

		GetResult<std::string, u32, u8, u8>
				result;
		result.key = request.key;
		result.callers = request.callers;
		result.item = getTextureIdDirect(request.key);

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

void TextureSource::insertSourceImage(const std::string &name, video::IImage *img)
{
	//infostream<<"TextureSource::insertSourceImage(): name="<<name<<std::endl;
	
	assert(get_current_thread_id() == m_main_thread);
	
	m_sourcecache.insert(name, img, true, m_device->getVideoDriver());
	m_source_image_existence.set(name, true);
}
	
void TextureSource::rebuildImagesAndTextures()
{
	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	/*// Oh well... just clear everything, they'll load sometime.
	m_atlaspointer_cache.clear();
	m_name_to_id.clear();*/

	video::IVideoDriver* driver = m_device->getVideoDriver();
	
	// Remove source images from textures to disable inheriting textures
	// from existing textures
	/*for(u32 i=0; i<m_atlaspointer_cache.size(); i++){
		SourceAtlasPointer *sap = &m_atlaspointer_cache[i];
		sap->atlas_img->drop();
		sap->atlas_img = NULL;
	}*/
	
	// Recreate textures
	for(u32 i=0; i<m_atlaspointer_cache.size(); i++){
		SourceAtlasPointer *sap = &m_atlaspointer_cache[i];
		video::IImage *img =
			generate_image_from_scratch(sap->name, m_device, &m_sourcecache);
		// Create texture from resulting image
		video::ITexture *t = NULL;
		if(img)
			t = driver->addTexture(sap->name.c_str(), img);
		video::ITexture *t_old = sap->a.atlas;
		// Replace texture
		sap->a.atlas = t;
		sap->a.pos = v2f(0,0);
		sap->a.size = v2f(1,1);
		sap->a.tiled = 0;
		sap->atlas_img = img;
		sap->intpos = v2s32(0,0);
		sap->intsize = img->getDimension();

		if (t_old != 0)
			driver->removeTexture(t_old);
	}
}

void TextureSource::buildMainAtlas(class IGameDef *gamedef) 
{
	assert(gamedef->tsrc() == this);
	INodeDefManager *ndef = gamedef->ndef();

	infostream<<"TextureSource::buildMainAtlas()"<<std::endl;

	//return; // Disable (for testing)
	
	video::IVideoDriver* driver = m_device->getVideoDriver();
	assert(driver);

	JMutexAutoLock lock(m_atlaspointer_cache_mutex);

	// Create an image of the right size
	core::dimension2d<u32> max_dim = driver->getMaxTextureSize();
	core::dimension2d<u32> atlas_dim(2048,2048);
	atlas_dim.Width  = MYMIN(atlas_dim.Width,  max_dim.Width);
	atlas_dim.Height = MYMIN(atlas_dim.Height, max_dim.Height);
	video::IImage *atlas_img =
			driver->createImage(video::ECF_A8R8G8B8, atlas_dim);
	//assert(atlas_img);
	if(atlas_img == NULL)
	{
		errorstream<<"TextureSource::buildMainAtlas(): Failed to create atlas "
				"image; not building texture atlas."<<std::endl;
		return;
	}

	/*
		Grab list of stuff to include in the texture atlas from the
		main content features
	*/

	std::set<std::string> sourcelist;

	for(u16 j=0; j<MAX_CONTENT+1; j++)
	{
		if(j == CONTENT_IGNORE || j == CONTENT_AIR)
			continue;
		const ContentFeatures &f = ndef->get(j);
		for(u32 i=0; i<6; i++)
		{
			std::string name = f.tiledef[i].name;
			sourcelist.insert(name);
		}
	}
	
	infostream<<"Creating texture atlas out of textures: ";
	for(std::set<std::string>::iterator
			i = sourcelist.begin();
			i != sourcelist.end(); ++i)
	{
		std::string name = *i;
		infostream<<"\""<<name<<"\" ";
	}
	infostream<<std::endl;

	// Padding to disallow texture bleeding
	// (16 needed if mipmapping is used; otherwise less will work too)
	s32 padding = 16;
	s32 column_padding = 16;
	s32 column_width = 256; // Space for 16 pieces of 16x16 textures

	/*
		First pass: generate almost everything
	*/
	core::position2d<s32> pos_in_atlas(0,0);
	
	pos_in_atlas.X = column_padding;
	pos_in_atlas.Y = padding;

	for(std::set<std::string>::iterator
			i = sourcelist.begin();
			i != sourcelist.end(); ++i)
	{
		std::string name = *i;

		// Generate image by name
		video::IImage *img2 = generate_image_from_scratch(name, m_device,
				&m_sourcecache);
		if(img2 == NULL)
		{
			errorstream<<"TextureSource::buildMainAtlas(): "
					<<"Couldn't generate image \""<<name<<"\""<<std::endl;
			continue;
		}

		core::dimension2d<u32> dim = img2->getDimension();

		// Don't add to atlas if image is too large
		core::dimension2d<u32> max_size_in_atlas(64,64);
		if(dim.Width > max_size_in_atlas.Width
		|| dim.Height > max_size_in_atlas.Height)
		{
			infostream<<"TextureSource::buildMainAtlas(): Not adding "
					<<"\""<<name<<"\" because image is large"<<std::endl;
			continue;
		}

		// Wrap columns and stop making atlas if atlas is full
		if(pos_in_atlas.Y + dim.Height > atlas_dim.Height)
		{
			if(pos_in_atlas.X > (s32)atlas_dim.Width - column_width - column_padding){
				errorstream<<"TextureSource::buildMainAtlas(): "
						<<"Atlas is full, not adding more textures."
						<<std::endl;
				break;
			}
			pos_in_atlas.Y = padding;
			pos_in_atlas.X += column_width + column_padding*2;
		}
		
		/*infostream<<"TextureSource::buildMainAtlas(): Adding \""<<name
				<<"\" to texture atlas"<<std::endl;*/

		// Tile it a few times in the X direction
		u16 xwise_tiling = column_width / dim.Width;
		if(xwise_tiling > 16) // Limit to 16 (more gives no benefit)
			xwise_tiling = 16;
		for(u32 j=0; j<xwise_tiling; j++)
		{
			// Copy the copy to the atlas
			/*img2->copyToWithAlpha(atlas_img,
					pos_in_atlas + v2s32(j*dim.Width,0),
					core::rect<s32>(v2s32(0,0), dim),
					video::SColor(255,255,255,255),
					NULL);*/
			img2->copyTo(atlas_img,
					pos_in_atlas + v2s32(j*dim.Width,0),
					core::rect<s32>(v2s32(0,0), dim),
					NULL);
		}

		// Copy the borders a few times to disallow texture bleeding
		for(u32 side=0; side<2; side++) // top and bottom
		for(s32 y0=0; y0<padding; y0++)
		for(s32 x0=0; x0<(s32)xwise_tiling*(s32)dim.Width; x0++)
		{
			s32 dst_y;
			s32 src_y;
			if(side==0)
			{
				dst_y = y0 + pos_in_atlas.Y + dim.Height;
				src_y = pos_in_atlas.Y + dim.Height - 1;
			}
			else
			{
				dst_y = -y0 + pos_in_atlas.Y-1;
				src_y = pos_in_atlas.Y;
			}
			s32 x = x0 + pos_in_atlas.X;
			video::SColor c = atlas_img->getPixel(x, src_y);
			atlas_img->setPixel(x,dst_y,c);
		}

		for(u32 side=0; side<2; side++) // left and right
		for(s32 x0=0; x0<column_padding; x0++)
		for(s32 y0=-padding; y0<(s32)dim.Height+padding; y0++)
		{
			s32 dst_x;
			s32 src_x;
			if(side==0)
			{
				dst_x = x0 + pos_in_atlas.X + dim.Width*xwise_tiling;
				src_x = pos_in_atlas.X + dim.Width*xwise_tiling - 1;
			}
			else
			{
				dst_x = -x0 + pos_in_atlas.X-1;
				src_x = pos_in_atlas.X;
			}
			s32 y = y0 + pos_in_atlas.Y;
			s32 src_y = MYMAX((int)pos_in_atlas.Y, MYMIN((int)pos_in_atlas.Y + (int)dim.Height - 1, y));
			s32 dst_y = y;
			video::SColor c = atlas_img->getPixel(src_x, src_y);
			atlas_img->setPixel(dst_x,dst_y,c);
		}

		img2->drop();

		/*
			Add texture to caches
		*/
		
		bool reuse_old_id = false;
		u32 id = m_atlaspointer_cache.size();
		// Check old id without fetching a texture
		std::map<std::string, u32>::iterator n;
		n = m_name_to_id.find(name);
		// If it exists, we will replace the old definition
		if(n != m_name_to_id.end()){
			id = n->second;
			reuse_old_id = true;
			/*infostream<<"TextureSource::buildMainAtlas(): "
					<<"Replacing old AtlasPointer"<<std::endl;*/
		}

		// Create AtlasPointer
		AtlasPointer ap(id);
		ap.atlas = NULL; // Set on the second pass
		ap.pos = v2f((float)pos_in_atlas.X/(float)atlas_dim.Width,
				(float)pos_in_atlas.Y/(float)atlas_dim.Height);
		ap.size = v2f((float)dim.Width/(float)atlas_dim.Width,
				(float)dim.Width/(float)atlas_dim.Height);
		ap.tiled = xwise_tiling;

		// Create SourceAtlasPointer and add to containers
		SourceAtlasPointer nap(name, ap, atlas_img, pos_in_atlas, dim);
		if(reuse_old_id)
			m_atlaspointer_cache[id] = nap;
		else
			m_atlaspointer_cache.push_back(nap);
		m_name_to_id[name] = id;
			
		// Increment position
		pos_in_atlas.Y += dim.Height + padding * 2;
	}

	/*
		Make texture
	*/
	video::ITexture *t = driver->addTexture("__main_atlas__", atlas_img);
	assert(t);

	/*
		Second pass: set texture pointer in generated AtlasPointers
	*/
	for(std::set<std::string>::iterator
			i = sourcelist.begin();
			i != sourcelist.end(); ++i)
	{
		std::string name = *i;
		if(m_name_to_id.find(name) == m_name_to_id.end())
			continue;
		u32 id = m_name_to_id[name];
		//infostream<<"id of name "<<name<<" is "<<id<<std::endl;
		m_atlaspointer_cache[id].a.atlas = t;
	}

	/*
		Write image to file so that it can be inspected
	*/
	/*std::string atlaspath = porting::path_user
			+ DIR_DELIM + "generated_texture_atlas.png";
	infostream<<"Removing and writing texture atlas for inspection to "
			<<atlaspath<<std::endl;
	fs::RecursiveDelete(atlaspath);
	driver->writeImageToFile(atlas_img, atlaspath.c_str());*/
}

video::IImage* generate_image_from_scratch(std::string name,
		IrrlichtDevice *device, SourceImageCache *sourcecache)
{
	/*infostream<<"generate_image_from_scratch(): "
			"\""<<name<<"\""<<std::endl;*/
	
	video::IVideoDriver* driver = device->getVideoDriver();
	assert(driver);

	/*
		Get the base image
	*/

	video::IImage *baseimg = NULL;

	char separator = '^';

	// Find last meta separator in name
	s32 last_separator_position = name.find_last_of(separator);
	//if(last_separator_position == std::npos)
	//	last_separator_position = -1;

	/*infostream<<"generate_image_from_scratch(): "
			<<"last_separator_position="<<last_separator_position
			<<std::endl;*/

	/*
		If separator was found, construct the base name and make the
		base image using a recursive call
	*/
	std::string base_image_name;
	if(last_separator_position != -1)
	{
		// Construct base name
		base_image_name = name.substr(0, last_separator_position);
		/*infostream<<"generate_image_from_scratch(): Calling itself recursively"
				" to get base image of \""<<name<<"\" = \""
                <<base_image_name<<"\""<<std::endl;*/
		baseimg = generate_image_from_scratch(base_image_name, device,
				sourcecache);
	}
	
	/*
		Parse out the last part of the name of the image and act
		according to it
	*/

	std::string last_part_of_name = name.substr(last_separator_position+1);
	//infostream<<"last_part_of_name=\""<<last_part_of_name<<"\""<<std::endl;
	
	// Generate image according to part of name
	if(!generate_image(last_part_of_name, baseimg, device, sourcecache))
	{
		errorstream<<"generate_image_from_scratch(): "
				"failed to generate \""<<last_part_of_name<<"\""
				<<std::endl;
		return NULL;
	}
	
	return baseimg;
}

bool generate_image(std::string part_of_name, video::IImage *& baseimg,
		IrrlichtDevice *device, SourceImageCache *sourcecache)
{
	video::IVideoDriver* driver = device->getVideoDriver();
	assert(driver);

	// Stuff starting with [ are special commands
	if(part_of_name.size() == 0 || part_of_name[0] != '[')
	{
		video::IImage *image = sourcecache->getOrLoad(part_of_name, device);

		if(image == NULL)
		{
			if(part_of_name != ""){
				errorstream<<"generate_image(): Could not load image \""
						<<part_of_name<<"\""<<" while building texture"<<std::endl;
				errorstream<<"generate_image(): Creating a dummy"
						<<" image for \""<<part_of_name<<"\""<<std::endl;
			}

			// Just create a dummy image
			//core::dimension2d<u32> dim(2,2);
			core::dimension2d<u32> dim(1,1);
			image = driver->createImage(video::ECF_A8R8G8B8, dim);
			assert(image);
			/*image->setPixel(0,0, video::SColor(255,255,0,0));
			image->setPixel(1,0, video::SColor(255,0,255,0));
			image->setPixel(0,1, video::SColor(255,0,0,255));
			image->setPixel(1,1, video::SColor(255,255,0,255));*/
			image->setPixel(0,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			/*image->setPixel(1,0, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(0,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));
			image->setPixel(1,1, video::SColor(255,myrand()%256,
					myrand()%256,myrand()%256));*/
		}

		// If base image is NULL, load as base.
		if(baseimg == NULL)
		{
			//infostream<<"Setting "<<part_of_name<<" as base"<<std::endl;
			/*
				Copy it this way to get an alpha channel.
				Otherwise images with alpha cannot be blitted on 
				images that don't have alpha in the original file.
			*/
			core::dimension2d<u32> dim = image->getDimension();
			baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
			image->copyTo(baseimg);
		}
		// Else blit on base.
		else
		{
			//infostream<<"Blitting "<<part_of_name<<" on base"<<std::endl;
			// Size of the copied area
			core::dimension2d<u32> dim = image->getDimension();
			//core::dimension2d<u32> dim(16,16);
			// Position to copy the blitted to in the base image
			core::position2d<s32> pos_to(0,0);
			// Position to copy the blitted from in the blitted image
			core::position2d<s32> pos_from(0,0);
			// Blit
			/*image->copyToWithAlpha(baseimg, pos_to,
					core::rect<s32>(pos_from, dim),
					video::SColor(255,255,255,255),
					NULL);*/
			blit_with_alpha(image, baseimg, pos_from, pos_to, dim);
		}
		//cleanup
		image->drop();
	}
	else
	{
		// A special texture modification

		/*infostream<<"generate_image(): generating special "
				<<"modification \""<<part_of_name<<"\""
				<<std::endl;*/
		
		/*
			This is the simplest of all; it just adds stuff to the
			name so that a separate texture is created.

			It is used to make textures for stuff that doesn't want
			to implement getting the texture from a bigger texture
			atlas.
		*/
		if(part_of_name == "[forcesingle")
		{
			// If base image is NULL, create a random color
			if(baseimg == NULL)
			{
				core::dimension2d<u32> dim(1,1);
				baseimg = driver->createImage(video::ECF_A8R8G8B8, dim);
				assert(baseimg);
				baseimg->setPixel(0,0, video::SColor(255,myrand()%256,
						myrand()%256,myrand()%256));
			}
		}
		/*
			[crackN
			Adds a cracking texture
		*/
		else if(part_of_name.substr(0,6) == "[crack")
		{
			if(baseimg == NULL)
			{
				errorstream<<"generate_image(): baseimg==NULL "
						<<"for part_of_name=\""<<part_of_name
						<<"\", cancelling."<<std::endl;
				return false;
			}
			
			// Crack image number and overlay option
			s32 progression = 0;
			bool use_overlay = false;
			if(part_of_name.substr(6,1) == "o")
			{
				progression = stoi(part_of_name.substr(7));
				use_overlay = true;
			}
			else
			{
				progression = stoi(part_of_name.substr(6));
				use_overlay = false;
			}

			// Size of the base image
			core::dimension2d<u32> dim_base = baseimg->getDimension();
			
			/*
				Load crack image.

				It is an image with a number of cracking stages
				horizontally tiled.
			*/
			video::IImage *img_crack = sourcecache->getOrLoad(
					"crack_anylength.png", device);
		
			if(img_crack && progression >= 0)
			{
				// Dimension of original image
				core::dimension2d<u32> dim_crack
						= img_crack->getDimension();
				// Count of crack stages
				s32 crack_count = dim_crack.Height / dim_crack.Width;
				// Limit progression
				if(progression > crack_count-1)
					progression = crack_count-1;
				// Dimension of a single crack stage
				core::dimension2d<u32> dim_crack_cropped(
					dim_crack.Width,
					dim_crack.Width
				);
				// Create cropped and scaled crack images
				video::IImage *img_crack_cropped = driver->createImage(
						video::ECF_A8R8G8B8, dim_crack_cropped);
				video::IImage *img_crack_scaled = driver->createImage(
						video::ECF_A8R8G8B8, dim_base);

				if(img_crack_cropped && img_crack_scaled)
				{
					// Crop crack image
					v2s32 pos_crack(0, progression*dim_crack.Width);
					img_crack->copyTo(img_crack_cropped,
							v2s32(0,0),
							core::rect<s32>(pos_crack, dim_crack_cropped));
					// Scale crack image by copying
					img_crack_cropped->copyToScaling(img_crack_scaled);
					// Copy or overlay crack image
					if(use_overlay)
					{
						overlay(baseimg, img_crack_scaled);
					}
					else
					{
						/*img_crack_scaled->copyToWithAlpha(
								baseimg,
								v2s32(0,0),
								core::rect<s32>(v2s32(0,0), dim_base),
								video::SColor(255,255,255,255));*/
						blit_with_alpha(img_crack_scaled, baseimg,