File: MapGenerator.cpp

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

#include "precompiled.h"

#include "MapGenerator.h"

#include "graphics/MapIO.h"
#include "graphics/Patch.h"
#include "graphics/Terrain.h"
#include "lib/status.h"
#include "lib/timer.h"
#include "lib/file/vfs/vfs_path.h"
#include "maths/MathUtil.h"
#include "ps/CLogger.h"
#include "ps/FileIo.h"
#include "ps/Future.h"
#include "ps/scripting/JSInterface_VFS.h"
#include "ps/TemplateLoader.h"
#include "scriptinterface/FunctionWrapper.h"
#include "scriptinterface/JSON.h"
#include "scriptinterface/Object.h"
#include "scriptinterface/ScriptContext.h"
#include "scriptinterface/ScriptConversions.h"
#include "scriptinterface/ScriptInterface.h"
#include "simulation2/helpers/MapEdgeTiles.h"

#include <boost/random/linear_congruential.hpp>
#include <set>
#include <string>
#include <vector>

namespace
{
constexpr const char* GENERATOR_NAME{"GenerateMap"};

bool MapGenerationInterruptCallback(JSContext* cx);

/**
 * Provides callback's for the JavaScript.
 */
class CMapGenerationCallbacks
{
public:
	// Only the constructor and the destructor are called by C++.

