4. The asset pack with many compatible tiles causes the map to collapse into local areas. This is doesn't allow you to make complex and beautiful patterns.
5. A little part of assets from "Real land" asset pack. An image will be created with simple and repeatable patterns.
- The map generation application is located in the directory
src/App/
- The application Backend and frontend is located in folders
src/backend/
andsrc/frontend/
. They are not part of the map generation application and its are used to only for demonstration purposes only. - The entry point is located in the folder
src/public
. Generation assets is in thesrc/public/assets/
and new generated images are in thesrc/public/saved/
. - The
tests/Functional/
andtests/Unit/
folders contain the application's Feature and Unit tests, respectively.
Path - src/App/Asset/Asset.php
The asset class is responsible for the operation of single asset that will be part of the generated map.
The name of single asset must follow the template below:
##_##_##_##_##_##
or short version if all asset sides are of the same type:
##_##_##
if the second ##
is equals 1
Underscore is used as delimiter _
Each ##
has its own meaning depending on the position:
- position 0 - the title type (not type of side), for example, it can be: corners, roads, rivers, mountains etc.
- position 1 - all sides of an asset are of the same type (1) or different (2)
- position 2 - the type of the top side (full version of the description) / the type of all sides (for short version of the description)
- position 3 - the type of the right side (full version of the description)
- position 4 - the type of the bottom side (full version of the description)
- position 5 - the type of the left side (full version of the description)
AssetsCollection is used to working with the group of assets. It's necessary to get the assets collection that will be used to generate the current map.
AssetFolder is used to working with one folder with assets.
AssetFolderCollection is used to get a collection of folders with assets.
This is an example of the Map Generator's implementation according to a certain algorithm. In this case it's a Simple Tile Model that compares all sides of the current asset to the sides of other assets. After a certain number of correct tiles are selected, a specific tile from this group is randomly selected.
This is the object that consist of many other small tiles. Each single tile in the map has its own coordinates and its own asset. The map also has dimension of X by Y tiles.
This is part for a map that has its own asset, its own dimension in pixels, the type of each side and the coordinates in the map.
MapSaver is the helper class for saving a map as an image with different types (jpg, png, webp). It's also possible to save the map as divided images or one single image.
Here are the following components:
route.php
- the Symfony component for handling requests coming from frontend.Controllers/
- all controllers that redirect requests to appropriate services.Services/
- this is the logic components for Map Generator application that is required for the frontend to work properly.
- Project setup (without Docker, if you have Apache/NGINX webserver and PHP above 7.4 version):
- Clone the repository:
git clone git@github.com:quoterbox/php-2d-location-generator.git
- Install required packages from Composer:
composer install
- In most cases, you can start the project from your web sever at http://localhost:8080 or another address that depends on your web server.
- Also, you can start the project without the frontend at
http://localhost:8080/index_no_frontend.php
- Clone the repository:
- Developing:
- NPM and NodeJS is required to build the frontend.
- Install NPM dependencies:
npm install
- Use one of the commands from
package.json
to build the frontend, for example:npm run dev
илиnpm run prod
. - More frontend build settings can be set in the
webpack.mix.js
file using a wrapper over Webpack - Laravel-mix.
- Tests:
- Use this command to start tests:
composer test
- Use this command to start tests:
2. Простые ассеты 100 на 100 пикселей. В большинстве случаев возникают коллизии, из-за неполного набора ассетов:
4. Ассеты с множеством подхдящих друг к другу тайлов создают карту, которая быстро "схлапывается" в локальные области и не позволяет создать сложные визуальные структуры.
5. Сильно сокращенное количество ассетов из 3-го набора. В итоге генерируется однообразная и простая карта.
- Само приложение генерации карт находится в папке
src/App/
- Backend и frontend приложения находится, соответственно, в папках
src/backend/
иsrc/frontend/
. Они не являются частью приложения-генератора и служат только для демонстрации его работы. - В папке
src/public
находится точка входа, ассеты для генерации (src/public/assets/
) и сохраняемые карты при генерации (src/public/saved/
). - В папках
tests/Functional/
иtests/Unit/
находятся, соответственно, функциональные и юнит тесты приложения.
Путь - src/App/Asset/Asset.php
Отвечает за работу каждого отдельного ассета, который будет являться частью сгенерированной карты.
Наименование ассетов должно следовать шаблону:
##_##_##_##_##_##
или укороченная версия, когда все стороны одного типа
##_##_##
если 2-й параметр равен 1
В качестве разделителя используется символ нижнего подчеркивания _
Каждая группа ##
имеет свое значение в зависимости от позиции:
- position 0 - тип тайла (не путать с типом стороны тайла), например это могут быть: угол, прямая, река, поле, горы и тд.
- position 1 - все стороны ассета одного типа (1) или разного (0)
- position 2 - тип верхней стороны (для полного описания) / тип всех сторон (для краткой версии)
- position 3 - тип правой стороны (для полного описания)
- position 4 - тип нижней стороны (для полного описания)
- position 5 - тип левой стороны (для полного описания)
Отвечает за работу группы ассетов, необходим для получения коллекции ассетов, которые будут использоваться для генерации текущей карты.
Отвечает за работу с одной папкой с ассетами.
Отвечает за получение коллекции папок с ассетами.
Пример реализации генератора карты по определенному алгоритму. В данном случае это простая тайловая модель, которая подбирает каждый тайл для карты смотря на стороны соседних тайлов. После того, как отобрано некоторое количество подходящих тайлов, случайным образом происходит выбор конкретного тайла.
Объект, который состоит из множества других - тайлов. Каждый тайл в карте имеет свои координаты и свой ассет. Карта также имеет размерность X на Y тайлов.
Составная часть для карты, имеющая свой ассет, свои размеры в пикселях, тип каждой стороны и координаты в составе карты.
Вспомогательный класс для сохранения карты ввиде изображения произвольного формата. Также есть возможность сохранять карту в ввиде отдельных тайлов или одним файлом.
Здесь находятся:
route.php
- содежит компоненты роутинга Symfony, для обработки запросов поступаемых от фронтенда.Controllers/
- содержит все контроллеры, перенаправляющие запросы на соответствующие сервисы.Services/
- содержит логику работы примера приложения генератора карт, которая необходима для правильной работы фронтенда.
- Установка проекта (без Docker, если у вас есть Apache/NGINX webserver и PHP не ниже 7.4):
- Клонируйте репозиторий:
git clone git@github.com:quoterbox/php-2d-location-generator.git
- Установите все требуемые пакеты из Composer:
composer install
- Запустить проект обычно можно из вашего веб сервера по адресу http://localhost:8080 либо другим аналогичным способом.
- Вы можете запустить проект без фронтенда по адресу
http://localhost:8080/index_no_frontend.php
- Клонируйте репозиторий:
- Разработка:
- Для сборки фронтенда вам необходимо установить менеджер пакетов NPM и сервер NodeJS
- Установите зависимости NPM:
npm install
- Для билда фронтенда можно использовать одну из команд из файла package.json, например,
npm run dev
илиnpm run prod
- Более подробные настройки билда фронтенда можно установить в файле webpack.mix.js иcпользующем обертку над Webpack - Laravel-mix
- Тесты:
- Тесты запускаются простой командой:
composer test
- Тесты запускаются простой командой: