-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDofusMapParser.php
More file actions
416 lines (383 loc) · 14.4 KB
/
DofusMapParser.php
File metadata and controls
416 lines (383 loc) · 14.4 KB
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
<?php
/*
* This file is part of PHP Map parser.
*
* PHP Map parser 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 3 of the License, or (at your option) any later version.
*
* PHP Map parser 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 PHP Map parser.
* If not, see <https://www.gnu.org/licenses/>.
*
* Copyright (C) 2019-2025 Vincent Quatrevieux (quatrevieux.vincent@gmail.com)
*/
namespace Arakne\MapParser;
use Arakne\MapParser\Loader\Map;
use Arakne\MapParser\Loader\MapCoordinates;
use Arakne\MapParser\Loader\MapLoader;
use Arakne\MapParser\Loader\MapStructure;
use Arakne\MapParser\Renderer\Layer\LayerRendersBuilder;
use Arakne\MapParser\Renderer\MapRenderer;
use Arakne\MapParser\Renderer\MapRendererInterface;
use Arakne\MapParser\Sprite\Cache\InMemorySpriteCache;
use Arakne\MapParser\Sprite\Cache\SpriteCacheInterface;
use Arakne\MapParser\Sprite\SpriteRepositoryInterface;
use Arakne\MapParser\Sprite\SwfSpriteRepository;
use Arakne\MapParser\Tile\Cache\NullTileCache;
use Arakne\MapParser\Tile\Cache\TileCacheInterface;
use Arakne\MapParser\Tile\TileMapCoordinates;
use Arakne\MapParser\Tile\TileRendererInterface;
use Arakne\MapParser\WorldMap\CombinedWorldMapTileRenderer;
use Arakne\MapParser\WorldMap\SwfWorldMap;
use Arakne\MapParser\WorldMap\WorldMapTileRenderer;
use Arakne\Swf\SwfFile;
use Closure;
use GdImage;
use InvalidArgumentException;
use function glob;
use function is_int;
/**
* Facade for parsing and rendering Dofus maps.
*
* Usage:
* ```php
* // Configure the parser
* $mapParser = new DofusMapParser(
* dofusPath: '/path/to/dofus',
* mapsPath: '/srv/www/dofus/maps', // Optional, by default will use maps from the client
* mapByCoordinates: function (MapCoordinates $coordinates, int $superAreaId) use ($pdo) {
* // Get the map ID from the database using coordinates
* $stmt = $pdo->prepare('SELECT id FROM maps WHERE x = ? AND y = ? AND super_area_id = ?');
* $stmt->execute([$coordinates->x, $coordinates->y, $superAreaId]);
*
* $id = $stmt->fetchColumn();
*
* return $id !== false ? (int) $id : null;
* },
* // Configure caches
* tileCache: new SqliteTileCache(__DIR__ . '/var/cache/tiles.db'),
* spriteCache: new SqliteSpriteCache(__DIR__ . '/var/cache/sprites.db'),
* layersConfigurator: function (LayerRendersBuilder $layers) {
* // Configure here the layers to render (for example, enable grid)
* $layers->enableGrid();
* },
* attachmentsProviders: [
* function (MapStructure $structure) {
* // Get map data from the database using map ID
* $stmt = $pdo->prepare('SELECT * FROM maps WHERE id = ?');
* $stmt->execute([$structure->id]);
* $row = $stmt->fetch();
*
* // Map is not found
* if ($row === false) {
* return [];
* }
*
* return [
* new MapKey($row['key']),
* new MapCoordinates($row['x'], $row['y']),
* // Other attachments like map name, super area, etc.
* ];
* },
* ],
* );
*
* // Parse map data
* $map = $mapParser->load(1302);
*
* foreach ($map->cells as $cell) {
* // You can now access cell properties
* if ($cell->isTeleport) {
* // ...
* }
* }
*
* // Render a map as PNG
* $img = $mapParser->render(1302);
* header('Content-Type: image/png');
* imagepng($img);
*
* // Render world map tile (using leaflet for example)
* $tileRenderer = $mapParser->incarnamWorldMap();
* $img = $tileRenderer->render((int) $_GET['x'], (int) $_GET['y'], (int) $_GET['z']);
* header('Content-Type: image/png');
* imagepng($img);
*
* // Find POIs on the world map using bounding box
* $tileRenderer = $mapParser->incarnamWorldMap();
* $bbox = LatLongBounds::fromString($_GET['bbox']); // bbox=west,south,east,north
*
* // Get map coordinates to load
* $bounds = $tileRenderer->coordinate->toMapBounds($bbox);
* $points = [];
*
* // Load POIs for each map in the bounding box
* for ($x = $bounds->xMin; $x <= $bounds->xMax; $x++) {
* for ($y = $bounds->yMin; $y <= $bounds->yMax; $y++) {
* $map = $mapRepository->findMapByCoords($x, $y);
*
* if ($map) {
* $loadedMap = $mapParser->load($map->id);
* foreach ($mapRepository->findMapPois($map) as $poi) {
* // Get the POI position in latitude/longitude, so it can be displayed by leaflet
* $pos = $tileRenderer->coordinate->cellToLatLong($map, $poi->cellId);
*
* if ($pos) {
* $points[] = [
* 'name' => $poi->name,
* 'type' => $poi->type,
* 'lat' => $pos->latitude,
* 'long' => $pos->longitude,
* ];
* }
* }
* }
* }
* }
*
* // Display POIs as JSON
* header('Content-Type: application/json');
* echo json_encode($points);
* ```
*/
final class DofusMapParser
{
public const int AMAKNA_SUPERAREA_ID = 0;
public const int INCARNAM_SUPERAREA_ID = 3;
/**
* Get ground sprites repository.
*/
public private(set) SpriteRepositoryInterface $grounds {
get => $this->grounds ??= new SwfSpriteRepository(
glob($this->dofusPath . '/clips/gfx/g*.swf') ?: [],
cache: $this->spriteCache->withNamespace('grounds'),
);
}
/**
* Get object sprites repository.
*/
public private(set) SpriteRepositoryInterface $objects {
get => $this->objects ??= new SwfSpriteRepository(
glob($this->dofusPath . '/clips/gfx/o*.swf') ?: [],
cache: $this->spriteCache->withNamespace('objects'),
);
}
public private(set) MapRendererInterface $renderer {
get {
if (isset($this->renderer)) {
return $this->renderer;
}
$layers = new LayerRendersBuilder($this->grounds, $this->objects);
if ($this->layersConfigurator !== null) {
($this->layersConfigurator)($layers);
}
return $this->renderer = new MapRenderer($layers->build());
}
}
public readonly MapLoader $loader;
/**
* @param list<callable(MapStructure):list<object>> $attachmentsProviders List of attachments providers to add to the map.
*/
public function __construct(
/**
* Path to the dofus client directory.
*/
private readonly string $dofusPath,
/**
* Path to the maps SWF files.
* If null, defaults to "$dofusPath/data/maps".
*/
private readonly ?string $mapsPath = null,
/**
* Closure used to load a map by its coordinates.
* This value must be set if you want to use world map rendering with actual game maps.
*
* It takes as first parameter the map coordinates, and as second parameter super area ID.
* It can return either:
* - an integer: the map ID to load
* - a SwfFile: the SWF file to load
* - a MapStructure: the pre-loaded map structure
*
* @var Closure(MapCoordinates, int):(int|SwfFile|MapStructure|null)|null
*/
private readonly ?Closure $mapByCoordinates = null,
/**
* Cache implementation to use for tile rendering.
* Only used when rendering world maps.
*/
private readonly TileCacheInterface $tileCache = new NullTileCache(),
/**
* Cache implementation to use for sprites.
*/
private readonly SpriteCacheInterface $spriteCache = new InMemorySpriteCache(100),
/**
* Custom configuration for renderer layers.
*
* Example:
* ```php
* $parser = new DofusMapParser(
* // ...
* layersConfigurator: function (LayerRendersBuilder $layers) use ($pnjRenderer) {
* $layers
* ->enableGrid()
* ->set(LayerRendersBuilder::GRID_LAYER + 10, $pnjRenderer) // Render PNJ above grid
* ;
* },
* // ...
* );
* ```
*
* @var Closure(LayerRendersBuilder):void|null
*/
private readonly ?Closure $layersConfigurator = null,
/**
* List of attachments providers to add to the map.
* Use this to provides the map key and coordinates automatically.
*
* @param list<callable(MapStructure):list<object>> $attachmentsProviders
* @var list<callable(MapStructure):list<object>> $attachmentsProviders
*/
array $attachmentsProviders = [],
) {
$this->loader = new MapLoader(attachmentsProviders: $attachmentsProviders);
}
/**
* Render a map to a GD image.
*
* Usage:
* ```php
* // Render map with ID 1302
* $img = $parser->render(1302);
*
* // Display the image in the browser
* header('Content-Type: image/png');
* imagepng($img);
* ```
*
* @param int|SwfFile|MapStructure $map The map to render, either as an ID, a SWF file, or a pre-loaded MapStructure.
*
* @return GdImage The rendered map as a GD image.
* @throws InvalidArgumentException If the map ID is invalid or the SWF file cannot be loaded.
*/
public function render(int|SwfFile|MapStructure $map): GdImage
{
return $this->renderer->render($this->load($map) ?? throw new InvalidArgumentException('Map not found'));
}
/**
* Load and parse a map
*
* Usage:
* ```php
* $map = $parser->load(1302); // Load map with ID 1302
*
* // Now you can access map properties
* foreach ($map->cells as $cell) {
* if ($cell->isTeleport) {
* // ...
* }
* }
* ```
*
* @param int|SwfFile|MapStructure $map The map to load, either as an ID, a SWF file, or a pre-loaded MapStructure.
*
* @return Map|null The loaded map, or null if the map ID is not found.
*/
public function load(int|SwfFile|MapStructure $map): ?Map
{
if (!$struct = $this->toMapStructure($map)) {
return null;
}
return $this->loader->load($struct);
}
/**
* Get the tile renderer for incarnam world map.
* If {@see DofusMapParser::$mapByCoordinates} is set, both world map and game maps will be rendered.
*
* Usage:
* ```php
* $tileRenderer = $parser->incarnamWorldMap(6);
*
* header('Content-Type: image/png');
* imagepng($tileRenderer->render(new TileMapCoordinates($_GET['x'], $_GET['y'], $_GET['z'])));
* ```
*
* @param int $minZoomLevel Zoom level when the actual game maps starts to be renderer over world map.
* If negative or zero, it will be used as relative to maxZoom (so maxZoom + minZoomLevel)
* @return TileRendererInterface
*/
public function incarnamWorldMap(int $minZoomLevel = -2): TileRendererInterface
{
return $this->worldMap(self::INCARNAM_SUPERAREA_ID, $minZoomLevel);
}
/**
* Get the tile renderer for amakna world map.
* If {@see DofusMapParser::$mapByCoordinates} is set, both world map and game maps will be rendered.
*
* Usage:
* ```php
* $tileRenderer = $parser->amaknaWorldMap(7);
*
* header('Content-Type: image/png');
* imagepng($tileRenderer->render(new TileMapCoordinates($_GET['x'], $_GET['y'], $_GET['z'])));
* ```
* @param int $minZoomLevel Zoom level when the actual game maps starts to be renderer over world map
* If negative or zero, it will be used as relative to maxZoom (so maxZoom + minZoomLevel)
*
* @return TileRendererInterface
*/
public function amaknaWorldMap(int $minZoomLevel = -2): TileRendererInterface
{
return $this->worldMap(self::AMAKNA_SUPERAREA_ID, $minZoomLevel);
}
/**
* Get the tile renderer for the given super area world map.
* If {@see DofusMapParser::$mapByCoordinates} is set, both world map and game maps will be rendered.
*
* @param non-negative-int $superAreaId The super area ID to render (0 = Amakna, 3 = Incarnam, etc.)
* @param int $minZoomLevel Zoom level when the actual game maps starts to be renderer over world map
* If negative or zero, it will be used as relative to maxZoom (so maxZoom + minZoomLevel)
*
* @return TileRendererInterface
*/
public function worldMap(int $superAreaId, int $minZoomLevel = -2): TileRendererInterface
{
$worldMap = new SwfWorldMap(new SwfFile($this->dofusPath . '/clips/maps/' . $superAreaId . '.swf'));
if ($this->mapByCoordinates === null) {
return new WorldMapTileRenderer(
$worldMap,
cache: $this->tileCache->withNamespace('super_area_' . $superAreaId),
);
}
return new CombinedWorldMapTileRenderer(
$worldMap,
$this->renderer,
function (TileMapCoordinates $coordinates) use ($superAreaId) {
$ret = ($this->mapByCoordinates)(
new MapCoordinates($coordinates->x, $coordinates->y),
$superAreaId
);
return $ret !== null ? $this->toMapStructure($ret) : null;
},
$minZoomLevel,
$this->loader,
$this->tileCache->withNamespace('super_area_' . $superAreaId),
);
}
private function toMapStructure(int|SwfFile|MapStructure $map): ?MapStructure
{
if (is_int($map)) {
$filepath = glob(($this->mapsPath ?? $this->dofusPath . '/data/maps') . '/' . $map . '_*.swf')[0] ?? null;
if ($filepath === null) {
return null;
}
$map = new SwfFile($filepath);
}
if ($map instanceof SwfFile) {
$map = MapStructure::fromSwfFile($map);
}
return $map;
}
}