	CMapGenerationCallbacks(const StopToken stopToken, std::atomic<int>& progress,
		ScriptInterface& scriptInterface, Script::StructuredClone& mapData, const u16 flags) :
		m_StopToken{stopToken},
		m_Progress{progress},
		m_ScriptInterface{scriptInterface},
		m_MapData{mapData}
	{
		m_ScriptInterface.SetCallbackData(static_cast<void*>(this));

		// Enable the script to be aborted
		JS_AddInterruptCallback(m_ScriptInterface.GetGeneralJSContext(),
			&MapGenerationInterruptCallback);

		// Set initial seed, callback data.
		// Expose functions, globals and classes relevant to the map scripts.
#define REGISTER_MAPGEN_FUNC(func) \
	ScriptFunction::Register<&CMapGenerationCallbacks::func, \
		ScriptInterface::ObjectFromCBData<CMapGenerationCallbacks>>(rq, #func, flags);

		// VFS
		JSI_VFS::RegisterScriptFunctions_ReadOnlySimulationMaps(m_ScriptInterface, flags);

		// Globalscripts may use VFS script functions
		m_ScriptInterface.LoadGlobalScripts();

		// File loading
		ScriptRequest rq(m_ScriptInterface);
		REGISTER_MAPGEN_FUNC(LoadLibrary);
		REGISTER_MAPGEN_FUNC(LoadHeightmapImage);
		REGISTER_MAPGEN_FUNC(LoadMapTerrain);

		// Template functions
		REGISTER_MAPGEN_FUNC(GetTemplate);
		REGISTER_MAPGEN_FUNC(TemplateExists);
		REGISTER_MAPGEN_FUNC(FindTemplates);
		REGISTER_MAPGEN_FUNC(FindActorTemplates);

		// Progression and profiling
		REGISTER_MAPGEN_FUNC(SetProgress);
		REGISTER_MAPGEN_FUNC(GetMicroseconds);
		REGISTER_MAPGEN_FUNC(ExportMap);

		// Engine constants

		// Length of one tile of the terrain grid in metres.
		// Useful to transform footprint sizes to the tilegrid coordinate system.
		m_ScriptInterface.SetGlobal("TERRAIN_TILE_SIZE", static_cast<int>(TERRAIN_TILE_SIZE));

		// Number of impassable tiles at the map border
		m_ScriptInterface.SetGlobal("MAP_BORDER_WIDTH", static_cast<int>(MAP_EDGE_TILES));

#undef REGISTER_MAPGEN_FUNC
	}

	~CMapGenerationCallbacks()
	{
		JS_AddInterruptCallback(m_ScriptInterface.GetGeneralJSContext(), nullptr);
		m_ScriptInterface.SetCallbackData(nullptr);
	}

	StopToken m_StopToken;

private:

	// These functions are called by JS.

	/**
	 * Load all scripts of the given library
	 *
	 * @param libraryName VfsPath specifying name of the library (subfolder of ../maps/random/)
	 * @return true if all scripts ran successfully, false if there's an error
	 */
	bool LoadLibrary(const VfsPath& libraryName)
	{
		// Ignore libraries that are already loaded
		if (m_LoadedLibraries.find(libraryName) != m_LoadedLibraries.end())
			return true;

		// Mark this as loaded, to prevent it recursively loading itself
		m_LoadedLibraries.insert(libraryName);

		VfsPath path = VfsPath(L"maps/random/") / libraryName / VfsPath();
		VfsPaths pathnames;

		// Load all scripts in mapgen directory
		Status ret = vfs::GetPathnames(g_VFS, path, L"*.js", pathnames);
		if (ret == INFO::OK)
		{
			for (const VfsPath& p : pathnames)
			{
				LOGMESSAGE("Loading map generator script '%s'", p.string8());

				if (!m_ScriptInterface.LoadGlobalScriptFile(p))
				{
					LOGERROR("CMapGenerationCallbacks::LoadScripts: Failed to load script '%s'",
						p.string8());
					return false;
				}
			}
		}
		else
		{
			// Some error reading directory
			wchar_t error[200];
			LOGERROR(
				"CMapGenerationCallbacks::LoadScripts: Error reading scripts in directory '%s': %s",
				path.string8(),
				utf8_from_wstring(StatusDescription(ret, error, ARRAY_SIZE(error))));
			return false;
		}

		return true;
	}

	/**
	 * Finalize map generation and pass results from the script to the engine.
	 * The `data` has to be according to this format:
	 * https://gitea.wildfiregames.com/0ad/0ad/wiki/Random_Map_Generator_Internals#Dataformat
	 */
	void ExportMap(JS::HandleValue data)
	{
		// Copy results
		m_MapData = Script::WriteStructuredClone(ScriptRequest(m_ScriptInterface), data);
	}

	/**
	 * Load an image file and return it as a height array.
	 */
	JS::Value LoadHeightmapImage(const VfsPath& filename)
	{
		std::vector<u16> heightmap;
		if (LoadHeightmapImageVfs(filename, heightmap) != INFO::OK)
		{
			LOGERROR("Could not load heightmap file '%s'", filename.string8());
			return JS::UndefinedValue();
		}

		ScriptRequest rq(m_ScriptInterface);
		JS::RootedValue returnValue(rq.cx);
		Script::ToJSVal(rq, &returnValue, heightmap);
		return returnValue;
	}

	/**
	 * Load an Atlas terrain file (PMP) returning textures and heightmap.
	 *
	 * See CMapReader::UnpackTerrain, CMapReader::ParseTerrain for the reordering
	 */
	JS::Value LoadMapTerrain(const VfsPath& filename)
	{
		ScriptRequest rq(m_ScriptInterface);

		if (!VfsFileExists(filename))
		{
			ScriptException::Raise(rq, "Terrain file \"%s\" does not exist!",
				filename.string8().c_str());
			return JS::UndefinedValue();
		}

		CFileUnpacker unpacker;
		unpacker.Read(filename, "PSMP");

		if (unpacker.GetVersion() < CMapIO::FILE_READ_VERSION)
		{
			ScriptException::Raise(rq, "Could not load terrain file \"%s\" too old version!",
				filename.string8().c_str());
			return JS::UndefinedValue();
		}

		// unpack size
		ssize_t patchesPerSide = (ssize_t)unpacker.UnpackSize();
		size_t verticesPerSide = patchesPerSide * PATCH_SIZE + 1;

		// unpack heightmap
		std::vector<u16> heightmap;
		heightmap.resize(SQR(verticesPerSide));
		unpacker.UnpackRaw(&heightmap[0], SQR(verticesPerSide) * sizeof(u16));

		// unpack texture names
		size_t textureCount = unpacker.UnpackSize();
		std::vector<std::string> textureNames;
		textureNames.reserve(textureCount);
		for (size_t i = 0; i < textureCount; ++i)
		{
			CStr texturename;
			unpacker.UnpackString(texturename);
			textureNames.push_back(texturename);
		}

		// unpack texture IDs per tile
		ssize_t tilesPerSide = patchesPerSide * PATCH_SIZE;
		std::vector<CMapIO::STileDesc> tiles;
		tiles.resize(size_t(SQR(tilesPerSide)));
		unpacker.UnpackRaw(&tiles[0], sizeof(CMapIO::STileDesc) * tiles.size());

		// reorder by patches and store and save texture IDs per tile
		std::vector<u16> textureIDs;
		for (ssize_t x = 0; x < tilesPerSide; ++x)
		{
			size_t patchX = x / PATCH_SIZE;
			size_t offX = x % PATCH_SIZE;
			for (ssize_t y = 0; y < tilesPerSide; ++y)
			{
				size_t patchY = y / PATCH_SIZE;
				size_t offY = y % PATCH_SIZE;
				// m_Priority and m_Tex2Index unused
				textureIDs.push_back(tiles[(patchY * patchesPerSide + patchX) * SQR(PATCH_SIZE) +
					(offY * PATCH_SIZE + offX)].m_Tex1Index);
			}
		}

		JS::RootedValue returnValue(rq.cx);

		Script::CreateObject(
			rq,
			&returnValue,
			"height", heightmap,
			"textureNames", textureNames,
			"textureIDs", textureIDs);

		return returnValue;
	}

	/**
	 * Sets the map generation progress, which is one of multiple stages
	 * determining the loading screen progress.
	 */
	void SetProgress(int progress)
	{
		// When the task is started, `m_Progress` is only mutated by this thread.
		const int currentProgress = m_Progress.load();
		if (progress >= currentProgress)
			m_Progress.store(progress);
		else
			LOGWARNING("The random map script tried to reduce the loading progress from %d to %d",
				currentProgress, progress);
	}

	/**
	 * Microseconds since the epoch.
	 */
	double GetMicroseconds() const
	{
		return JS_Now();
	}

	/**
	 * Return the template data of the given template name.
	 */
	CParamNode GetTemplate(const std::string& templateName)
	{
		const CParamNode& templateRoot =
			m_TemplateLoader.GetTemplateFileData(templateName).GetOnlyChild();
		if (!templateRoot.IsOk())
			LOGERROR("Invalid template found for '%s'", templateName.c_str());

		return templateRoot;
	}

	/**
	 * Check whether the given template exists.
	 */
	bool TemplateExists(const std::string& templateName) const
	{
		return m_TemplateLoader.TemplateExists(templateName);
	}

	/**
	 * Returns all template names of simulation entity templates.
	 */
	std::vector<std::string> FindTemplates(const std::string& path, bool includeSubdirectories)
	{
		return m_TemplateLoader.FindTemplates(path, includeSubdirectories, SIMULATION_TEMPLATES);
	}

	/**
	 * Returns all template names of actors.
	 */
	std::vector<std::string> FindActorTemplates(const std::string& path, bool includeSubdirectories)
	{
		return m_TemplateLoader.FindTemplates(path, includeSubdirectories, ACTOR_TEMPLATES);
	}

	/**
	 * Current map generation progress.
	 */
	std::atomic<int>& m_Progress;

	/**
	 * Provides the script context.
	 */
	ScriptInterface& m_ScriptInterface;

	/**
	 * Result of the mapscript generation including terrain, entities and environment settings.
	 */
	Script::StructuredClone& m_MapData;

	/**
	 * Currently loaded script librarynames.
	 */
	std::set<VfsPath> m_LoadedLibraries;

	/**
	 * Backend to loading template data.
	 */
	CTemplateLoader m_TemplateLoader;
};

bool MapGenerationInterruptCallback(JSContext* cx)
{
	return !ScriptInterface::ObjectFromCBData<CMapGenerationCallbacks>(
		ScriptInterface::CmptPrivate::GetScriptInterface(cx))->m_StopToken.IsStopRequested();
}
} // anonymous namespace

Script::StructuredClone RunMapGenerationScript(const StopToken stopToken, std::atomic<int>& progress,
	ScriptInterface& scriptInterface, const VfsPath& script, const std::string& settings, const u16 flags)
{
	ScriptRequest rq(scriptInterface);

	// Parse settings
	JS::RootedValue settingsVal(rq.cx);
	if (!Script::ParseJSON(rq, settings, &settingsVal) && settingsVal.isUndefined())
	{
		LOGERROR("RunMapGenerationScript: Failed to parse settings");
		return nullptr;
	}

	// Prevent unintentional modifications to the settings object by random map scripts
	if (!Script::DeepFreezeObject(rq, settingsVal))
	{
		LOGERROR("RunMapGenerationScript: Failed to deepfreeze settings");
		return nullptr;
	}

	// Init RNG seed
	u32 seed = 0;
	if (!Script::HasProperty(rq, settingsVal, "Seed") ||
		!Script::GetProperty(rq, settingsVal, "Seed", seed))
		LOGWARNING("RunMapGenerationScript: No seed value specified - using 0");

	boost::rand48 mapGenRNG{seed};
	scriptInterface.ReplaceNondeterministicRNG(mapGenRNG);

	Script::StructuredClone mapData;
	CMapGenerationCallbacks callbackData{stopToken, progress, scriptInterface, mapData, flags};

	// Copy settings to global variable
	JS::RootedValue global(rq.cx, rq.globalValue());
	if (!Script::SetProperty(rq, global, "g_MapSettings", settingsVal, flags & JSPROP_READONLY,
		flags & JSPROP_ENUMERATE))
	{
		LOGERROR("RunMapGenerationScript: Failed to define g_MapSettings");
		return nullptr;
	}

	// Load RMS
	LOGMESSAGE("Loading RMS '%s'", script.string8());
	if (!scriptInterface.LoadGlobalScriptFile(script))
	{
		LOGERROR("RunMapGenerationScript: Failed to load RMS '%s'", script.string8());
		return nullptr;
	}

	LOGMESSAGE("Run RMS generator");
	bool hasGenerator;
	JS::RootedObject globalAsObject{rq.cx, &JS::HandleValue{global}.toObject()};
	if (!JS_HasProperty(rq.cx, globalAsObject, GENERATOR_NAME, &hasGenerator))
	{
		LOGERROR("RunMapGenerationScript: failed to search `%s`.", GENERATOR_NAME);
		return nullptr;
	}

	if (mapData != nullptr)
	{
		LOGWARNING("The map generation script called `Engine.ExportMap` that's deprecated. The "
			"generator based interface should be used.");
		if (hasGenerator)
			LOGWARNING("The map generation script contains a `%s` but `Engine.ExportMap` was already "
				"called. `%s` isn't called, preserving the old behavior.", GENERATOR_NAME,
				GENERATOR_NAME);
		return mapData;
	}

	JS::RootedValue map{rq.cx, ScriptFunction::RunGenerator(rq, global, GENERATOR_NAME, settingsVal,
		[&](const JS::HandleValue value)
		{
			int tempProgress;
			if (!Script::FromJSVal(rq, value, tempProgress))
				throw std::runtime_error{"Failed to convert the yielded value to an "
					"integer."};
			progress.store(tempProgress);
		})};

	JS::RootedValue exportedMap{rq.cx};
	const bool exportSuccess{ScriptFunction::Call(rq, map, "MakeExportable", &exportedMap)};
	return Script::WriteStructuredClone(rq, exportSuccess ? exportedMap : map);
}